快学Scala习题答案(第12章高阶函数)



object exc12 {

  def main(args: Array[String]){
    //1
    def values(f:Int=>Int, low:Int , high:Int)={
      //for(x <- low to high )yield x->f(x)
      (low to high).map(x=>x->f(x))
    }
    println(values( x=>x*x, -5,5))

    //2
    assert( Array(2,13,5,12).reduceLeft(Math.max) == 13 )

    //3
    def factorial(x:Int)= (1 to x).reduceLeft(_*_)//(1 to x).product
    assert( factorial(4) == 24 )

    //4
    println( 1 to -3)//Range()
    def factorial2(x:Int)= (1 /: (1 to x))(_*_) //.foldLeft( 1)( _*_ )
    assert( factorial2(0) == 1)

    //5
    def largest(f:Int=>Int, inputs:Seq[Int])={
      inputs.reduceLeft( (x,y)=> {
        if(f(x)>f(y)) f(x) else f(y)
      }
      )
    }
    println( largest(x=>10*x-x*x,1 to 10))// should be 25, why 9???

    //6
    def largest2(f:Int=>Int, inputs:Seq[Int])={
      inputs.reduceLeft( (x,y)=> {
        if(f(x)>f(y))
          x
        else
          y} )
    }
    println( largest2(x=>10*x-x*x,1 to 10))//5

    //7 **
    def adjustToPair(f:(Int,Int)=>Int)={
      tup:(Int,Int) => f(tup._1, tup._2)
    }
    println( adjustToPair(_*_)((6,7))==42)
    println( ((1 to 10) zip (1 to 10)).map(adjustToPair(_+_)))
    
    //8
    println( Array("abc","a","1234").corresponds(Array(3,1,4))( (s:String,l:Int)=>if( s.size == l) true else false))

    //10
    def unless(condition: =>Boolean)(action: =>Unit ) ={
      if( !condition ){
        action
      }
    }
    unless( 3 == 1){
      println("not equals")
    }
  }
}



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值