I am going through Haskell Programming book and an in exercise on page 140, the author states this:
A hypothetical function a->a->a has two possible implementations. Write both possible versions.
I am assuming a -> a -> a
would imply a function that takes two arguments (a and a)
- (which does not makes sense to me and if I declare a function with two args as a
, ghci rightly complains too) and returns a
I think I am missing something, what is it?
The way to think about this problem, perhaps, is to imagine how much we do not know about your arguments a
and a
.
It is impossible, for instance, for us to say the following:
someFunc :: a -> a -> a
someFunc x y = x == y
This won't typecheck because we don't even know if a
is an instance of the typeclass Eq
. In other words, we have no useful information about these a
things except that they are the same type of thing (whatever that may be).
Consider the identity function:
ident :: a -> a
ident x = ...
There is nothing this function can know about its sole argument x
. There is, as a result, only one possible, valid result:
ident x = x
Nothing else works because there's nothing else we can assume about our argument.
Now, in your case, you have two arguments which can be absolutely anything in the universe. There is no possible assertion we can make about any behaviors these two arguments can conform to. Thus, we can define our function in possibly two different ways:
someFunc1 :: a -> a -> a
someFunc1 x y = x
OR
someFunc2 :: a -> a -> a
someFunc2 x y = y
There is no other valid way to represent this function.
let f :: a -> a -> a
, because there's no limitation on type a
, the only possible 2 implementations would be just return 1st/2nd parameter, i.e.
f x _ = x
or
f _ x = x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With