Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this Haskell I translated to Python work properly?

Haskell:

average x y = (x + y) / 2

sqrt' :: (Ord a, Fractional a) => a -> Int -> a
sqrt' 0 _ = 0.0
sqrt' 1 _ = 1.0
sqrt' s approximations = (infsqr' s) !! approximations

infsqr' n = unfoldr acc 1 where
    acc guess | guess < 0 = Nothing
              | otherwise = Just (newguess', newguess') where
                newguess' = average guess (n / guess)

Python:

def unfold(f, x):
    while True:
        w, x = f(x)
        yield w

def average(x, y):
    return float((x + y) / 2)

def acc(guess):
    if guess < 1:
        return None
    else:
        newguess = average(guess, (float(n/guess)))
        return (newguess, newguess) 
n = 9
print unfold(acc, 1).next()
print unfold(acc, 1).next()

It should output the next two values of the list, e.g. 5.0, 3.4

But it outputs 5.0 twice, why?

like image 563
Wes Avatar asked Aug 25 '11 06:08

Wes


1 Answers

If you called unfold again, your generator will regenerate again, so you need to assign it to variable.

>>> res = unfold(acc, 1)
>>> print res.next()
5.0
>>> print res.next()
3.4
>>>
like image 149
YOU Avatar answered Nov 01 '22 10:11

YOU