packagecom.learn.scala.day16
importscala.math._
/**
* 第十六天函數(shù)
* Created by zhuqing on 2017/3/17.
*/
objectDay16Function {
defmain(args: Array[String]): Unit = {
/**
* 函數(shù)可以賦值給一個變量
* 函數(shù)有apply方法
*/
valtriple = (x: Double) =>3* x
/**
* 實(shí)際是:triple.apply(4)
*/
println(triple(4))
/**
* 10*3
*/
countTen(triple)
/**
*
* 10-5
*/
countTen((x: Double) => x -5)
/**
* 自動推斷x為Double類型
*/
countTen((x) => x -5)
/**
* 自動推斷“_”為第一個參數(shù)
*/
countTen(_ -5)
/**
* 是否math包下的方法
* _把方法轉(zhuǎn)成函數(shù)
*/
countTen(sqrt_)
/**
* multiplyBy(3); 返回 函數(shù)(x:Double)=> 3*x;
*/
valtriple2 =multiplyBy(3)
/**
* 3*10
*/
println(triple2(10))
/**
* 把柯里化方法multiply 賦值給變量
* 柯里化:將原來接受兩個參數(shù)的函數(shù)變成新的接受一個參數(shù)的函數(shù)的過程。
* 新的函數(shù)返回一個以原有第二個參數(shù)作為參數(shù)的函數(shù)
* 在這里:triple3=3*y
*/
valtriple3 =multiply(3) _
println(triple3(10))
println(indexOf("hello",'o'))
}
/**
* 函數(shù)可以作為方法的參數(shù)
* 作為參數(shù)的函數(shù)必須是參數(shù)為Double類型,返回值為double類型
*
*@param f
*@return
*/
defcountTen(f: (Double) => Double) = {
println(f(10))
}
/**
* 函數(shù)作為返回值
* 這是一個閉包:綁定了變量的函數(shù)。
*
*@param factor
*@return
*/
defmultiplyBy(factor: Double) = {
(x: Double) => factor * x;
}
/**
* 可柯里化的方法,功能與multiplyBy方法一樣
*-? ? *? def multiply(x:Double)=(y:Double)=>x*y
*
*@param x
*@param y
*@return
*/
defmultiply(x: Double)(y: Double) = x * y
/**
* scala 不提倡在方法中使用return
* 但是有時候不得不使用
*
*@param str
*@param ch
*@return
*/
defindexOf(str:String, ch: Char): Int = {
for(i <-0until str.length) {
valc = str.charAt(i)
if(c == ch) {
returni;
}
}
-1
}
}