Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial Application with Infix Functions

While I understand a little about currying in the mathematical sense, partially applying an infix function was a new concept which I discovered after diving into the book Learn You a Haskell for Great Good.

Given this function:

applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)

The author uses it in a interesting way:

ghci> applyTwice (++ [0]) [1]  
[1,0,0]
ghci> applyTwice ([0] ++) [1]
[0,0,1]

Here I can see clearly that the resulting function had different parameters passed, which would not happen by normal means considering it is a curried function (would it?). So, is there any special treatment on infix sectioning by Haskell? Is it generic to all infix functions?


As a side note, this is my first week with Haskell and functional programming, and I'm still reading the book.

like image 566
sidyll Avatar asked Apr 12 '12 20:04

sidyll


People also ask

What are infix functions?

Infix notation Infix functions must meet the following requirements: They must be member functions or extension functions. They must have a single parameter. The parameter must not accept variable number of arguments and must have no default value.

What is the use of infix function in Kotlin?

Kotlin allows some functions to be called without using the period and brackets. These are called infix methods, and their use can result in code that looks much more like a natural language.

What is an infix function in Haskell?

Functions in Haskell default to prefix syntax, meaning that the function being applied is at the beginning of the expression rather than the middle. Operators are functions which can be used in infix style. All operators are functions.

What is a Section in Haskell?

Haskell Language Partial Application Sections Sectioning is a concise way to partially apply arguments to infix operators. For example, if we want to write a function which adds "ing" to the end of a word we can use a section to succinctly define a function.


1 Answers

Yes, you can partially apply an infix operator by specifying either its left or right operand, just leaving the other one blank (exactly in the two examples you wrote).

So, ([0] ++) is the same as (++) [0] or \x -> [0] ++ x (remember you can turn an infix operator into a standard function by means of parenthesis), while (++ [0]) equals to \x -> x ++ [0].

It is useful to know also the usage of backticks, ( `` ), that enable you to turn any standard function with two arguments in an infix operator:

Prelude> elem 2 [1,2,3]
True
Prelude> 2 `elem` [1,2,3] -- this is the same as before
True
Prelude> let f = (`elem` [1,2,3]) -- partial application, second operand
Prelude> f 1
True
Prelude> f 4
False
Prelude> let g = (1 `elem`) -- partial application, first operand
Prelude> g [1,2]
True
Prelude> g [2,3]
False
like image 66
Riccardo T. Avatar answered Sep 28 '22 20:09

Riccardo T.