Difference between revisions of "Infix operator"
Jump to navigation
Jump to search
(links to other articles) |
m (Various minor changes) |
||
(One intermediate revision by one other user not shown) | |||
Line 2: | Line 2: | ||
== Overview == |
== Overview == |
||
− | Functions in Haskell are usually called using prefix notation, or the function name followed by its arguments. However, some functions |
+ | Functions in Haskell are usually called using prefix notation, or the function name followed by its arguments. However, some functions e.g. addition are called using ''infix notation'' - putting the function name between its two arguments: |
+ | |||
+ | Prelude> 17 + 25 |
||
+ | 42 |
||
== Using infix functions with prefix notation == |
== Using infix functions with prefix notation == |
||
− | Putting |
+ | Putting parentheses around an infix operator converts it into a prefix function: |
Prelude> (+) 1 2 |
Prelude> (+) 1 2 |
||
Line 15: | Line 18: | ||
== Using prefix functions with infix notation == |
== Using prefix functions with infix notation == |
||
− | Putting ` |
+ | Putting <code>`</code>-marks around a prefix function allows us to use it like an infix function: |
Prelude> let concatPrint x y = putStrLn $ (++) x y |
Prelude> let concatPrint x y = putStrLn $ (++) x y |
||
Line 23: | Line 26: | ||
ab |
ab |
||
− | Note that you can only do this with a function that takes two arguments. |
+ | Note that you can only normally do this with a function that takes two arguments. Actually, for a function taking more than two arguments, you can do it but it's not nearly as nice (note the need for extra parentheses): |
+ | |||
+ | Prelude> foldl (+) 0 [1..5] |
||
+ | 15 |
||
+ | Prelude> ((+) `foldl` 0) [1..5] |
||
+ | 15 |
||
== See also == |
== See also == |
Latest revision as of 23:45, 25 June 2021
Overview
Functions in Haskell are usually called using prefix notation, or the function name followed by its arguments. However, some functions e.g. addition are called using infix notation - putting the function name between its two arguments:
Prelude> 17 + 25 42
Using infix functions with prefix notation
Putting parentheses around an infix operator converts it into a prefix function:
Prelude> (+) 1 2 3 Prelude> (*) 3 4 12
Using prefix functions with infix notation
Putting `
-marks around a prefix function allows us to use it like an infix function:
Prelude> let concatPrint x y = putStrLn $ (++) x y Prelude> concatPrint "a" "b" ab Prelude> "a" `concatPrint` "b" ab
Note that you can only normally do this with a function that takes two arguments. Actually, for a function taking more than two arguments, you can do it but it's not nearly as nice (note the need for extra parentheses):
Prelude> foldl (+) 0 [1..5] 15 Prelude> ((+) `foldl` 0) [1..5] 15