我在OCaml中有以下函数,它将c作为参数传递的数组中的第一个元素相加:
let rec sum_array c a =
if c < 0 then 0
else a.(c) + sum_array (c - 1) a;;
Run Code Online (Sandbox Code Playgroud)
我碰巧知道数组a是高级的,所以我想设置它.我试过了:
fun c -> let int_array = [| 1 ; 2 ; 3 ; 4 ; 5 |] in
let rec sum_array c =
if c < 0 then 0
else int_array.(c) + sum_array (c - 1);;
Run Code Online (Sandbox Code Playgroud)
但OCaml抱怨模糊的"错误:语法错误",这是非常有用的.
sum_array返回的值?在某种意义上,你的问题是你fun c -> ...在错误的地方添加.
假设你有这样的功能:
let f count =
(count + 72 - 1) / 72
Run Code Online (Sandbox Code Playgroud)
如果您想象硬编码值72是您想要预先计算的,您可以按如下方式重写该函数:
let f =
let line_length = 72 in
fun count -> (count + line_length - 1) / line_length
Run Code Online (Sandbox Code Playgroud)
您的代码将数组放在函数体之前,但它应该在它内部,在let新的内部函数定义之间.
你的情况特别棘手,因为你的函数是递归的.所以你无法切换到fun c -> ...表单.相反,您可以在本地保留原始的基于let的定义.对于人为的例子,它看起来像这样:
let f =
let line_length = 72 in
let inner_f count =
(count + line_length - 1) / line_length
in
inner_f
Run Code Online (Sandbox Code Playgroud)
(作为旁注,你的代码总结了数组的第一个c + 1元素,而不是前c个元素.)