@amoszhou
2014-05-25T08:29:00.000000Z
字数 2022
阅读 1146
scala课后习题
def values(fun: (Int) => Int, low: Int, high: Int): List[(Int,Int)] = {
(low to high) zip {(low to high).map(fun(_))} toList
}
def ArrayMaxNumber(arr : Array[Int]):Int={
arr.reduceLeft((a,b)=>if (a>b) a else b)
}
def jiecheng(num :Int):Int={
(1 to num).reduceLeft(_*_)
}
def jiecheng(num: Int):Int={
(1 to num).foldLeft(1)(_*_)
}
def largest(fun : (Int)=>Int, inputs : Seq[Int] )={
inputs.map(fun).max
}
def largestInput(fun : (Int)=>Int, inputs : Seq[Int] )={
inputs.reduceLeft((a,b)=>if (fun(a) > fun(b)) a else b)
}
val pairs = (1 to 10) zip (11 to 20)
假定你想要对这个序列做某中操作—比如,给对偶中的值求和,但是你不能直接使用:
pairs.map(_ + )
函数 + _ 接受两个Int作为参数,而不是(Int,Int)对偶。编写函数adjustToPair,该函数接受一个类型为(Int,Int)=>Int的函数作为参数,并返回一个等效的, 可以以对偶作为参数的函数。举例来说就是:adjustToPair(_ * _)((6,7))应得到42。然后用这个函数通过map计算出各个对偶的元素之和
def adjustToPair(func:(Int,Int)=>Int):((Int,Int))=>Int={
(tuple:(Int,Int)) => func(tuple._1,tuple._2)
}
def compareArrayLength(srcArr : Array[String], compareLengh : Array[Int]):Boolean={
arr1.corresponds(arr2)(_.length == _)
}
val arr1 = Array("Hello","world","scala is funny")
val arr2 = Array(5,5,14)
println(compareArrayLength(arr1,arr2))
def unless(condition: =>Boolean)(block: =>Unit)={
if(!condition){
block
}
}
var x = 1
unless(x>10){
println(x)
x += 1
}
当然都需要,如果不用换名调用参数的话。代码将会是如下这样:
def unless(condition:()=>Boolean)(block:()=>Unit)={
if(!condition()){
block()
}
}
var x = 1
unless(()=>x>10){
()=>
println(x)
x += 1
}
如果不用柯里化的话,就惨不忍睹了。
def unless(condition:()=>Boolean,block:()=>Unit)={
if(!condition()){
block()
}
}
var x = 1
unless(()=>x>10 , {()=>println(x); x += 1;})
根本就达不到if语句这样的效果。