gpt4 book ai didi

Haskell - 预期类型与实际类型

转载 作者:行者123 更新时间:2023-12-03 23:21:16 25 4
gpt4 key购买 nike

我定义了以下函数:

calculateApproximation :: Int -> Int -> Int -> Double -> Double
calculateApproximation n a r tol =
if abs(((take n xs)!!(n-1)) - (((take n xs)!!(n-2)))) <= tol
then ((take n xs)!!(n-1))
else calculateApproximation (n+1) a r tol
where xs = unfoldr (\x -> Just(x, (x + (r/x))/2)) a

但我看到了以下类型错误:

Couldn't match expected type `Int' with actual type `Double'
In the second argument of `(<=)', namely `tol'
In the expression:
abs (((take n xs) !! (n - 1)) - (((take n xs) !! (n - 2)))) <= tol

但是,为什么它期望 tol 是一个 Int,而我已经将它定义为 Double?还是我在这里忽略了一个完全愚蠢的错误?

最佳答案

最简单的修复是修改类型签名,使您的初始猜测 a 和您计算平方根的数字 rDouble 而不是 Int

我还冒昧地提取了定义 ys = take n xs 以稍微简化代码。

calculateApproximation :: Int -> Double -> Double -> Double -> Double
calculateApproximation n a r tol =
if abs (ys!!(n-1) - ys!!(n-2)) <= tol
then ys!!(n-1)
else calculateApproximation (n+1) a r tol
where xs = unfoldr (\x -> Just(x, (x + (r/x))/2)) a
ys = take n xs

但是,正如评论中所指出的,在查找第 n-1 个元素之前,您实际上不需要获取 n 个元素。您可以将 !! 应用于无限列表,这进一步简化了您的代码

calculateApproximation :: Int -> Double -> Double -> Double -> Double
calculateApproximation n a r tol =
if abs (xs!!(n-1) - xs!!(n-2)) <= tol
then xs!!(n-1)
else calculateApproximation (n+1) a r tol
where xs = unfoldr (\x -> Just(x, (x + (r/x))/2)) a

为了清楚起见,我可能会分解出更多的定义,给出

calculateApproximation' n a r tol = go n
where
go n = let eps = abs $ xs!!(n-1) - xs!!(n-2)
in if eps <= tol
then xs !! (n-1)
else go (n+1)

xs = unfoldr (\x -> Just (x, (x + r/x)/2)) a

最后,我会注意到 go 操作只使用列表的 n-1n-2 元素,从不较早的元素,并且索引 n 仅用于跟踪您在列表中的位置。所以我会重写,以便 go 对列表而不是索引进行操作,并让它遍历列表直到找到合适的答案。在一个小的整理中,我将从 unfoldr 更改为 iterate - 如果列表应该是,你真的只需要 unfoldr在某个点终止。

calculateApproximation a r tol = go xs
where
go (x:y:rest) = if abs (x-y) < tol
then y
else go (y:rest)

xs = iterate (\x -> (x+r/x)/2) a

关于Haskell - 预期类型与实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20370949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com