Adding a ! factorial operator

  • strict warning: Non-static method view::load() should not be called statically in /home/eob/ on line 842.
  • strict warning: Declaration of views_handler_argument::init() should be compatible with views_handler::init(&$view, $options) in /home/eob/ on line 745.
  • strict warning: Declaration of views_handler_filter::options_validate() should be compatible with views_handler::options_validate($form, &$form_state) in /home/eob/ on line 589.
  • strict warning: Declaration of views_handler_filter::options_submit() should be compatible with views_handler::options_submit($form, &$form_state) in /home/eob/ on line 589.
  • strict warning: Declaration of views_handler_filter_boolean_operator::value_validate() should be compatible with views_handler_filter::value_validate($form, &$form_state) in /home/eob/ on line 149.
  • strict warning: Declaration of views_plugin_row::options_validate() should be compatible with views_plugin::options_validate(&$form, &$form_state) in /home/eob/ on line 135.
  • strict warning: Declaration of views_plugin_row::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in /home/eob/ on line 135.

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.


Typo in the non-recursive version

Since foldRight actually uses recursion underneath the covers I think you meant for your non-recursive version to be:

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

Otherwise you will still be using recursion and will probably end up running out of heap space.

Also it might make more sense to use BigInt for the return value since even small factorials will easily overflow both Int and Long.

> omeprazole 40 mg price - buy misoprostol and mifepristone
- valtrex buy online no prescription - where to buy asacol - cell spy phone - generic levitra -