Adding a ! factorial operator

If you learned about recursion you probably were given the factorial function as a simple example. Here it is in Scala:

def factorial(n:Int):Int = if(n==0) 1 else n * factorial(n-1)

Very nice. Now you can do factorial(6) to get the answer 720.

But would it not be nicer if you could use standard mathematical notation and do 6!

Well you can. Simply add this simple pimping implicit somewhere in scope:

implicit def pimp(i:Int) = new { def ! = factorial(i) }

Now you can use the ! operator after any integer. To avoid confusing the compiler, however, you may have to add some extra parentheses:

(3!) + (3!)


Can we do better? Well if we avoid using recursion we can do it all in one line:

implicit def pimp(n:Int) = new { def ! = ((1 to n) :\ 1) ( _ * _ ) }

Here we are generating the integers 1,2,3,...,n and using the :/ fold operator to multiply them all together.

Adding a exponentiation operator to Double

Using the same pattern that we used to add the ! factorial operator to Int we can add an ** exponentiation operator to Double.

def pow(x:Double,k:Int):Double = if(k==1)
   (if (k%2==0) 1.0 else x) * pow(x*x,k/2)

implicit def pimp(x:Double) = new { def **(k:Int) = pow(x,k) }

You can now, for example, type in 2.0 ** 8 to get 256.0 or Math.Pi ** 4 to get 97.40909103400243

- valtrex buy online no prescription - where to buy asacol - cell spy phone - generic levitra -