The other day I wanted to work out what 52 factorial was. I’d beeen to a pub quiz the night before. What can I say?
It is pretty easy to make the factorial function in Haskell. Something ike this usually suffices. fac :: Integer -> Integer
fac n = product [1..n]
I wanted to be a bit clever and make a proper postfix operator, so that I could write 52! As it turns out there does exist a Postfix operator GHCi extension. It is described thus
The -XPostfixOperators flag enables a small extension to the syntax of left operator sections, which allows you to define postfix operators. The extension is this: the left section
(e !)is equivalent (from the point of view of both type checking and execution) to the expression((!) e)(for any expression e and operator (!). The strict Haskell 98 interpretation is that the section is equivalent to(\y -> (!) e y)That is, the operator must be a function of two arguments. GHC allows it to take only one argument, and that in turn allows you to write the function postfix.
It took me a few minutes to work out how to get the following code to run in GHCi.{-# LANGUAGE PostfixOperators #-}
(!) :: Integer -> Integer
(!) n = product [1..n]
As it turns out the solution was rather straightforward. I needed to load the extension directly in GHCi thus :set -XPostfixOperators
So now I can write 52 factorial almost properly, though I still need to use brackets. *Main> :l fact.hs
[1 of 1] Compiling Main ( fact.hs, interpreted )
Ok, modules loaded: Main.
*Main> :set -XPostfixOperators
*Main> (52!)
80658175170943878571660636856403766975289505440883277824000000000000
*Main>