首页 > 解决方案 > 在haskell中制作Integral类的newtype实例

问题描述

我想制作我的 Integral 类的新类型实例。我的新类型:

newtype NT = NT Integer deriving (Eq,Ord,Show)

我希望能够div使用我的newtype NT

Prelude> (NT 5) `div` (NT 2)
2

自从:

Prelude> :t div
div :: Integral a => a -> a -> a 

我应该制作我NT的课程实例Integral

这是Integral类的定义方式:

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

并且因为我只需要div我尝试过:

instance Integral NT where
  (NT x) `div` (NT y) =  (NT q)  where (q,r) = divMod x y

或者我可以这样做吗?

instance Integral NT where
  div (NT x)  (NT y) =  NT (div x y )

但无论哪种方式我都会得到错误:

• No instance for (Real NT)
  arising from the superclasses of an instance declaration
• In the instance declaration for ‘Integral NT’

我应该首先创建类NT的实例Real吗?如何创建?

标签: haskellnewtype

解决方案


推荐阅读