Difference between revisions of "$"

From HaskellWiki
Jump to navigation Jump to search
(A new page for the $ operator explaining its usefulness)
 
m (Added Category:FAQ)
 
(One intermediate revision by one other user not shown)
Line 15: Line 15:
 
($) :: (a -> b) -> a -> b
 
($) :: (a -> b) -> a -> b
 
f $ x = f x
 
f $ x = f x
  +
  +
==Note==
  +
The $ syntax is also used in [[Template Haskell]] with an entirely different meaning. If the $ is ''immediately followed'' by a letter or a left parenthesis (with no intervening white space), then it is understood by the GHC compiler as a Template Haskell splice and not the infix operator described above. To get the infix operator be sure to separate the $ from the right argument by at least one white space.
   
 
==See also==
 
==See also==
 
*[[$!]]
 
*[[$!]]
  +
  +
  +
[[Category:FAQ]]

Latest revision as of 00:09, 1 October 2016

$ is an infix operator often seen in Haskell code. It applies the function on its left to the value on its right. At first glance this operator appears redundant, since ordinary application (f x) means the same as (f $ x). However, $ has the lowest, right-associative binding precedence (infixr 0), so it sometimes allows parentheses to be omitted; for example:

    f $ g $ h x  =  f (g (h x))

If $ were omitted, the parse would be different:

    f g h x = ((f g) h) x

It is also useful in higher-order situations, such as map ($ 0) xs, or zipWith ($) fs xs.

Definition

$ comes from the Prelude, where it is defined as:

    infixr 0  $
    ($) :: (a -> b) -> a -> b
    f $ x = f x

Note

The $ syntax is also used in Template Haskell with an entirely different meaning. If the $ is immediately followed by a letter or a left parenthesis (with no intervening white space), then it is understood by the GHC compiler as a Template Haskell splice and not the infix operator described above. To get the infix operator be sure to separate the $ from the right argument by at least one white space.

See also