gpt4 book ai didi

haskell除法类型不匹配?

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

我是 Haskell 新手,我正在尝试为作业实现一个计算器。我陷入了需要对两个值进行除法的地方,我认为问题是无法推断它们的类型或需要声明/转换。我正在尝试学习如何自己解决这个问题,但在此过程中的任何见解都会有所帮助。

这是代码:

data Value e = OK e | Error String deriving (Eq)

-- assuming we know how to type e can be shown, i.e. Show e, then
-- we know how to show a Value e type
instance (Show e) => Show (Value e) where
show (OK x) = (show x)
show (Error s) = "ERROR: " ++ s

type Token = String
type Result = Value Int
type Intermediate = [ (Value Int) ]

-- an algebra is a things that knows about plus and times
class Algebra a where
plus :: a -> a -> a
times :: a -> a -> a
subtraction :: a -> a -> a
division :: a -> a-> a

-- assuming that we know how to + and * things of type e, (i.e.
-- we have Num e, then we have algebra's over Value e
instance (Num e) => Algebra (Value e) where
plus (OK x) (OK y) = (OK (x+y))
times (OK x) (OK y) = (OK (x*y))
subtraction (OK x) (OK y) = (OK (x-y))
division (OK x) (OK 0) = (Error "div by 0")
division (OK x) (OK y) = (OK (x `div` y)) <-- this is line 44 that it complains about

这是我尝试通过 ghci test.hs 运行程序时出现的错误

test.hs:44:34:  
Could not deduce (Integral e)
from the context (Algebra (Value e), Num e)
arising from a use of `div' at test.hs:44:34-42
Possible fix:
add (Integral e) to the context of the instance declaration
In the first argument of `OK', namely `(x `div` y)'
In the expression: (OK (x `div` y))
In the definition of `division':
division (OK x) (OK y) = (OK (x `div` y))

还有更多代码,为了清楚起见,我想将其省略,但如果不清楚的话,我随时可以对其进行编辑。

最佳答案

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

Num a 并不意味着Integral a 也不意味着Fractional a(当然,反之亦然)。如果您想使用 div,则必须提供至少与 Integral a 上下文一样严格的内容。

关于haskell除法类型不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4362342/

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