Haskell 中指数函数的泰勒序列
Taylor sequence for the exponential function in Haskell
我尝试为指数函数实现泰勒序列,但出现大量错误,我不完全理解这些错误,因为所有代码段本身都有效...有人可以解释错误吗请解决方法:
top x = map (x^) [0..]
bottom = foldr (*) 1 [1..]
whole x = zipWith (/) (top x) bottom
提前致谢!
好的,我明白了。问题是 bottom
实际上并不是所有可能阶乘的列表。
为了解决这个问题,我不得不使用 scanl
而不是 foldr
:
bottom = scanl (*) 1 [1..]
您可以在 GHCi 中分别测试每个功能,看看它是否与您设计的一样。
比如你的第一个定义bottom
Prelude> bottom = foldr (*) 1 [1..]
Prelude> :t bottom
bottom :: (Num b, Enum b) => b
没有给出列表。这显然不是 zipWith
的正确输入
Prelude> :t zipWith
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
与正确的对比
Prelude> bottom = scanl (*) 1 [1..]
Prelude> :t bottom
bottom :: (Num b, Enum b) => [b]
其中给出了一个列表。
我尝试为指数函数实现泰勒序列,但出现大量错误,我不完全理解这些错误,因为所有代码段本身都有效...有人可以解释错误吗请解决方法:
top x = map (x^) [0..]
bottom = foldr (*) 1 [1..]
whole x = zipWith (/) (top x) bottom
提前致谢!
好的,我明白了。问题是 bottom
实际上并不是所有可能阶乘的列表。
为了解决这个问题,我不得不使用 scanl
而不是 foldr
:
bottom = scanl (*) 1 [1..]
您可以在 GHCi 中分别测试每个功能,看看它是否与您设计的一样。
比如你的第一个定义bottom
Prelude> bottom = foldr (*) 1 [1..]
Prelude> :t bottom
bottom :: (Num b, Enum b) => b
没有给出列表。这显然不是 zipWith
Prelude> :t zipWith
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
与正确的对比
Prelude> bottom = scanl (*) 1 [1..]
Prelude> :t bottom
bottom :: (Num b, Enum b) => [b]
其中给出了一个列表。