Efficient way to perform independent processing of list from IO?

Thomas Hallgren hallgren@cse.ogi.edu
Wed, 29 Aug 2001 13:43:12 -0700


mctague@one.net wrote:

>Is there a more
>memory-efficient approach, perhaps exploiting laziness somehow?
>
The libraries supplied with HBC (*) include a function called 
readListLazily, which I have taken the liberty to enclose below. 
Hopefully, it will help you solve the problem.

Regards,
Thomas Hallgren

(*) See http://www.haskell.org/implementations.html
------------------------------------------------------------------------

-- Copyright (c) 1982-1999 Lennart Augustsson, Thomas Johnsson
-- See LICENSE for the full license.
--

-- Read a list lazily (in contrast with reads which requires
-- to see the ']' before returning the list.
readListLazily :: (Read a) => String -> [a]
readListLazily cs = 
    case lex cs of
      [("[",cs)] -> readl' cs
      _          -> error "No leading '['"
    where readl' cs  =
                case reads cs of
                  [(x,cs)]  -> x : readl cs
                  []        -> error "No parse for list element"
                  _         -> error "Ambigous parse for list element"
          readl cs =
                case lex cs of
                  [("]",_)]  -> []
                  [(",",cs)] -> readl' cs
                  _          -> error "No ',' or ']'"