Friday, 29 April 2016

Haskell: Infix functions

Till now we called the functions like function name followed by arguments. This kind of notation is called prefix notation, since function name comes before arguments. If a function takes more than one argument, then you can use it in both prefix and infix notation.


For example,
*Main> let sum x y = (x + y)
*Main> 
*Main> sum 10 20
30
*Main>

How to use sum function in infix notation?
Syntax
Argument1 `functionName` Argument2


*Main> 123 `sum` 1234
1357
*Main> 
*Main> 123 `sum` 1234 `sum` 3456
4813


Usually, you can apply a function in infix notation, when it is taking exactly two arguments. When a function takes more than 2 arguments, you need extra parenthesis.
*Main> let processData x y z = (x-z) * y
*Main> 
*Main> ((10) `processData` 20) 30
-400
*Main> 
*Main> ((10) `processData` 20) 10
0


In Haskell the functions whose name consists of alphanumeric characters are prefix by default, and the functions made up from non alpha numeric character like +, >, $ etc are infix by default. For example, you can define an infix function like,
Prelude> let a $+ b = a + 5*b
Prelude> 
Prelude> 5 $+ 6
35
Prelude> 
Prelude> 5 $+ 10
55
Prelude>




Previous                                                 Next                                                 Home

No comments:

Post a Comment