4
votes

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?

2
can you post the full description of the exercise? - delta
a probably indicates a type; with no constraints it's a type you know nothing about, which limits you to two implementations having signature a -> a -> a. (I'm not a Haskell programmer but I think I know what the question's getting at.) - Jeffrey Bosboom
In layman's terms: since you need to know something about an argument's type to do anything to it, you can't do anything to either argument. Since you can't do anything to either argument, you can either return (unchanged) argument one, or argument two. - Adam Smith
@Ngm Every parameter to a function needs to have a different name. The type signature of a -> a -> a is just saying that the first two parameters have the same type. It doesn't mean they have the same name. - 4castle
The don't have the same name, they have the same type. a -> a -> a means that the function takes in two arguments of the same type type a and returns a value of that same type. - puhlen

2 Answers

10
votes

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.

6
votes

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