Re: Map is not tail recursive

From: Marc Rouaix (
Date: Wed Jan 13 1999 - 18:40:39 MET

Date: Wed, 13 Jan 1999 17:40:39 -0000
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.


(* 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

This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:17 MET