[Haskell] definition of intersperse

Iavor S. Diatchki diatchki at cse.ogi.edu
Tue Mar 2 16:59:48 EST 2004


hello,
i'd like to suggest that the definition of "intersperse" from the List 
module be made more lazy.
in the hugs prelude (and GHC exhibits the same behaviour) we are given 
the following defn:

intersperse             :: a -> [a] -> [a]
intersperse _   []      = []
intersperse _   [x]     = [x]
intersperse sep (x:xs)  = x : sep : intersperse sep xs

the second equation makes the defn, strict in the tail of the list.
this is a probelm when processing lazy lists (e.g. things coming over a network), as one gets all events with a delay.  
here is an alternative definition:

intersperse             :: a -> [a] -> [a]
intersperse _   []      = []
intersperse sep (x:xs)  = x : rest
  where rest [] = []
        rest xs = sep : intersperse sep xs

bye
iavor


-- 
==================================================
| Iavor S. Diatchki, Ph.D. student               | 
| Department of Computer Science and Engineering |
| School of OGI at OHSU                          |
| http://www.cse.ogi.edu/~diatchki               |
==================================================



More information about the Haskell mailing list