E.g. if you have a function (fun x -> x+1) and you want to map it to [1; 2; 3]. But you only want to map it when x=1, so that the output is [2; 2; 3]. How do you do this?
Using OCaml, I tried:
let rec foo (input : int list) : int list =
match input with
| [] -> []
| hd::tl -> List.map (fun x -> if x=1 then (x+1)) input;;
And I’ve tried ‘when’ statements, but to no avail.
An
elsebranch is missing here.You’re almost there. You just need to make a complete if/else statement:
if x=1 then (x+1) else xOCaml requires a return value on any branch of above expression.
To be clear,
whenguard is irrelevant here because it is used for conditional pattern matching. Since pattern matching is redundant in this case, your function could be shortened quite a lot: