Unary operator

From HaskellWiki
Jump to navigation Jump to search

A unary operator is an operator with one parameter. In mathematics, they can be written in prefix notation like in or in postfix notation like in .

Haskell only has one built-in unary operator, namely the negation operator -. It is syntactic sugar for the Prelude.negate function and allows writing expressions like -a. Unary operators may also be defined and used by the programmer with similar rules to infix operators.

Negation operator

The standard parsing rules concerning the negation operator are somewhat controversial because they can lead to unexpected results. In particular, they conflict with operator sections and disallow subtraction sectioning. For example, expressions like map (- 2) are rejected by the compiler because (- 2) is interpreted as the negated digit -2 rather than the partial application of (-). There is a workaround to this: the subtract function from base can be used to write the previous example as map (subtract 2).

GHC supports two language extensions that modify the behaviour of the unary minus, NegativeLiterals and LexicalNegation. The latter effectively solves the aforementioned problem by parsing expressions like map (- 2) as expected.

Postfix operators

Standard Haskell does not support postfix operators. This is because expressions like (n !) are parsed as the partial application of an infix operator rather than the application of a unary operator (!). A typical use-case would be the factorial, which is written postfix in mathematical notation (i.e. )

GHC also supports a language extension to mitigate this deficiency, PostfixOperators. With it enabled, expressions like (n !) are parsed as ((!) n).


See also