【发布时间】:2016-02-20 03:19:26
【问题描述】:
我对 SML 有一点经验,我正在尝试制作扫描仪。我被困在以下代码中。任何帮助表示赞赏。
- fun nextChar nil = NONE
| nextChar (head::tail) = SOME (head, tail);
- val a = [#"a",#"b",#"d",#"c"];
- val (head, tail) = nextChar a;
我收到关于模式和表达式返回类型不匹配的错误。有人可以指出我可以使用哪种模式来匹配表达式返回类型。
错误:
stdIn:7.5-7.28 Error: pattern and expression in val dec don't agree [tycon mismatch]
pattern: 'Z * 'Y
expression: (char * char list) option
in declaration:
(head,tail) = nextChar a
stdIn:7.5-7.28 Warning: type vars not generalized because of
value restriction are instantiated to dummy types (X1,X2,...)
stdIn:7.5-7.28 Warning: type vars not generalized because of
value restriction are instantiated to dummy types (X1,X2,...)
【问题讨论】:
-
nextChar a返回SOME (#"a", [#"b", #"d", #"c"]),并且这个值的类型(char × char list)选项)永远不会和val (head,tail) = ...中的模式类型统一(即'a × 'b)。如果你写了val SOME (head, tail) = nextChar a,它会起作用,但不建议在 let 绑定中解构SOME/NONE,因为一种模式会排除另一种模式并导致运行时异常。相反,您应该使用 case-of。
标签: pattern-matching sml type-mismatch