-1

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.

coder
  • 9
  • 3
  • 1
    You've switched the the order of the initial value and the list to fold over, so that you pass the original list as the initial value and fold over the empty list, thereby returning the initial value/original list. – glennsl Oct 17 '20 at 07:57

1 Answers1

1

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.

ivg
  • 34,431
  • 2
  • 35
  • 63