Unary operator
A unary operator is an operator with one parameter. In mathematics, they can be written in prefix notation like in Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "https://wikimedia.org/api/rest_v1/":): {\displaystyle -2} or in postfix notation like in Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "https://wikimedia.org/api/rest_v1/":): {\displaystyle 2!} .
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[edit]
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[edit]
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. Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "https://wikimedia.org/api/rest_v1/":): {\displaystyle n!}
)
GHC also supports a language extension to mitigate this deficiency, PostfixOperators.
With it enabled, expressions like (n !)
are parsed as ((!) n)
.
See also[edit]
- GHC docs: Syntax extensions
- Haskell-Cafe: Discussion on unary minus with title
map (-2) [1..5]
- Haskell-Cafe: Custom unary operator extension?