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")
}
}
}
快学Scala习题答案(第12章高阶函数)
最新推荐文章于 2020-07-29 23:21:03 发布