Ibo
Ibo

Reputation: 93

Ocaml summing up values in an integer list

I'm facing a syntax error in the code below:

let sum list =
let current_sum = List.hd list in
for i = 1 to List.length list - 1 do
let counter = List.nth list i
    current_sum = current_sum + counter 
done;;

The error that I'm facing is here

done;
^^^^
Error: Syntax error

The code is supposed to sum up the current values of the list at each iteration, for example

sum [1;2;3;4];;
- : int list = [1; 3; 6; 10]

So I think I'm going about this in the right direction, what I don't understand is why this error keeps popping up?

Upvotes: 4

Views: 5061

Answers (2)

Pierre G.
Pierre G.

Reputation: 4441

The keyword in is missing in the let counter statement.

Another error that will pop after : current_sum is immutable. You will have to change this.

Another way to achieve your sum : use List.fold function.

Putting in shape the comments below :

let sum_l l = 
   let (r,_) = List.fold_left 
      (fun (a_l, a_i) x -> ((a_i + x) :: a_l , a_i+x))
      ([],0) l in
   List.rev r;;

Upvotes: 6

Richard-Degenne
Richard-Degenne

Reputation: 2959

You have simply forgotten the in keywork in your line 4.

However, OCaml is a functional language, and you're trying to use an imperative method here.

Even though it will work when you solve your syntax error, it is not the way you would do this in OCaml. For example, a function summing up the elements of a integer list can be done with the following:

let sum = List.fold_left (+) 0;;

or even

let sum = List.reduce ~f:(+);;

if you're using the Core library.

EDIT

After reading the comments under another answer, I've understood what you're really trying to do:

# sum [1;2;3;4];;
- : int list = [1; 3; 6; 10]

And here is a way to do so, using OCaml's functional features:

let sum l =
  let sums =
    List.fold_left (fun l x -> match l with
      | [] -> [x]
      | h::t -> (x+h)::l) [] l
  in List.rev sums;;

The code is more complicated than just computing the sum itself, but it does the trick.

Upvotes: 4

Related Questions