[Haskell-cafe] Stupid newbie question

Donald Bruce Stewart dons at cse.unsw.edu.au
Fri Jan 5 20:44:28 EST 2007


bhurt:
> 
> My apologies for wasting bandwidth on what I'm sure is a stupid newbie 
> question.
> 
> Given:
> 
> -- Reimplementing the wheel here, I know
> 
> data Option a = Some a | Empty
> 	deriving (Eq,Ord,Show,Read)
> 
> nth 0 (x:xs) = Some x
> nth i (x:xs) = if i < 0 then Empty else nth (i-1) xs
> nth i [] = Empty
> 
> That:
> 
> nth 1000000 [1..10000000]
> 
> returns the right answer, while:
> 
> nth 1000000 [1..]

Now I'm really intrigued, since the standard list-index function also
fails:

    Prelude> [1..] !! (10^6)
    *** Exception: stack overflow

It's implemeeted roughly as:

    nth xs     n | n < 0 = Nothing
    nth []     _         = Nothing
    nth (x:_)  0         = Just x
    nth (_:xs) n         = xs `nth` (n-1)

    main = print $ [1..] `nth` (10^6)

-- Don


More information about the Haskell-Cafe mailing list