Personal tools

Infix operator

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
m (Categorize, link to "section of an infix operator")
(Correct a claim: backticks work even for functions with more than two arguments)
 
(One intermediate revision by one user not shown)
Line 23: Line 23:
 
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):
   
==Section==
+
Prelude> foldl (+) 0 [1..5]
See the article [[section of an infix operator]]
+
15
  +
Prelude> ((+) `foldl` 0) [1..5]
  +
15
  +
  +
== See also ==
  +
  +
* [[section of an infix operator]]
  +
* [[use of infix operators]]

Latest revision as of 13:34, 6 January 2008

Contents

[edit] 1 Overview

Functions in Haskell are usually called using prefix notation, or the function name followed by its arguments. However, some functions, like +, are called with infix notation, or putting the function name between its two arguments.

[edit] 2 Using infix functions with prefix notation

Putting parenthesis around an infix operator converts it into a prefix function:

 Prelude> (+) 1 2
 3
 Prelude> (*) 3 4
 12

[edit] 3 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

[edit] 4 See also