How would you declare the types of these functions in Haskell?

  • A+
Category:Languages

So I'm learning about Haskell at the moment, and I came across this question:

The type of a function f is supposed to be a->[a]->a. The following definitions of f are incorrect because their types are all different from a->[a]->a:

i. f x xs = xs ii. f x xs = x+1 iii. f x xs = x ++ xs iv. f x (y:ys) = y 

My answers as I see it are:

i) f :: a -> a -> a 

This is because x or xs can be of any value and is not a list as it does not contain the ':' operator.

ii) f :: Int -> a -> Int 

This is because the + operator is used on x, meaning x is of type Int.

iii) f :: Eq a => a -> a -> a 

The ++ operators are used, therefore in order to concatenate they must be of the same type..?

iv) f :: a -> [a] -> a 

f returns an element from the list.

The last one is definitely wrong, because it can't be of type a -> [a] -> a. Are there any others I did wrong, and why? I'm hoping I can fully understand types and how to find out the types of functions.


i) f :: a -> a -> a

f x xs = xs

This is because x or xs can be of any value and is not a list as it does not contain the ':' operator.

True, but it also does not have to be of the same type! So, it's actually f :: a -> b -> b.

ii) f :: Int -> a -> Int

f x xs = x+1

This is because the + operator is used on x, meaning x is of type Int.

Correct. (Actually, in Haskell we get Num b => b -> a -> b which generalized the Int to any numeric type, but it's not that important.)

iii) f :: Eq a => a -> a -> a

f x xs = x ++ xs

The ++ operators are used, therefore in order to concatenate they must be of the same type..?

True, but they must be lists. Also, Eq is only needed if you use == or something which compares values.

Here, f :: [a] -> [a] -> [a].

iv) f :: a -> [a] -> a

f x (y:ys) = y

f returns an element from the list.

The type of x does not have to be the same. We get f :: b -> [a] -> a.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: