Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with a -> a -> a possible in Haskell?

Tags:

haskell

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?

like image 839
coder_bro Avatar asked Dec 04 '22 21:12

coder_bro


2 Answers

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.

like image 198
erewok Avatar answered Dec 30 '22 11:12

erewok


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
like image 42
delta Avatar answered Dec 30 '22 12:12

delta