Last active
December 15, 2015 22:49
-
-
Save mizanRahman/5335872 to your computer and use it in GitHub Desktop.
Scala code snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test | |
object TestSheet { | |
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet | |
def sum(a:Int,b:Int):Int = { | |
def sumF(acc:Int,a:Int,b:Int):Int = { | |
if(a>b) acc | |
else sumF(acc+a,a+1,b) | |
} | |
sumF(0,a,b) | |
} //> sum: (a: Int, b: Int)Int | |
def fact(a:Int):Int = { | |
def factF(acc: Int,a: Int): Int = { | |
if(a<0) -1 | |
else if(a==0) acc | |
else factF(acc*a,a-1) | |
} | |
factF(1,a) | |
} //> fact: (a: Int)Int | |
def coinChange(money: Int, coins: List[Int]): Int={ | |
def changeF(ways:Int, money: Int, coins: List[Int]):Int = { | |
if(money==0) ways+1 | |
else if(money<0) ways | |
else { | |
if(!coins.isEmpty) { | |
val acc= changeF(ways,money-coins.head, coins) | |
changeF(acc, money, coins.tail) | |
} | |
else ways | |
} | |
} | |
changeF(0,money,coins) | |
} //> coinChange: (money: Int, coins: List[Int])Int | |
sum(1,3) //> res0: Int = 6 | |
sum(3,3) //> res1: Int = 3 | |
sum(0,1) //> res2: Int = 1 | |
sum(1,99) //> res3: Int = 4950 | |
sum(2,1) //> res4: Int = 0 | |
fact(0) //> res5: Int = 1 | |
fact(1) //> res6: Int = 1 | |
fact(2) //> res7: Int = 2 | |
fact(3) //> res8: Int = 6 | |
fact(25) //> res9: Int = 2076180480 | |
coinChange(4, List(1,2)) //> res10: Int = 3 | |
coinChange(10,List(1,2,3)) //> res11: Int = 14 | |
coinChange(0,List(1,2,3)) //> res12: Int = 1 | |
coinChange(-1,List(1,2,3)) //> res13: Int = 0 | |
coinChange(100,List(1,2,3)) //> res14: Int = 884 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tail recursion Examples in Scala
I am getting introduced to Functional Programming using Scala. One thing that is coming out from my initial learning is that Functional programming demotivates to use loops and mutative (changable) variables. Instead, it relies heavily on recursion especially on Tail Recursion.
Here is some examples of tail recursion functions in Scala
Tail recursion: Why?