1

为什么我必须使用 switch 将 typeof 转换为字符串才能使其工作?

这不起作用:

  typeof: type? get 'optional
  switch typeof [
    word! [
      print "word"
    ] 
    string! [
      print "string"
    ]           
  ]

这有效:

  typeof: type? get 'optional
  switch to-string typeof [
    "word" [
      print "word"
    ] 
    "string" [
      print "string"
    ]           
  ]
4

1 回答 1

1
开关类型?/字:可选[
    单词![打印“单词”]
    细绳![打印“字符串”]
]

或者

开关类型?:可选减少[
    单词![打印“单词”]
    细绳![打印“字符串”]
]

原因是 REBOL 不会减少(“评估”)switch 语句中的情况。如果没有/word细化,type?函数会返回 a datatype!,但 switch 语句会尝试将其与 a 匹配,但word!它失败了。

我意识到这可能会令人困惑,因此您最好的选择是将类型转换为字符串(就像您所做的那样),或者使用我建议的两个习语之一。我更喜欢第一个,使用type?/word.

于 2009-10-11T19:18:34.317 回答