我想要一个在运行时获取值类型的函数。例如使用:如何获得Scheme中的值类型?
(get-type a)
其中a
一直define
d是一些任意方案的值。
我如何做到这一点?或者我必须自己实现这个,使用一个boolean?
,number?
等cond栈?
我想要一个在运行时获取值类型的函数。例如使用:如何获得Scheme中的值类型?
(get-type a)
其中a
一直define
d是一些任意方案的值。
我如何做到这一点?或者我必须自己实现这个,使用一个boolean?
,number?
等cond栈?
在具有Tiny-CLOS类对象系统的Scheme实现中,您可以使用class-of
。下面是在拍一个示例会话,使用诈骗:
$ 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:
[email protected](guile-user)> ,use (oop goops)
[email protected](guile-user)> (class-of 42)
$1 = #<<class> <integer> 14d6a50>
[email protected](guile-user)> (class-of #t)
$2 = #<<class> <boolean> 14c0000>
[email protected](guile-user)> (class-of 'foo)
$3 = #<<class> <symbol> 14d3a50>
[email protected](guile-user)> (class-of "bar")
$4 = #<<class> <string> 14d3b40>
要检查什么类型只需添加一个问号的类型后,例如要检查,如果x是一个数字:
(define get-Type
(lambda (x)
(cond ((number? x) "Number")
((pair? x) "Pair")
((string? x) "String")
((list? x) "List"))))
只是继续与。
球拍,你可以通过道格·威廉姆斯从地球使用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)
这个软件包确实很有帮助。我希望它是核心球拍的一部分。 – Salil 2013-06-01 02:39:55
这里的所有答案都有帮助,但我认为人们忽视了解释为什么这可能很难; Scheme标准不包含静态类型系统,所以值不能说只有一个“类型”。事物在子类型(例如数字和浮点数)和联合类型(对于返回一个数字或字符串的函数是什么类型?
如果您更多地描述您的使用需求,您可能会发现更多具体的答案可以帮助您更多。
他说“在运行时”,所以这与静态类型无关。这是他在 – newacct 2012-07-20 06:23:50
之后的动态(运行时)类型的值。您错过了John的观点,因为动态运行时类型并不总是有足够的信息来消除歧义。具体的例子:假设我有一个处理颜色和名称的程序。我可以选择只用字符串表示这些类型的值。然后,如果我看到“灰色”一词,则我没有足够的信息来区分该类型,因为我使用的是相同的表示形式。 – dyoo 2012-07-20 15:18:11
同上;你可以从我的帖子中删除“静态”这个词,它仍然是有道理的。丹尼的例子是一个很好的例子。事实上,C语言有相同的问题:没有“这个值的类型是什么”操作符,因为许多值具有相同的表示形式。 – 2012-07-23 13:00:24
该OP特别询问是否有替代方法。另外,为什么在使用'cond'时使用嵌套'if'? \ * boggles \ * – 2012-07-19 18:24:57
@ewein @Chris Jester-Young这是缺少的吗?对于'(get-Type(car(string-> list(number-> string 5))))'这不会返回任何东西。 – ArtB 2012-12-28 21:31:37
原来我的情况是缺失的是'character?'。为了完整起见,还有'vector?'。 – ArtB 2012-12-28 21:56:49