Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 358
James Haigh Avatar asked Apr 24 '13 15:04

James Haigh


People also ask

What does ++ mean in Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combine" them into a single list.

What is the OR operator in Haskell?

In Haskell we have or operator to compare the values of the variable, this operator also comes under the lexical notation of the Haskell programming language. This operator works in the same way as any other programming language, it just returns true or false based on the input we have provided.


2 Answers

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.

like image 93
C. A. McCann Avatar answered Oct 12 '22 23:10

C. A. McCann


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

like image 33
amindfv Avatar answered Oct 12 '22 23:10

amindfv