Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 527

Difference between two kinds of recursive function

$
0
0

In OCaml, there are two ways I have seen to write a map function for example

let rec map f xs =  match xs with  | [] -> []  | x::rest -> f x :: map f rest

and

let map f xs =  let rec go xs =     match xs with    | [] -> []    | x::rest -> f x :: go rest  in go xs

The second one looks like more optimizing because it is similar to loop invariant elimination but in functional programming it may involve allocating a new closure. Can anyone explain the difference between the two styles of recursive function, in particular in terms of performance? Thanks for your help!

I couldn't find similar questions in SO and I'm expecting there is a term like "recursive invariant elimination" to describe the kind of transformation from the first program to the second one.


Viewing all articles
Browse latest Browse all 527

Trending Articles