I wanted to have a tail-recursive version of List.map
, so I wrote my own. Here it is:
let rec list_map f l ?(accum=[])=
match l with
head :: tail -> list_map f tail ~accum:(head :: accum)
| [] -> accum;;
Whenever I compile this function, I get:
File "main.ml", line 69, characters 29-31:
Warning X: this optional argument cannot be erased.
The tutorial says that this means that I'm trying to create a function with no non-optional arguments. But the function above clearly takes non-optional arguments.
I'm probably just doing something really dumb, but what?
The previous solutions do compile, but won't give the expected result. The function
f
is never applied to the arguments. A correct code is:The inferred type is:
... in contrast to the wrong one:
Please note, that the result list is reversed:
... and equals the function rev_list from the List module:
So you may want to change your function into:
... which should be tail-recursive as well (according to the manual) and returns the list in the original order: