gpt4 book ai didi

Haskell 余弦定理的实现

转载 作者:行者123 更新时间:2023-12-02 13:32:32 25 4
gpt4 key购买 nike

我正在尝试实现 law of cosines函数,这是我的代码:

cosC :: [a] -> a
cosC sides
| length sides < 3 = 0
| otherwise = (x ^ 2 + y ^ 2 - z ^ 2) / (2 * x * y)
where x = head(tail(tail(sides)))
y = head(tail(sides))
z = head(sides)

但是我收到两个错误:

No instance for (Fractional a)
arising from a use of `/'
In the expression: (x ^ 2 + y ^ 2 - z ^ 2) / (2 * x * y)
In an equation for `cosC':
cosC sides
| length sides < 3 = 0
| otherwise = (x ^ 2 + y ^ 2 - z ^ 2) / (2 * x * y)
where
x = head (tail (tail (sides)))
y = head (tail (sides))
z = head (sides)

No instance for (Num a)
arising from the literal `2'
In the first argument of `(*)', namely `2'
In the first argument of `(*)', namely `2 * x'
In the second argument of `(/)', namely `(2 * x * y)'

编辑:我已经修复了上面余弦定理中的符号拼写错误。感谢 Daniel Fischer 指出了这一点。

最佳答案

您正在尝试从一般类型 a 中计算数值结果,这是不可能的。 (这就像试图不仅为一般公路车辆 build 一座桥梁,而且为一般事物 build 一座桥梁,例如宇宙飞船、摩天大楼、回形针和中子星)。只需将 Floating 约束添加到:

cosC :: Floating a => [a] -> a

您可以执行此类计算所需的任何算术运算。 (Fractional 实际上对于这个函数来说已经足够了,但是你将无法计算结果的 arccos)。

<小时/>

与您的问题无关,请注意,在 Haskell 中有一种更好的分解列表的方法:

cosC (x:y:z:_) = (x^2 + y^2 - z^2) / (2*x*y)
cosC _ = 0

相当于你的定义。无论如何,你为什么要把这些论点作为一个列表?这是一个相当 Lisp 风格的事情,我更喜欢用 Haskell 来做

cosC :: Floating a => a -> a -> a -> a
cosC x y z = (x^2 + y^2 - z^2) / (2*x*y)

关于Haskell 余弦定理的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13645874/

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