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()

它应该输出列表的后两个值,例如5.0、3.4

但是它输出两次5.0,为什么呢?

最佳答案

如果再次调用展开,则生成器将再次重新生成,因此需要将其分配给变量。

>>> res = unfold(acc, 1)
>>> print res.next()
5.0
>>> print res.next()
3.4
>>>

关于python - 为什么我翻译成Python的Haskell无法正常工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7186081/

10-13 08:51