Skip to content

CodeNinjaResearch/tailCallFactorial

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build

Build Status Kotlin Maven Central

Time

Value

Configure

private fun listFactorial() = listOf(Recursive(),TailCallFunctional(), Functional(), Iterative())

Api

interface Factorial {
    fun method(n : Int) : Long
}

##Recursive

class Recursive : Factorial {
    init {
        println("Initialize Factorial Recursive")
    }

   /**
    *  fact(2)
    *  (* 2 (fact 1)))
    *  (* 2 (* 1 (fact 0))))
    *  (* 2 (* 1 1)))
    *  (* 2 1))
    *  2
    */
    override fun method(n:Long): Long {
       return when(n){
           0L -> 1L
           else ->  n * method(n-1)
       }
    }

}

Funtional

class Functional : Factorial {
    init {
        println("Initialize Factorial Functional")
    }

    override fun method(n: Long) : Long {
         fun _functional(n : Long, res: Long) :Long {
            return if(n <= 0) res
            else _functional(n -1, n * res)
        }
        return _functional(n,1)
    }
}

Tail Call Functional

class TailCallFunctional : Factorial {                        
    init {                                                    
        println("Initialize Factorial Tail Call Functional")  
    }                                                         
                                                              
    /**                                                       
     *  (fact 2)                                              
     *  (tailrec-fact 2 1)                                    
     *  (tailrec-fact 1 2)                                    
     *  (tailrec-fact 0 2)                                    
     *  2                                                     
     */                                                       
    override fun method(n: Long) : Long {             
        tailrec fun _method(n : Long, res: Long) :Long {          
            return if(n <= 0) res                             
            else _method(n -1, n * res)                   
        }                                                     
        return _method(n,1)                               
    }                                                         
}                                                             

Iterative

class Iterative : Factorial {
    init {
        println("Initialize Factorial Iterative")
    }

    override fun method(n:Long) : Long {
        var res = 1L
        for(i in 1..n)
            res *= i
        return res
    }
}

References:

About

Tail Call Optimization / Kotlin - Paper

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages