2013-06-18 16 views
5

sto imparando Haskell e ha scritto questa funzione:apprendimento Haskell: thunk restituiti da ripetere

continueWith :: [a] -> a -> [a] 
continueWith [] y  = repeat y 
continueWith (x:xs) y = x : (continueWith xs y) 

Ora, non capisco il comportamento di GHCi:

GHCi> let x = continueWith [1, 2] 3 
x :: [Integer] 
GHCi> :sp x 
x = _ 
GHCi> take 3 x 
[1,2,3] 
it :: [Integer] 
GHCi> :sp x 

Gli ultimi sprint doesn 't terminare, ma mi aspettavo che il thunk restituito da repeat essere valutata solo fino ai primi contro:

... 
GHCi> take 3 x 
[1,2,3] 
it :: [Integer] 
GHCi> :sp x 
x = 1 : 2 : 3 : _  <= This is not happening 

Cosa mi manca?

risposta

5

Il "problema" è che repeat y riferisce a se stessa,

repeat y = let ys = y:ys in ys 

così una volta la prima cella cons viene valutata, repeat y è completamente valutata. In ASCII art:

(:) <- 
/\ | 
y \_| 

:sp stampe per quanto la cosa è già valutato ...