Search code examples
ocamlfold

OCaml: Using fold_right to implement map


I am trying to implement map using List.fold_right in OCaml, in which my function has the same signature and behaviour as List.map. I am not allowed to use pattern matching or any other list functions.

Example:

SIGNATURE: fold_map: ('a -> 'b) -> 'b list -> 'b list = <fun>


EXAMPLE: fold_map (fun x -> x + 1) [1; 2; 3; 4; 5] = [2; 3; 4; 5; 6]

My attempt:

let fold_map f =
  List.fold_right(fun x acc -> (f x) :: acc) []

This type checks, however, when I run my function on the example, it returns the original list. I am not sure why this is happening, so any clarification would be appreciated.

The problem is taken from the forums of Coursera's programming languages course, which is in SML.


Solution

  • Check the List.fold_right documentation. It first takes the list to fold on and then the initial value. Therefore, your code is folding over the empty list and immediately returns the initial value, which is the list that you really want to fold over.