diff -r 2345ba5b4264 -r 197babb05539 Fahad/Scala/Chapter5.sc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Fahad/Scala/Chapter5.sc Sat Oct 25 17:28:56 2014 +0100 @@ -0,0 +1,55 @@ +package greeter + +object Chapter5 { + println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet + + ///////////////////////////////////////////////////////////////////////////// + // CHAPTER 5: FIRST-CLASS FUNCTIONS + + /* + // Write a function to sumall integers between two given numbers a and b + def sumInts(a: Int, b: Int): Int = + if (a > b) 0 else a + sumInts(a + 1, b) + + sumInts(1, 5) + + //Write a function to sum the squares of all integers between two given numbers a and b + def square(x: Int): Int = x * x + def sumSquares(a: Int, b: Int): Int = + if (a > b) 0 else square(a) + sumSquares(a + 1, b) + + square(5) + + //Write a function to sum the powers 2n of all integers n between two given numbers a and b: + def powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x - 1) + def sumPowersOfTwo(a: Int, b: Int): Int = + if (a > b) 0 else powerOfTwo(a) + sumPowersOfTwo(a + 1, b) + + 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 + + //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 powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x - 1) + //> powerOfTwo: (x: Int)Int + + // 5.2: Currying + + + + +} \ No newline at end of file