Created
July 26, 2014 13:42
-
-
Save ilovejs/77b2cfc8aa18c8e964a9 to your computer and use it in GitHub Desktop.
worksheet of week1 for course <Functional Programming Principles in Scala>
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
import scala.annotation.tailrec | |
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet | |
def loop: Boolean = loop | |
def abs(x: Double) = if (x < 0) -x else x | |
def and(x: Boolean, y:Boolean) = if (x) y else false | |
//> and: (x: Boolean, y: Boolean)Boolean | |
and(true, true) //> res0: Boolean = true | |
and(true, false) //> res1: Boolean = false | |
and(false, true) //> res2: Boolean = false | |
and(false, false) //> res3: Boolean = false | |
def sqrt(x: Double) = { | |
def sqrtIter(guess: Double, x: Double): Double = | |
if (isGoodEnough(guess, x)) guess | |
else sqrtIter(improve(guess, x), x) | |
//proportionally small error | |
def isGoodEnough(guess: Double, x: Double): Boolean = | |
abs(guess * guess - x) / x < 0.001 | |
def improve(guess: Double, x: Double) = | |
(guess + x / guess) / 2 | |
sqrtIter(1.0, x) | |
} | |
def sqrtSimplify(x: Double) = { | |
def sqrtIter(guess: Double): Double = | |
if (isGoodEnough(guess)) guess | |
else sqrtIter(improve(guess)) | |
//proportionally small error | |
def isGoodEnough(guess: Double): Boolean = | |
abs(guess * guess - x) / x < 0.001 | |
def improve(guess: Double) = | |
(guess + x / guess) / 2 | |
sqrtIter(1.0) | |
} | |
sqrt(2) | |
sqrt(3) | |
sqrt(1e-6) //expect: 1e-3 | |
sqrt(1e60) //expect: 1e30 | |
//@tailrec | |
def gcd(a: Int, b: Int): Int = | |
if(b == 0) a else gcd(b, a % b) | |
//non-tail recursion | |
def factorialNT(n: Int): Int = | |
if (n == 0) 1 else n * factorial(n - 1) | |
def factorial(n: Int): Int = { | |
//loop call itself is ===>> tail recursion function | |
def loop(acc: Int, n: Int): Int = | |
if(n == 0) acc | |
else loop(acc * n ,(n - 1)) | |
loop(1, n); | |
} | |
factorial(3) | |
factorial(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment