Define functions that have the following type signature!
One :: Num a => a -> Bool -> a
One = ?
I do not understand how a Num can be a bool and become again a Num. Could anybody help for me to understand and solve it.
CodePudding user response:
how a Num can be a bool and become again a Num. Could anybody help for me to understand this.
Well, this would be the case if the grouping in the type was to the left, like so
one :: Num a => (a -> Bool) -> a
But actually, the grouping is to the right:
one :: Num a => a -> (Bool -> a)
So we need to find a way to turn an a
type value into a way to turn a Bool
value to an a
type value.
Since we will have had this a
type value, we could just return it:
one a = two
where
two b = a
Do note that I had to change One
to one
. While One
is syntactically a type in Haskell, one
is a value which has a type. Which you show.
So what we did here is define the value one
, which has this type. Or in Haskell,
one :: a -> (Bool -> a)
But wait, where did the Num a =>
constraint go? We didn't use it at all, and that's why all we could do was to just return the a
.
But what does it mean, for a
to be a Num
?
GHCi> :i Num
class Num a where
( ) :: a -> a -> a
(*) :: a -> a -> a
(-) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
So then, any Num
has absolute value, and can be negated. Thus a possible definition is
one :: Num a => a -> (Bool -> a)
one a = two
where
two b | b = negate a
| otherwise = abs a