[Haskell-cafe] Stupid newbie question
Brian Hulley
brianh at metamilk.com
Sat Jan 6 06:54:59 EST 2007
Brian Hurt wrote:
> nth 0 (x:xs) = Some x
> nth i (x:xs) = if i < 0 then Empty else nth (i-1) xs
> nth i [] = Empty
[blows stack on large i]
As other people have pointed out, this is due to laziness. I'd write it
like:
nth 0 (x:_) = Some x
nth i (_:xs) = of i < 0 then Empty else (nth $! i-1) xs
nth _ [] = Empty
where a general rule of thumb is always to replace (fun intexp) by (fun $!
intexp) whenever intexp is just a trivial arithmetic expression that doesn't
involve traversing (ie forcing of) any other data structure.
Brian.
--
http://www.metamilk.com
More information about the Haskell-Cafe
mailing list