【发布时间】:2014-12-20 04:15:26
【问题描述】:
这段简单的代码难倒我
所以这行得通
> let l = [1; 2; 3; 4];;
val l : int list = [1; 2; 3; 4]
> List.reduce(fun accm i -> accm + i) l;;
val it : int = 10
但这不是(即使逻辑完全相同)
> let l = [("a", 1); ("b", 2); ("c", 3); ("d", 4)];;
val l : (string * int) list = [("a", 1); ("b", 2); ("c", 3); ("d", 4)]
> List.reduce(fun accm tup -> accm + (snd tup)) l;;
List.reduce(fun accm tup -> accm + (snd tup)) l;;
>stdin(46,47): error FS0001: The type 'int' does not match the type 'string * int'
为什么我会收到此错误,因为代码很简单。遍历列表,获取元组并将其与累加器的值一起传递给 reduce 函数。
在函数内部从元组中取出第二个值并将其添加到累加器中。
我知道可能有很多其他方法可以得到我想要的……但我想知道为什么上面的代码不起作用?
【问题讨论】:
标签: f# f#-interactive f#-3.0