Your idea is correct, but your syntax for expressing it is wrong. This function:
# fun acc element -> let acc = element;;
Error: Syntax error
Isn't correct (as you've probably noticed).
To define a function that returns a value expr
:
fun a b -> <expr>
Your expression should have the value b
. So your function would look like this:
fun a b -> b
(With possible renamings.)
Another way to look at your problem is that when you use let
as an expression, it needs an in
. So you could write the function like this (though it's redundant):
fun a b -> let a = b in a
However, this form seems to be a result of thinking imperatively. You're not assigning a new value to a
. You're just returning a value.
The following function is completely identical; it just renames the second a
to something else:
fun a b -> let zzz = b in zzz
Generally speaking in OCaml you want to give up the idea of assigning values to variables. They are immutable and can't change value (generally speaking).
Update
Here's a session showing that fun a b -> b
will solve the problem.
$ ocaml
OCaml version 4.00.1
# List.fold_left (fun a b -> b) 0 [2; 3; 4; 88];;
- : int = 88
One thing that's easy to forget is that you need to supply a starting value for the accumulator. One obvious choice is the first element of the list. (There must be a first element; an empty list doesn't have a last element.)