James Haigh
James Haigh

Reputation: 1272

How do I define a postfix operator in Haskell?

When working with angles in degrees, I want to define the degree symbol (°) to be used as a postfix operator. Currently, I use this line (in GHCi):

let o = pi/180

and use it like this:

tan(11*o)

but I want to just go:

tan 11°

which is much clearer. The degree operator should have higher precedence than ‘tan’ and other functions.

The closest I've got is:

let (°) x _ = x*pi/180

used like this:

tan(11°0)

but the default precedence means the parens are still needed, and with the dummy number, this alternative is worse than what I currently use.

Upvotes: 11

Views: 6112

Answers (2)

C. A. McCann
C. A. McCann

Reputation: 77424

You can't, at least in Haskell as defined by the Report. There is, however, a GHC extension that allows postfix operators.

Unfortunately this doesn't give you everything you want; in particular, it still requires parentheses, as the unary negation operator often does.

Upvotes: 17

amindfv
amindfv

Reputation: 8448

Check out fixity declarations, which allow you to change the precedence of infix operators. Be careful not to set the precedence too high, or other operators won't behave as expected.

For example:

infixl 7 °
(°) x _ = x*pi/180

Edit: ah, @Daniel Fischer's right - this won't work for your current needs because function application has the highest precedence

Upvotes: 3

Related Questions