简体   繁体   中英

Why these functions have different types in Haskell?

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 ;)

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] , ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM