0

I want to make my newtype instance of Integral class. My newtype:

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

I want to be able to do div with my newtype NT:

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

Since:

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

I should make my NT instance of Integral class.

This is how is Integral class defined:

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

and Since I need only div I tried:

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

or can I do this?

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

but either way I get the error:

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

Should I make NT instance of Real class First and how?

duplode
  • 33,731
  • 7
  • 79
  • 150
cheshire
  • 1,109
  • 3
  • 15
  • 37
  • 2
    Related: https://stackoverflow.com/q/53188123/67579 – Willem Van Onsem Nov 17 '18 at 22:57
  • 2
    Yes, a type has to have both `Real` and `Enum` instances before you can declare an instance for `Integral`. That's what `(Real a, Enum a) => Integral a` means in the class definition. – chepner Nov 17 '18 at 23:09
  • If you only need `div`, you probably shouldn't declare any instance at all. Just define a custom div-like function and use that. – melpomene Nov 17 '18 at 23:41
  • 1
    In cases like this, there is no need to edit a "solved" note into your question. Instead, leave a comment saying the suggested question solves the problem, so that the rest of us know it is okay to close it as a duplicate. (Also, if someone casts a duplicate vote and it doesn't close the question immediately, an option will show up for you to confirm the duplicate.) – duplode Nov 18 '18 at 02:09

0 Answers0