如何在Scheme中获取值的类型?

Mat*_*ick 16 scheme types dynamic

我想要一个在运行时获取值类型的函数.使用示例:

(get-type a)
Run Code Online (Sandbox Code Playgroud)

其中adefineð是一些任意的计划值.

我该怎么做呢?还是我这个实现自己使用的堆栈COND boolean?,number?等等?

Chr*_*ung 13

在使用类似Tiny-CLOS的对象系统的Scheme实现中,您可以使用class-of.这是使用Swindle在Racket中的示例会话:

$ 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>
Run Code Online (Sandbox Code Playgroud)

与使用GOOPS的Guile类似:

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>
Run Code Online (Sandbox Code Playgroud)


Sam*_*adt 12

在Racket中,您可以使用describe来自PLaneT的Doug Williams的软件包.它的工作原理如下:

> (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)
Run Code Online (Sandbox Code Playgroud)


Joh*_*nts 7

这里的所有答案都是有帮助的,但我认为人们忽略了解释为什么这可能很难; Scheme标准不包括静态类型系统,因此不能说值只有一个"类型".事物在子类型中变得有趣(例如数字与浮点数)和联合类型(你给一个返回数字或字符串的函数提供什么类型?).

如果您更多地描述了您想要的用途,您可能会发现有更多具体的答案会对您有所帮助.

  • 他说"在运行时",所以这与静态类型无关.这是他追求的动态(运行时)类型的值 (5认同)

ewe*_*ein 5

要检查某事物的类型,只需在类型后添加一个问号,例如检查 x 是否为数字:

(define get-Type
  (lambda (x)
    (cond ((number? x) "Number")
          ((pair? x) "Pair")
          ((string? x) "String")
          ((list? x) "List")))) 
Run Code Online (Sandbox Code Playgroud)

继续。

  • OP 特别询问是否有替代这种方法的方法。另外,为什么在可以使用 `cond` 的情况下使用嵌套的 `if`s?\*笨蛋\* (7认同)