匿名函数与高阶函数的使用

场景

匿名函数的语法与常用使用方式、高阶函数初体验

实验
package com.scode.scala
import scala.io.Source
/**
 * author: Ivy Peng
 * function: 1、学习匿名函数作为函数参数的使用方式 
 * 	     2、了解函数内部定义函数-实现高内聚、低耦合
 * 	     3、高阶函数-初体验:多重嵌套
 * date:2016/03/09 23.36
 * sum:
 * 匿名函数语法:(arg:argType,...)=> operations  。
 */
object FunctionOps
{
  def main(args:Array[String]):Unit =
  {
    val width = args(0).toInt
    for(arg<-args.drop(1))
      processData(arg, width)
      
      functionChild
      
      println(high_order_fun2(scala.math.ceil _))
  }
  
  /**
   * 匿名函数语法:(arg:argType,...)=> operations 
   * 若参数只有一个,则可以简写成  arg =>operations
   */
  def functionChild()
  {
    var increase=(x:Int)=>x+10 //匿名函数(),方法体只有一行,用 => 链接起来
    println(increase(10)) 
    increase=(x:Int)=>x+100
    
    val someNums = List(-1,2,3,0)
    someNums.foreach((x:Int)=>print(x+" "))
    println
    someNums.filter((x:Int)=>x>0).foreach(x=>println(x+" "))
    someNums.filter((x)=>x>0).foreach(x=>println(x+" "))
    someNums.filter(x=>x>0).foreach(x=>println(x+" "))
    
    val f = (_: Int)+(_: Int)
    println(f(5,10))
  }
  
  /**
   * 高内聚低耦合
   */
  def processData(filename:String , width:Int)
  {
    def processLine(line:String) = 
    {
      if(line.length>width)
      {
        println(filename+":"+line)
      }
    }
    val file = Source.fromFile(filename);
    for(line<-file.getLines)
    {
      processLine(line)
    }
  }
  
  /**
   * 高阶函数-初体验
   */
  def high_order_fun()
  {
    (1 to 9).map("*" * _).foreach(println _)
    (1 to 9).filter(_%2 ==0).foreach(println)
    println((1 to 4).reduceLeft(_*_))
    
     "you are my sunshine ,my only sunshine".split(" ").
     sortWith(_.length<_.length).foreach(println)
     
    val fun = scala.math.ceil _;
    val num = 3.14
    println(fun(num))
    Array(2,3.3,4.3).map(fun).foreach(println _)
  }
  
  /**
   * 高阶函数:函数作为函数的参数
   * 注:(Double)=>Double : 对函数的参数(Double型)不做处理
   */
  def high_order_fun2(f:(Double)=>Double) = f(0.29)
}
参考文献
scala 深入浅出实战经典 . 王家林



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值