[Infix functions. Bryan O'Sullivan **20070721051058] { hunk ./en/ch03-funcs-types.xml 1150 + + + Infix functions + + Usually, when we define or call a function in Haskell, we + write the name of the function, followed by its arguments; this + is called prefix notation, because the name of the function + comes before its arguments. For a function that takes two + arguments, we have the option of using it in + infix form, between its first and second + arguments. This allows us to write expressions using functions + as if they were infix operators. + + The syntax for defining or calling a function in infix form + is to enclose the name of the function in backtick characters + (sometimes known as backquotes). Here's a simple infix + definition. + + &Plus.hs:plus; + + Defining a function in infix form doesn't change anything + about the behaviour of the function. We can call the function + using infix or prefix notation, as we prefer. + + &infix.ghci:plus; + + Infix notation is useful for more than just our own + functions. For example, Haskell's standard + Data.List module defines a function, + isPrefixOf, that indicates whether all + elements of its first argument are equal to the first elements + of its second argument. + + &infix.ghci:type; + + Let's define a few variables in &ghci;. + + &infix.ghci:vars; + + If we call isPrefixOf using prefix + notation, we can have a hard time remembering which argument + we're checking for as a prefix of the other. + + &infix.ghci:prefix; + + But if we use infix notation, the code reads + more naturally; it's now obvious that we're checking the + variable on the left to see if it's a prefix of the variable on + the right. + + &infix.ghci:infix; + + There's no hard-and-fast rule that dictates when you ought + to use infix versus prefix notation, although prefix notation is + far more common. It's best to choose whichever makes your code + more readable in a specific situation. + + + The backtick notation is not a general mechanism: it's a + piece of special syntax that applies only to names. For + example, we can't put backticks around an expression that + returns a function, and then treat that as an infix + function. + + addfile ./examples/ch03/Plus.hs hunk ./examples/ch03/Plus.hs 1 +{-- snippet plus --} +a `plus` b = a + b +{-- /snippet plus --} addfile ./examples/ch03/infix.ghci hunk ./examples/ch03/infix.ghci 1 +:load Plus + +--# plus +1 `plus` 2 +plus 1 2 + +--# type +:module +Data.List +:type isPrefixOf + +--# vars +let string = "foo" +let other = "foobar" + +--# prefix +isprefixOf string other + +--# infix +string `isPrefixOf` other }