How do I get the type of a value in Scheme?

前端 未结 4 1616
情话喂你
情话喂你 2021-01-01 13:58

I want a function that gets the type of a value at runtime. Example use:

(get-type a)

where a has been defined t

相关标签:
4条回答
  • 2021-01-01 14:23

    In Scheme implementations with a Tiny-CLOS-like object system, you can just use class-of. Here's a sample session in Racket, using Swindle:

    $ racket -I swindle
    Welcome to Racket v5.2.1.
    -> (class-of 42)
    #<primitive-class:exact-integer>
    -> (class-of #t)
    #<primitive-class:boolean>
    -> (class-of 'foo)
    #<primitive-class:symbol>
    -> (class-of "bar")
    #<primitive-class:immutable-string>
    

    And similarly with Guile using GOOPS:

    scheme@(guile-user)> ,use (oop goops)
    scheme@(guile-user)> (class-of 42)
    $1 = #<<class> <integer> 14d6a50>
    scheme@(guile-user)> (class-of #t)
    $2 = #<<class> <boolean> 14c0000>
    scheme@(guile-user)> (class-of 'foo)
    $3 = #<<class> <symbol> 14d3a50>
    scheme@(guile-user)> (class-of "bar")
    $4 = #<<class> <string> 14d3b40>
    
    0 讨论(0)
  • 2021-01-01 14:39

    In Racket, you can use the describe package by Doug Williams from PLaneT. It works like this:

    > (require (planet williams/describe/describe))
    > (variant (λ (x) x))
    'procedure
    > (describe #\a)
    #\a is the character whose code-point number is 97(#x61) and
    general category is ’ll (letter, lowercase)
    
    0 讨论(0)
  • 2021-01-01 14:46

    All of the answers here are helpful, but I think that people have neglected to explain why this might be hard; the Scheme standard doesn't include a static type system, so values can't be said to have just one "type". Things get interesting in and around subtypes (e.g. number vs floating-point-number) and union types (what type do you give to a function that returns either a number or a string?).

    If you describe your desired use a bit more, you might discover that there are more specific answers that will help you more.

    0 讨论(0)
  • 2021-01-01 14:46

    To check the type of something just add a question mark after the type, for example to check if x is a number:

    (define get-Type
      (lambda (x)
        (cond ((number? x) "Number")
              ((pair? x) "Pair")
              ((string? x) "String")
              ((list? x) "List")))) 
    

    Just continue with that.

    0 讨论(0)
提交回复
热议问题