This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

Re: Map is not tail recursive
• Marc Rouaix
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: -- (:) From: Marc Rouaix Subject: Re: Map is not tail recursive
```It looks like this didn't get sent the first time.  I made the suggestion of using a map function that maps chunks of the list at a time.  Also, in a separate mail, I suggested using a map function that tested the length of the list and then chose what function to invoke, but I suppose that's a questionable strategy since finding the length of a list requires traversing it.

Anyway...

(* returns nth cons of a list, or [] if there is no such cons *)
let rec nth_tail ls n =
if n = 0 then ls else
match ls with
[] -> []
| x::xs -> nth_tail xs (n-1)

(* jump_map n should compute the same function as List.map for any n>0.  But
jump_map n will use min(list_size, n+list_size/n) stack space whereas
List.map uses list_size stack space.  jump_map costs an extra list
traversal compared to List.map. *)
let rec jump_map jump fn lst =
let rec do_a_chunk last stub chunk =
if chunk == last then stub else
(fn (List.hd chunk))::(do_a_chunk last stub (List.tl chunk))
in
if lst == [] then [] else
let last = nth_tail lst jump
in do_a_chunk last (jump_map jump fn last) lst

(* It may be a bad idea to use this because of the cost of List.length, but
you get the idea. *)
let general_map fn lst =
let n = List.length lst in
if n < 1000 then List.map fn lst
else jump_map (truncate (sqrt (float n))) fn lst

---
Marc

-----== Sent via Deja News, The Discussion Network ==-----