import scala.math._
//Technically, the _ turns the ceil method into a function. In Scala, you cannot manipulate methods, only functions
val fun: (Double) => Double = ceil //The _ behind the ceil function indicates that you really meant the function, and you didn’t just forget to supply the arguments.
fun(3.14)
//但是,The _ suffix is not necessary when you use a method name in a context where a function is expected
val f: (Double) => Double = ceil // No underscore needed,但是val f = ceil 则会报错
f(3.14)
Array(1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8).map(f)
//-------------------------------------------------------注意,下面说的方法和ceil的不同
//The ceil method is a method of the scala.math package object. If you
//have a method from a class, the syntax for turning it into a function is slightly
//different
//A function (String, Int) => Char
val f2 = (_:String)charAt(_:Int)
f2("hello",1)
//--上面的也可以用下面这种方法
val f3: (String, Int) => Char = _.charAt(_)
val threeNumAdd:(Double, Double, Double) => Double = _+_+_
threeNumAdd(1,2,3)
//--------------------------------------------------匿名函数
val triple = (x:Double) => x * 3
val tripleMe : Double => Double = x => x * 3
Array(3.14, 1.42, 2.0).map((x:Double)=> 3 * x)
//注意省去点号的写法:
//This is more common when a method is used in infix notation (without the dot).
Array(3.14, 1.42, 3.0) map ( (x: Double) => 3 * x )
Array(3.14, 1.42, 2.0).map( (x: Double) => 3 * x )
//注意上面两个自理大括号可以换成花括号{}
//---------------------------------Functions with Function Parameters或者返回一个函数
def valueAtOneQuarter(f: (Double) => Double) = f(0.25)
valueAtOneQuarter(ceil) // 1.0
valueAtOneQuarter(sqrt _)
def mulBy(factor : Double) = (x : Double) => factor * x
//-------------------------------函数参数类型推导
//If a parameter occurs only once on the right-hand side of the =>,you can replace it with an underscore:
valueAtOneQuarter(3 * _) //得到0.75
//只有当参数类型可以推到的时候方可省略类型:
//val fun1 = 3 * _ // Error: Can’t infer types
val fun2 = 3 * (_: Double) // OK
val fun3: (Double) => Double = 3 * _ // OK because we specified the type for fun
(1 to 9).map("*" * _).foreach(println(_))
(1 to 9).reduceLeft(_ * _)
//(...((1 * 2) * 3) * ... * 9) 前面省略号表示省略的括号
"Mary had a little lamb".split(" ").sortWith(_.length < _.length)
柯里化:
def mulOneAtATime(x: Int)(y: Int) = x * y
mulOneAtATime(3)(4)
控制抽象:比如我们自己定义一个until功能:
Scala programmers can build control abstractions: functions
that look like language keywords
def until(condition: => Boolean)(block: => Unit) {
if (!condition) {
block
until(condition)(block)
}
}
var x = 10
until(x == 0) {
x -= 1
println(x)
}
注意上面until函数的定义也使用了currying(注意两个参数分开写的)
网友评论