Home > other >  How can I define a function of type Integral a => a?
How can I define a function of type Integral a => a?

Time:09-22

We've just started learning Haskell at uni, and in one of my homework problems, we have to define a function for this type signature:

f1 :: Integral a => a

To be honest, I'm still trying to understand a bunch of basics about Haskell, but I know that with Integral, you can do mod and div, plus the ones you can do with Num, , - and *.

So I could write

f1 :: Integral a=> a -> a
f1 k = k `mod` k

And it would work. But with

f1 :: Integral a => a

There seems to be no output.

How can I write something with this that doesn't give an error when interpreted?

CodePudding user response:

You're right that Integral doesn't have anything of that shape. But Integral is also a lot of other things, and if we trace the hierarchy up, we see that every Integral is a Num, and every Num has

fromInteger :: Num a => Integer -> a

So, for your function, we could write

f1 :: Integral a => a
f1 = fromInteger 0

or

f1 :: Integral a => a
f1 = fromInteger 42

or, frankly, pick your favorite number.

Also, because of Haskell magic, the literal number 42 is actually fromInteger 42 (the literal 42, in Haskell, has type Num a => a. So this function will suffice as well.

f1 :: Integral a => a
f1 = 42
  • Related