Hemanth's Scribes

haskell

Thunks in Haskell

Author Photo

Hemanth HM

Thumbnail

Understanding thunks with Fibonacci:

let fib = 0 : 1 : zipWith (+) fib (tail fib)
take 10 fib  -- [0,1,1,2,3,5,8,13,21,34]

What are Thunks?

In Haskell, (4+2,7) is stored as (_,7) where _ is the thunk - a value not yet computed.

let x = (4+2,7)
:print x  -- ((_t1::Integer),7)

snd x  -- 7
:print x  -- ((_t2::Integer),7)  -- still not evaluated!

fst x  -- 6
x  -- (6,7)  -- now it's evaluated

Thunks are only evaluated when needed. Partial evaluation creates more thunks - values are computed lazily on demand.

From haskell-rascal.

#haskell#functional
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.