Functional Programming in Scala第二章练习

请同学们多多指教

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)
   }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值