I'm trying to construct a list in OCaml only using List.map
, List.filter
, and anonymous functions.
What I want to get is this:
- : int list list = [[2; 2]; [5; 5; 5; 5; 5]; [7; 7; 7; 7; 7; 7; 7]; [3; 3; 3];
2
[12; 12; 12; 12; 12; 12; 12; 12; 12; 12; 12; 12]; [4; 4; 4; 4]; ... ]
from this list
let entiers = [2; 5; 7; 3; 12; 4; 9; 2; 11];;
What i've tried so far:
List.map (fun n acc -> acc = n if acc = 0 then [] else n :: fun n acc -1 ) entiers;;
But i'm getting a syntax error, so i'm kinded of stuck...
Can someone help me to solve this problem ? Thank you !
As @ChristopheRiolo comments, it looks like you're trying to define an anonymous function that is recursive. This is very difficult, as you really need the name of the function for it to call itself recursively.
In particular, it looks like this fragment:
fun n (acc - 1)
is intended as a recursive call. However, this is not a function call at all but the beginning of definition of a new (inner) anonymous function. (This is the source of the syntax error since it's not a valid lambda definition.)
It will work much better if you define the function to be mapped ouside the call to map
, as a function with a name.
Something very roughly like this:
let rec helper n =
if n = 0 then [] else n :: helper (n - 1)
in
List.map helper ...
(This definition of helper is probably not correct; I'm just trying to show the general layout you might want to use.)