×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Scala
Posted by: osocron coder
Added: Oct 10, 2016 7:23 PM
Views: 10
The steps taken to get the fix function.
  1. /**
  2.     * This is the original recursive factorial function
  3.     *
  4.     * @param n A positive integer number
  5.     * @return  The factorial of n
  6.     */
  7.   def factorial(n: Int): Int = if (n == 0) 1 else factorial(n - 1) * n
  8.  
  9.   /**
  10.     * If we abstract over the factorial function so that the call to factorial
  11.     * is replaced to a call to a function f that is taken as a parameter then
  12.     * we are beginning to create an anonymous recursive function.
  13.     *
  14.     * @param factorial The factorial function as a parameter
  15.     * @return          The result of computing the recursive function factorial.
  16.     */
  17.   def semi_factorial(factorial: Int => Int): Int => Int =
  18.     n => if (n == 0) 1 else factorial(n - 1) * n
  19.  
  20.   /**
  21.     * This is the tricky part, if we abstract the semi_factorial function and
  22.     * pass it as a parameter to this function we get the following.
  23.     *
  24.     * @param semi_factorial The semi_factorial function taken as a parameter
  25.     * @return               A function from Int to Int
  26.     */
  27.   def semi_abstract(semi_factorial: (Int => Int) => (Int => Int)): Int => Int =
  28.     semi_factorial(semi_abstract(semi_factorial))
  29.  
  30.   /**
  31.     * If we write semi_factorial in a type generic way we get the following
  32.     *
  33.     * @param f   A function that takes a function as a paramter and returns a function
  34.     * @tparam A  The first type parameter of the function
  35.     * @tparam B  The second type parameter of the function
  36.     * @return    A function from A to B
  37.     */
  38.   def fix[A, B](f: (A => B) => (A => B)): A => B = f(fix(f))(_)