Haskell-如何制作"div"或"/"只是在实例中? [英] Haskell - How to make "div" or "/" simply in Instance?

查看:102
本文介绍了Haskell-如何制作"div"或"/"只是在实例中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例

    data SomeData = Number Integer | String String | Bool Bool
                  deriving Eq

而且,我想对SomeData使用'div'.

And,I want to use 'div' with SomeData.

    instance Num SomeData where
            (Number x) + (Number y) = Number $ x + y -- It's Ok.
            (Number x) - (Number y) = Number $ x - y -- It's Ok.
            (Number x) * (Number y) = Number $ x * y -- It's ok.
    instance Integral SomeData Where
            (Number x) `div` (Number y) = Number $ x `div` y

但是我收到了错误消息.

But I got Error Message.

main.hs:105:10:
    No instance for (Real SomeData)
      arising from the superclasses of an instance declaration
    Possible fix: add an instance declaration for (Real SomeData)
    In the instance declaration for `Integral SomeData'

main.hs:105:10:
    No instance for (Enum SomeData)
      arising from the superclasses of an instance declaration
    Possible fix: add an instance declaration for (Enum SomeData)
    In the instance declaration for `Integral SomeData'

好,如果我要对SomeData数据使用div,我应该为SomeData逐步编写Real InstanceEnum Instance吗?还是还有另一种好方法?

Ok,If I want to use div with SomeData data,should I write Real Instance and Enum Instance for SomeData step-by-step? Or Is there another good way ?

推荐答案

解决此类问题的通用方法是在ghci中使用:info命令:

A general method to solve problems like this is to use :info command in ghci:

Prelude> :i Integral
class (Real a, Enum a) => Integral a where
  quot :: a -> a -> a
  rem :: a -> a -> a
  div :: a -> a -> a
  mod :: a -> a -> a
  quotRem :: a -> a -> (a, a)
  divMod :: a -> a -> (a, a)
  toInteger :: a -> Integer

因此,不能,如果不实现Real,就不能实现Integral.您可能直接从div开始:

So no, you cannot implement Integral without implementing Real. You could have started straight from div:

Prelude> :i div
class (Real a, Enum a) => Integral a where
  ...
  div :: a -> a -> a
  ...
        -- Defined in GHC.Real
infixl 7 div

因此您可以看到div是整数类型类的方法,并且还需要定义RealEnum.如果选中Real,则需要NumOrd等.

So you can see that div is a method of Integral type class and you need Real and Enum to be defined as well. If you check Real, it requires Num and Ord etc.

这篇关于Haskell-如何制作"div"或"/"只是在实例中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆