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

帅比萌擦擦* 提交于 2019-12-03 20:40:52

问题


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

(get-type a)

where a has been defined to be some arbitrary Scheme value.

How do I do this? Or do I have to implement this myself, using a cond stack of boolean?, number? etc. ?


回答1:


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>



回答2:


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)



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/11566886/how-do-i-get-the-type-of-a-value-in-scheme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!