Version française
Home     About     Download     Resources     Contact us    

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

Browse thread
Re: Map is not tail recursive
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Marc Rouaix <rouaix@m...>
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.


(* 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 for any n>0.  But
   jump_map n will use min(list_size, n+list_size/n) stack space whereas uses list_size stack space.  jump_map costs an extra list
   traversal compared to *)
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 ( chunk))
  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 fn lst
  else jump_map (truncate (sqrt (float n))) fn lst


-----== Sent via Deja News, The Discussion Network ==-----  Easy access to 50,000+ discussion forums