请同学们多多指教
package com.hotcharm.www
object Chapter2 {
/**
*
* EXERCISE 2.1
* Write a recursive function to get the nth Fibonacci number (http://mng.bz/C29s).
* The first two Fibonacci numbers are 0 and 1. The nth number is always the sum of the
* previous two—the sequence begins 0, 1, 1, 2, 3, 5. Your definition should use a
* local tail-recursive function.
*
*/
def fib(n: Int): Int = {
@annotation.tailrec
def fibIter(n: Int, a: Int, b: Int): Int = {
if (n <= 1) a
else fibIter(n - 1, b, a + b)
}
fibIter(n, 0, 1)
}
/**
*
* EXERCISE 2.2
* Implement isSorted, which checks whether an Array[A] is sorted according to a
* given comparison function:
*
*/
def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
@annotation.tailrec
def isSortedIter(n: Int): Boolean = {
if (n < as.length - 1) {
if (ordered(as(n), as(n + 1)))
isSortedIter(n + 1)
else
false
} else {
true
}
}
if (as.length <= 1) true else isSortedIter(0)
}
/**
* EXERCISE 2.3
* Let’s look at another example, currying,9 which converts a function f of two arguments
* into a function of one argument that partially applies f. Here again there’s only one
* implementation that compiles. Write this implementation.
*/
def curry[A, B, C](f: (A, B) => C): A => (B => C) = (a: A) => ((b: B) => f(a, b))
/**
* EXERCISE 2.4
* Implement uncurry, which reverses the transformation of curry. Note that since =>
* associates to the right, A => (B => C) can be written as A => B => C.
*/
def uncurry[A,B,C](f: A => B => C): (A, B) => C = (a: A, b: B) => f(a)(b)
/**
* EXERCISE 2.5
* Implement the higher-order function that composes two functions.
*/
def compose[A,B,C](f: B => C, g: A => B): A => C = (a: A) => f(g(a))
}
package com.hotcharm.www
import org.scalatest._
import Chapter2._
class TestChapter2 extends FunSuite {
test("fib(n) return the nth fib right"){
assert(fib(1) == 0)
assert(fib(2) == 1)
assert(fib(3) == 1)
assert(fib(6) == 5)
}
test("Array is sorted or not"){
assert(isSorted(Array(1,1,3,5,6), (x:Int, y:Int)=>(x <= y)))
assert(! isSorted(Array(1,1,6,5,6), (x:Int, y:Int)=>(x <= y)))
}
def sum(i:Int, j:Int) = i + j
test("curry"){
assert(curry(sum)(1)(2) == 3 )
}
test("uncurry"){
assert(uncurry(curry(sum))(1,2) == 3 )
}
def dStr(a:String) = a + a
def len(b: String) = b.length()
test("compose"){
assert(compose(len, dStr)("abc")==6)
}
}