Using fold to sum all ASCII values of characters in a list OCAML

ocaml

#1

I am trying to implement “List.fold_left” to compute the ASCII values of each character in a list (e.g [‘a’;‘b’;‘A’]) and then add them up.

let ascii_sum lst = List.fold_left (fun elem acc -> Char.code(elem) + … ) 0 lst

In the "…’ of my code, I was thinking of a way to move on to the next element of my accumulator, compute its ASCII value and then add its value to the current Char.code(elem). I may not understand how to implement fold_left correctly, especially I am not quite sure to understand what (fun …) is in Ocaml, so any input from you will be helpful for me.

Thank you!


#2

There are already some good answers to this question on StackOverflow: https://stackoverflow.com/questions/48656558/using-fold-to-sum-all-ascii-values-of-characters-in-a-list-ocaml/48657093


#3

The (fun a b -> ...) in ocaml is how you define a lambda - an anonymous function. Basically the following 3 code styles are equivalent.

let f = fun acc elem -> Char.code elem + acc in 
List.fold_left f 0 lst 

or

let f acc elem = Char.code elem + acc in 
List.fold_left f 0 lst 

or

List.fold_left (fun acc elem -> Char.code elem + acc) 0 lst 

I think it is a typo in your original question, but in List.fold_left the lambda function takes acc as a first argument and elem as the second.

in the "…’ of my code, I was thinking of a way to move on to the next element of my accumulator, compute its ASCII value and then add its value to the current Char.code(elem).

List.fold_left is a list iterator function already so you don’t need to move on to the next element. Ocaml is an expression based language. What this means in practice is that when you define a function (named or lambda) you don’t explicitly return a value. The compiler automatically infers it for you based on the last expression in your function. In our example, the returned value(type) is int since (+) returns an int.

If it helps, you could read List.fold_left (fun acc elem -> Char.code elem + acc) 0 lst as follows:
List.fold_left iterates over the list lst and applies lambda function (fun acc alem -> ... ) to each element elem of lst and acc. The acc is initialized to 0 and holds the result of successive application of lambda function. The acc is returned when the iteration is complete.