[英]Ocaml: recursion on a list of tuples
I have the following function table which takes a list of tuples (x's are strings and y's are a list of strings) and I want to return a tuple of x1 and the length of the list y1. 我有下面的函数表,其中包含一个元组列表(x是字符串,y是字符串列表),我想返回一个元组x1和列表y1的长度。 I tried it with this simple function: 我用这个简单的功能试了一下:
let rec table lst = function
| [] -> []
| [(x1, y1, x2, y2)] -> [(x1, (List.length y1))]
| (x1_h, y1_h, x2_h, y2_h) :: tail -> (x1_h, (List.length y1_h))::(table tail)
But the following error occured: 但是发生了以下错误:
Error: This expression has type ('a * 'b list * 'c * 'd) list -> ('a * int) list but an expression was expected of type ('a * int) list 错误:此表达式的类型为('a *'b list *'c *'d)list->('a * int)list,但是期望表达式为('a * int)list类型
I'm not really sure what I did wrong there. 我不确定自己在哪里做错了。
function
takes an argument implicitly and pattern matches on that. function
隐式地接受参数,并在其上进行模式匹配。 In other words: 换一种说法:
let f = function | ...
is equivalent to 相当于
let f lst = match lst with | ...
So when you write 所以当你写
let rec table lst = function | ...
That translates to 转化为
let rec table lst lst2 = match lst2 with | ...
The error points to the recursive call, table tail
, because it is partially applied and returns a function ('a * 'b list * 'c * 'd) list -> ('a * int)
. 错误指向递归调用table tail
,因为它被部分应用并返回一个函数('a * 'b list * 'c * 'd) list -> ('a * int)
。 table tail tail
would return ('a * int list)
as expected and is completely valid. table tail tail
将按预期方式返回('a * int list)
,并且完全有效。 But since lst
is unused in your function, you can just remove it instead. 但是由于lst
在您的函数中未使用,因此您可以删除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.