【发布时间】:2012-07-19 18:14:48
【问题描述】:
我想要一个在运行时获取值类型的函数。使用示例:
(get-type a)
其中a 一直是defined 是一些任意的Scheme 值。
我该怎么做?还是我必须自己实现这个,使用boolean?、number? 等的条件堆栈?
【问题讨论】:
我想要一个在运行时获取值类型的函数。使用示例:
(get-type a)
其中a 一直是defined 是一些任意的Scheme 值。
我该怎么做?还是我必须自己实现这个,使用boolean?、number? 等的条件堆栈?
【问题讨论】:
在具有类似 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>
与使用 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>
【讨论】:
在 Racket 中,您可以使用来自 PLaneT 的 Doug Williams 的 describe 包。它的工作原理是这样的:
> (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)
【讨论】:
这里的所有答案都很有帮助,但我认为人们忽略了解释为什么这可能很难; Scheme 标准不包括静态类型系统,因此不能说值只有一种“类型”。子类型(例如数字与浮点数)和联合类型(您为返回数字或字符串的函数提供什么类型?)中和周围的事情变得有趣。
如果您更多地描述您想要的用途,您可能会发现有更具体的答案可以为您提供更多帮助。
【讨论】:
′procedure。
要检查某事物的类型,只需在类型后添加一个问号,例如检查 x 是否为数字:
(define get-Type
(lambda (x)
(cond ((number? x) "Number")
((pair? x) "Pair")
((string? x) "String")
((list? x) "List"))))
请继续。
【讨论】:
cond,为什么还要使用嵌套的ifs? *难以置信*
(get-Type (car (string->list (number->string 5)))),这不会返回任何内容。
character?。为了完整起见,还有vector?。