gpt4 book ai didi

haskell - Haskell 中不直观的类型签名

转载 作者:行者123 更新时间:2023-12-01 07:00:41 26 4
gpt4 key购买 nike

我做了这个(我认为是)相当简单的代码来计算三角形的第三边:

toRadians :: Int -> Double
toRadians d = let deg = mod d 360
in deg/180 * pi

lawOfCosines :: Int -> Int -> Int -> Double
lawOfCosines a b gamma = sqrt $ a*a + b*b - 2*a*b*(cos (toRadians gamma))

但是,当我尝试将其加载到 GHCi 中时,出现以下错误:
[1 of 1] Compiling Main             ( law_of_cosines.hs, interpreted )

law_of_cosines.hs:3:18:
Couldn't match expected type `Double' with actual type `Int'
In the first argument of `(/)', namely `deg'
In the first argument of `(*)', namely `deg / 180'
In the expression: deg / 180 * pi

law_of_cosines.hs:6:26:
No instance for (Floating Int)
arising from a use of `sqrt'
Possible fix: add an instance declaration for (Floating Int)
In the expression: sqrt
In the expression:
sqrt $ a * a + b * b - 2 * a * b * (cos (toRadians gamma))
In an equation for `lawOfCosines':
lawOfCosines a b gamma
= sqrt $ a * a + b * b - 2 * a * b * (cos (toRadians gamma))

law_of_cosines.hs:6:57:
Couldn't match expected type `Int' with actual type `Double'
In the return type of a call of `toRadians'
In the first argument of `cos', namely `(toRadians gamma)'
In the second argument of `(*)', namely `(cos (toRadians gamma))'

结果证明修复是删除我的类型签名,它工作正常。
toRadians d = let deg = mod d 360
in deg/180 * pi

lawOfCosines a b gamma = sqrt $ a*a + b*b - 2*a*b*(cos (toRadians gamma))

当我查询 toRadians 的类型时和 lawOfCosines :
*Main> :t toRadians
toRadians :: (Floating a, Integral a) => a -> a
*Main> :t lawOfCosines
lawOfCosines :: (Floating a, Integral a) => a -> a -> a -> a
*Main>

有人可以向我解释这里发生了什么吗?为什么我写的“直观”类型签名实际上是不正确的?

最佳答案

问题出在toRadians :mod有类型 Integral a => a -> a -> a ,因此,deg有类型 Integral i => i (所以要么 IntInteger )。

然后您尝试使用 /deg , 但是 /不取整数(用 div 除积分):

(/) :: Fractional a => a -> a -> a

解决方案是简单地使用 fromIntegral :: (Integral a, Num b) => a -> b :
toRadians :: Int -> Double
toRadians d = let deg = mod d 360
in (fromIntegral deg)/180 * pi

关于haskell - Haskell 中不直观的类型签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15556077/

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