Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through first n elements of array in OCaml

Tags:

arrays

ocaml

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.

  1. How can I fix this function definition? How can I specify that I want the value of sum_array returned?
  2. How can I get OCaml to report more helpful error messages?
like image 720
James Taylor Avatar asked Jan 22 '26 09:01

James Taylor


1 Answers

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.)

like image 170
Jeffrey Scofield Avatar answered Jan 25 '26 09:01

Jeffrey Scofield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!