Functional programming SML咖喱(功能程序)?
几天前我问过这个问题,但现在我对这个问题有了更多的了解。但我仍然遇到一个问题,运算符和操作数不一致: 使用ListPair.foldr,我需要创建一个函数zipWith,它将两两列表组合在一起。整体功能的类型应为:Functional programming SML咖喱(功能程序)?,functional-programming,sml,currying,fold,Functional Programming,Sml,Currying,Fold,几天前我问过这个问题,但现在我对这个问题有了更多的了解。但我仍然遇到一个问题,运算符和操作数不一致: 使用ListPair.foldr,我需要创建一个函数zipWith,它将两两列表组合在一起。整体功能的类型应为: zipWith : ('a * 'b -> 'c) -> 'a list -> 'b list -> 'c list ListPair.foldr : ('a * 'b * 'c -> 'c) -> 'c -> 'a list * 'b l
zipWith : ('a * 'b -> 'c) -> 'a list -> 'b list -> 'c list
ListPair.foldr : ('a * 'b * 'c -> 'c) -> 'c -> 'a list * 'b list -> 'c
- zipWith (fn (x, y) => x + y) [1,2,3,4] [10,20,30,40];
val it = [11,22,33,44] : int list
我的尝试:
fun zipWith xs ys = ListPair.foldr(zipWith(x,y,z) => (x+y)::z) 0 xs ys
在您的尝试中,有几件事是错误的:
zipWith
,但类型表示第一个参数必须是函数,因此将其更改为带f xs ys的zipWith
fn : ('a * 'b * 'c -> 'c) -> 'c -> 'a list * 'b list -> 'c
第一个参数是具有以下类型的函数:
fn : 'a * 'b * 'c -> 'c
让我们制作一个玩具函数作为示例:
fun foo (a, b, acc) = a+b :: acc
此函数获取两个数字和一个列表,将两个数字相加,将它们放在列表前面,然后返回。类型为:
fn : int * int * int list -> int list
这与ListPair.foldr的第一个参数中的类型签名非常吻合
现在,让我们看看ListPair.foldr foo
的类型
fn : int list -> int list * int list -> int list
下一个参数是一个int列表-折叠的起始值。太好了,我们已经发现这是一张空名单。ListPair.foldr foo[]
的类型为:
fn : int list * int list -> int list
最后一个参数是包含两个列表的元组。我们放入一些随机列表,并在sml解释器中试用:
- ListPair.foldr foo [] ([1,2,3],[10,20,30])
> val it = [11, 22, 33] : int list
现在,您所需要做的就是用zipWith中的参数替换ListPair.foldr(foo和两个随机列表)的参数,您就完成了。查看我对类似问题的答案好的,谢谢,我很接近hahaThanks的解释。我想出来了。