python - 为什么我翻译成 Python 的 Haskell 不能正常工作?

标签 python math haskell

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,为什么?

最佳答案

如果你再次调用 unfold ,你的生成器将重新生成,所以你需要将它赋值给变量。

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

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

相关文章:

python - 无法编辑 django 表

iphone - cocos2d 帮助找到圆上的点

haskell - 如何在 Haskell 中以隐藏的方式初始化状态(就像 PRNG 一样)?

python - 如何从 python 程序生成多个 python 脚本?

python - 如何计算新点在Voronoi图的哪个位置?

python - 在 Python 中为 Random.random() 组装 float

javascript - 寻找数字的最佳子集组合以达到给定的总和或最接近它

java - 在 Java 中将分数转换为单词

haskell - 管道解析器过早中断

string - Haskell 中如何比较字符串?