2

我对 F# 和学习列表很陌生。我很难尝试实现自己的 reduce 函数。我一直在尝试实现这一点。这是我到目前为止所拥有的,但是我收到一个错误,当调用 reduce 时说我传入的列表是 type 是 int 类型,但应该是 type 'a list. 我对此感到非常沮丧,所以欢迎任何帮助。

这是我的代码的样子:

let reduce Fn (list: 'a list) = 
      let rec innerFun list acc =
          match list with
          | (x::xs) :: xss ->
              let newAcc = Fn x xs // the fn applied to the head and the next element
              innerFun xss newAcc // recurse through the list with new accumulator
          | [] -> acc // if the list is empty return the accumulator
      innerFun list 0 
               
   //Calling reduce            
   let red2 = reduce (fun x y -> x*y) [23; 4]

4

1 回答 1

2

您遇到的直接问题实际上非常简单且纯粹是语法:

match list with
| (x::xs) :: xss ->

括号使得模式匹配列表的列表,即x::xs是列表的头元素,x并且xs分别是它的头和尾。

你想要的是匹配列表前面的两个元素 - 你需要删除括号:

match list with
| a::b::tail ->

请注意,您使用的命名约定已经有一个提示 - sinxs表示复数 - 因此在该模式中,您将列表拆分为“ex”的头部和“exes”的尾部。

于 2020-10-11T17:26:12.797 回答