Reputation: 5
If anyone can help me out with clearing this question?
The Standard Prelude function takeWhile has type (a -> Bool) -> [a] -> [a]
Write down the type of the Haskell expression takeWhile even
The function even
is defined as:
even x = x `mod` 2 == 0
Would this be considered right?
takeWhile:: Num a => (a->Bool) -> [a] -> [a]
Upvotes: 0
Views: 474
Reputation: 1957
To derive the type signature of takeWhile even
you need to first take a look at the type signature for takeWhile
and even
. According to GHCi, the type signatures for those functions are the following.
takeWhile :: (a -> Bool) -> [a] -> [a]
even :: Integral a => a -> Bool
In the case of takeWhile even
, takeWhile
takes in a function of type (a -> Bool)
, thus a function that takes in some value of type a
and returns a Bool
.
The even
function takes in an Integral
value and returns a Bool
value, so it can be passed in as the first argument to takeWhile
. Since the Integral
typeclass is implemented by several different types such as Int
and Integer
, you can pass in a value of any such type that implements the Integer
typeclass.
You will want to notice that in takeWhile
, the a
in (a -> Bool)
is not bound to any typeclass, however in even
the corresponding a
is bound to the Integral
typeclass. In this case, this causes the resulting expression to bind the a
in the takeWhile
type signature to Integral
. For example, you could imagine takeWhile
to have the following type signature in this case:
takeWhile :: Integral a => (a -> Bool) -> [a] -> [a]
Also, since the first argument of takeWhile
is filled by even
, the type signature of the resulting expression does not have the (a -> Bool)
term.
Thus, you are left with the following type signature for takeWhile even
. Therefore takeWhile even
takes in a list of Integral
values and returns a list of Integral
values of the same type.
takeWhile even :: Integral a => [a] -> [a]
If you want to confirm this using GHCi, you can run the following command to get the type signature of the expression:
:t takeWhile even
Upvotes: 2