How to convert a custom type to an Integer in Haskell?

I am trying to use my own data type in haskell for prime numbers, but i am currently running into a few issues.

newtype Prime = Prime Integer deriving (Eq, Ord, Typeable, Show)

As soon as i am doing any numeric operation on a prime number (e.g. the "phi" function below) i want to handle the result as an Integer but i don't know how to do it.

phi :: Prime -> Prime -> Integer
phi p q = (p-1)*(q-1)

phi should return an Integer because it's not a Prime number anymore. All i get is the expected error message:

    • Couldn't match expected type ‘Integer’ with actual type ‘Prime’
    • In the expression: (p - 1) * (q - 1)
      In an equation for ‘genPhi’: genPhi p q = (p - 1) * (q - 1)

So how can i convert a my custom type to an Integer? I don't have a lot of experience with Haskell.


  • You can unwrap the Integer out of the Prime data constructor:

    genPhi :: Prime -> Prime -> Integer
    genPhi (Prime p) (Prime q) = (p-1) * (q-1)