I have the following function in OCaml which sums the first c elements in an array passed as an argument:
let rec sum_array c a =
if c < 0 then 0
else a.(c) + sum_array (c - 1) a;;
I happen to know what the array a is in advanced, so I'd like to set this. I tried:
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);;
But OCaml complains with an ambiguous 'Error: Syntax error', which is super helpful.
sum_array returned?In some sense your problem is that you're adding fun c -> ... in the wrong place.
Say you had a function like this:
let f count =
(count + 72 - 1) / 72
If you imagine that the hard-coded value 72 is something you would like to pre-calculate, you can rewrite the function as follows:
let f =
let line_length = 72 in
fun count -> (count + line_length - 1) / line_length
Your code is placing the array before the body of the function, but it should be inside it, between the let and a new inner function definition.
Your case is particularly tricky because your function is recursive. So you can't switch over to the fun c -> ... form. Instead you can retain the original let-based definition locally. For the contrived example, it would look like this:
let f =
let line_length = 72 in
let inner_f count =
(count + line_length - 1) / line_length
in
inner_f
(As a side comment, your code sums the first c+1 elements of the array, not the first c elements.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With