【发布时间】:2019-05-04 03:15:45
【问题描述】:
我仍在尝试了解 fold_left 的具体工作原理。它会像List.iter 这样遍历列表吗?还是我的代码有其他问题?我认为 e 是列表中的元素(所以它是一个元组),fst e 采用元组的第一个元素,snd e 采用元组中的第二个元素。
let rec pow x n =
if n < 0 then
0
else if n = 0 then
1
else
x * pow x (n - 1);;
let polynomial lst = function
| x -> List.fold_left (fun e -> (fst e) * (pow x (snd e))) 1 lst;;
lst 是一个元组列表,其中每个元组有两个整数并构成一个多项式函数,因此多项式应该返回一个函数。所以应该发生的一个例子是这样的
# let f = polynomial [3, 3; -2, 1; 5, 0];;
val f : int -> int = <fun>
# f 2;; (* f is the polynomial function f(x) = 3x^3 + (-2)x + 5 *)
- : int = 25
但我收到此错误消息
“错误:此表达式的类型为 int,但表达式应为 'a -> int * int”类型。
【问题讨论】:
标签: ocaml