[Haskell-cafe] Stupid newbie question

Marc A. Ziegert coeus at gmx.de
Sat Jan 6 02:42:33 EST 2007


Am Samstag, 6. Januar 2007 05:12 schrieb Brian Hurt:
> Even better, if I define:
> 
> nth 0 (x:_) = Just x
> nth i (_:xs) = if i < 0 then Nothing else nth (i-1) xs
> nth i [] = Nothing
> 
> makelist i = i `seq` i : (makelist (i+1))
> 
> nth 10000000 (makelist 1)
> 

Hi Brian.
i just like to mention another tricky solution:
you can apply seq in such a way to the list, so that each element will be evaluated before advancing deeper into the list.


ghci -fglasgow-exts -fbang-patterns

Prelude> :t foldr
foldr :: forall a b. (a -> b -> b) -> b -> [a] -> b

Prelude> let strict = foldr (\x xs ->x `seq` (x:xs)) []
Prelude> let strict = foldr (\(!x) xs -> (x:xs)) []     --  using bang patterns instead, this is easier to read
Prelude> let strict = foldr ((:) $!) []                 --  or complete pointfree
Prelude> let lazy   = foldr ((:) $) []
Prelude> :t strict
strict :: forall a. [a] -> [a]

Prelude> lazy [1..] !! 1000000
*** Exception: stack overflow
Prelude> strict [1..] !! 1000000
1000001



- marc


More information about the Haskell-Cafe mailing list