[Haskell-cafe] Stupid newbie question

Brian Hulley brianh at metamilk.com
Sat Jan 6 09:32:12 EST 2007

Brian Hulley wrote:
> Brian Hulley wrote:
>> 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
>                           ^^^ -- oops!
>>    nth _ [] = Empty

Actually I see I should have read Jeremy Shaw's answer more carefully before 
giving my own since I'd missed the point about the problem being with the 
list itself not the decrementing of (i) (which wouldn't be a problem since 
it is immediately forced on the next iteration by the comparison of i to 0).

The answer therefore lies in the laziness of the makelist function which 
could be solved by:

    makelist i = i : (makelist $! i - 1)

Jeremy Shaw wrote:
> pps. I didn't explain why [1..1000000] works, but [1..] fails, because
> I don't know :) It's a bit suprising to me...

I think this might be because the code that produces the list [1..1000000] 
would have to be something like:

    produce n i = if i < n then i : produce n (i +1) else []

so each element of the list is now forced by the comparison with n, so even 
though the end of the list will be a thunk when 1000000 has not yet been 
reached, none of the elements are thunks.

Anyway it was certainly not a "stupid" question - thanks for asking it.

Best regards, Brian.

More information about the Haskell-Cafe mailing list