简体   繁体   中英

Confusion on partially applied infix operators

So I was reading through a Haskell guide online, and was just curious about the combination of infix operators and filter.

Say you have a function like

filter (>5) [6, 10, 5]

That will return [6,10], which seems like the intuitive way filter should work.

However, doing

filter ((>) 5) [6, 10, 5]

returns an empty list (this still makes sense, (>) checks if its first argument is larger than the second argument).

However, filter is typically defined something like

filter :: (a -> Bool) -> [a] -> [a]  
filter _ [] = []  
filter p (x:xs)   
    | p x       = x : filter p xs  
    | otherwise = filter p xs

When the type system knows it has an infix operator, are most of those infix operators written so that a partially applied function needs a leading argument to the original prefix function? ie is infix > defined as something like (butchered syntax)

infix> :: Int -> Int-> Bool
infix> x y = (>) y x
x infix> y = (>) x y

Sorry if this question doesn't make sense, I feel like I'm missing something basic in how px is evaluated when p is a partially applied infix operator.

(>5) and ((>) 5) are two different types of expression.

The first is what is known as a section . Sections are of the form (op exp) or (exp op) where op is an infix operator and exp is another expression. A section takes an argument and applies it on the missing side, so (>5) 4 = (4 > 5) and (5>) 4 = (5 > 4) . In other words, (>5) is equivalent to \\x -> x > 5 .

In ((>) 5) , (>) is the infix operator > converted to an expression. ((>) 5) then is the application of 5 to the function (>) , which gives a new function that takes the next argument. If we apply that argument, eg, (>) 5 4 , we get the prefix equivalent of (5 > 4) .

This conversion of an infix operator to an expression that can be used prefix works for all infix operators. You can also go the other way and covert an identifier into an infix operator, ie:

`foo`

You can even say:

(`foo`)

to turn it back into an expression.

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