Reputation: 731
Can anyone explain me why these functions have different types?
fa xs x = filter (>x) xs
fb xs = \x -> filter (> x)
fc x = filter (> x)
I think the first has the type: Ord a => [a]->a->[a] but I'm not sure about the rest. Can anyone help me please? Thanks ;)
Upvotes: 2
Views: 123
Reputation: 48654
The functions have the following type:
fa :: Ord a => [a] -> a -> [a]
fa xs x = filter (>x) xs
fb :: Ord a => t -> a -> [a] -> [a]
fb xs = \x -> filter (> x)
fc :: Ord a => a -> [a] -> [a]
fc x = filter (> x)
The first function is of the type [a] -> a -> [a]
because xs
corresponds to the list and x
corresponds to the element.
The key to figuring this out is by inspecting the type of filter
function:
ghci > :t filter
filter :: (a -> Bool) -> [a] -> [a]
So xs
is passed as the second parameter of the filter function and hence it is of list type. The x
is passed in the function (a -> bool)
and hence it is a single element. And the result you get from filter
function is also of list type. So your type definition will look like this:
[a] -> a -> [a]
You can apply the same logic to figure out the type definitions for the rest of the functions. When you have doubt about any type, just load the function definitions in ghci
and inspect them using :t function_name
there.
Upvotes: 3
Reputation: 144136
The first has type Ord a => [a] -> a -> [a]
and it filters the input list to contain all elements greater than the argument x
.
filter (> x)
has type Ord a => [a] -> [a]
, i.e. it defines a function which filters a list to contain elements greater than x
. This meas your second function has type
Ord a => b -> (a -> ([a] -> [a]))
.
Note that this function makes no use of the input xs
, unlike the first, so the first argument can be any type at all.
The third has type Ord a => a -> [a] -> [a]
. This is like the first except the argument to compare against comes first, before the list argument.
Upvotes: 8