--- a/Fahad/Scala/Chapter5.sc Sun Oct 26 11:17:40 2014 +0000
+++ b/Fahad/Scala/Chapter5.sc Sun Oct 26 16:42:28 2014 +0000
@@ -28,28 +28,79 @@
sumPowersOfTwo(2, 4)
*/
+ /*
def sum(f: Int => Int, a: Int, b: Int): Int =
- if (a > b) 0 else f(a) + sum(f, a + 1, b) //> sum: (f: Int => Int, a: Int, b: Int)Int
+ if (a > b) 0 else f(a) + sum(f, a + 1, b)
//def sumInts(a: Int, b: Int): Int = sum(id, a, b)
//def sumInts(a: Int, b: Int): Int = sum((x: Int) => x, a, b)
def sumInts(a: Int, b: Int): Int = sum(x => x, a, b)
- //> sumInts: (a: Int, b: Int)Int
//def sumSquares(a: Int, b: Int): Int = sum(square, a, b)
//def sumSquares(a: Int, b: Int): Int = sum((x: Int) => x * x, a, b)
def sumSquares(a: Int, b: Int): Int = sum(x => x * x, a, b)
- //> sumSquares: (a: Int, b: Int)Int
def sumPowersOfTwo(a: Int, b: Int): Int = sum(powerOfTwo, a, b)
- //> sumPowersOfTwo: (a: Int, b: Int)Int
- def id(x: Int): Int = x //> id: (x: Int)Int
- def square(x: Int): Int = x * x //> square: (x: Int)Int
+ def id(x: Int): Int = x
+ def square(x: Int): Int = x * x
+ */
def powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x - 1)
//> powerOfTwo: (x: Int)Int
-
+
+
// 5.2: Currying
-
-
-
+
+ def sum(f: Int => Int): (Int, Int) => Int = {
+ def sumF(a: Int, b: Int): Int =
+ if (a > b) 0 else f(a) + sumF(a + 1, b)
+ sumF
+ } //> sum: (f: Int => Int)(Int, Int) => Int
+
+ def sumInts = sum(x => x) //> sumInts: => (Int, Int) => Int
+ def sumSquares = sum(x => x * x) //> sumSquares: => (Int, Int) => Int
+ def sumPowersOfTwo = sum(powerOfTwo) //> sumPowersOfTwo: => (Int, Int) => Int
+ sumSquares(1,10) + sumPowersOfTwo(10,20) //> res0: Int = 2096513
+ sum(x => x * x)(2,4) //> res1: Int = 29
+
+ // 5.3: Finding Fixed Points of Functions
+
+ val tolerance = 0.001 //> tolerance : Double = 0.001
+ def isCloseEnough(x: Double, y: Double) = Math.abs((x-y) / x) < tolerance
+ //> isCloseEnough: (x: Double, y: Double)Boolean
+ def fixedPoint(f: Double => Double)(firstGuess: Double) = {
+ def iterate(guess: Double): Double = {
+ val next = f(guess)
+ if (isCloseEnough(guess, next)) next
+ else iterate(next)
+ }
+ iterate(firstGuess)
+ } //> fixedPoint: (f: Double => Double)(firstGuess: Double)Double
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
}
\ No newline at end of file