我建立一个函数,给定一个组合列表,返回两个名单:多类型列表
let rec split2 l =
match l with
[] -> ([], [])
| (x, y)::ls -> let (xs, ys) =
split ls in (x::xs, y::ys);;
val split2 : l:('a * 'b) list -> 'a list * 'b list
lsts = [('a', 1); ('b', 2); ('c', 3); ('d', 4)]
split2 lsts;;
val it : int list * char list = ([1; 2; 3; 4], ['a'; 'b'; 'c'; 'd'])
现在,我申请的概念,更复杂的列表:
let l1 = [('a', 1, 'a'); ('b', 2, 'b'); ('c', 3, 'c'); ('d', 4, 'd')]
功能我使用类型的问题,所以我建立第二个。在这种情况下,我已经仔细地定义了类型,但是即使编译时它仍然会返回错误l1
。
let rec split3 (l:(char * int * char) list) =
match l with
[] -> ([], [], [])
| (x, y, z)::ls ->
let (xs, ys, zs) =
split3 ls in (xs, ys, zs);;
val split3 : l:(char * int * char) list -> 'a list * 'b list * 'c list
split3 l1;;
error FS0030: Value restriction. The value 'it' has been inferred to
have generic type val it : '_a list * '_b list * '_c list
Either define 'it' as a simple data term, make it a function with explicit
arguments or, if you do not intend for it to be generic, add a type annotation.
为什么,即使类型声明,它需要进一步的类型注释?
是的。这让我想到了第二个问题:第一个例子中的'two elements'列表和第二个'three elements'列表有什么不同?它们都是由字符和整数组成的,毕竟。 – Worice
对不起,我的第一个评论是无关紧要的。编译器不能推断函数的返回类型。您可以明确指出:'let rec split3(l:(char * int * char)list):(char list * int list * char list)=' – Petr
更多关于值限制错误,因为它有时很难理解:https: //blogs.msdn.microsoft.com/mulambda/2010/05/01/finer-points-of-f-value-restriction/ – Petr