I wrote a function, which adds all elements from the given list:
let rec add = function []->0 | h::t->h+add(t);;
Now I want to write the same function, but using List.fold_left
, but I tried several changes but I still have an error. First I tried this:
let rec add = function []->0 | h::t-> add List.fold_left((fun h t-> h+t) h t);;
But I had an error, and I noticed that List.fold_left returns an int value so the recursion is unnecessary. So I changed for:
let add = function []->0 | h::t -> List.fold_left ( fun h t-> h+t h t);;
But I still getting error about wrong type :
Error: This expression has type int -> 'a -> 'b
but an expression was expected of type 'a
But I don't know how to fix that, can anybody explain my how to use List.fold_left
in this example?