lazy evaluation in infinte list

  • A+
Category:Languages

Hi I have the following code:

let f n (xs) = if n < 0 then f (n-1) (n:xs) else xs f (-3) [] !! 1 

and I expect it to print -4

But it does not print anything and keeps calculation in background.

What is wrong with my code?

 


Let's step through the evaluation:

f (-3) [] f (-4) [-3] f (-5) [-4, -3] f (-6) [-5, -4, -3] f (-7) [-6, -5, -4, -3] ... 

Considering this, what do you expect f (-3) [] !! 1 to be? The value in the index 1 changes each iteration, so there's no way Haskell can know what it is until it reaches the non-recursive case at n >= 0, which never happens.

If you build the list in the other direction, it will work as you expect:

let f n = if n < 0 then n : f (n - 1) else []  > f (-3) !! 1 -4 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: