Currying & Partial[applied] function 初体验

来源:互联网 发布:日本黑科技 知乎 编辑:程序博客网 时间:2024/05/24 01:47
参考文献

1、王家林.scala深入浅出实战经典

2、http://www.cnblogs.com/nixil/archive/2012/05/16/2503722.html

3、http://spreadscala.iteye.com/blog/705466

场景

scala中柯里化与偏函数的基本概念与应用初体验

实验

<pre name="code" class="java"> def <pre name="code" class="java">curring
(x:Int,y:Int)=x*y;
package com.scode.scala/** * author: Ivy Peng * function: Curring & Partial Function & Partial applied Function 学习 * date:2016/03/22 22.34 * 1、Curring:把接收多个参数的函数变成接收单一参数的函数。 * 2、偏函数:偷懒,简化函数调用时的参数传递 * collectionA.zip(collectionB) */object Curring_Partial_Function{ def main(args: Array[String]): Unit = { /* * Currying 柯里化 */ def multiple(x:Int,y:Int)=x*y; 
    def curring(x:Int)= (y:Int)=> x*y;  // Curry
def curring2(x:Int)(y:Int)=x*y; // 简化版Curry println(curring(3)(8)) //Currying应用:_.equalsIgnoreCase(_) val a = Array("Hello","World") val b = Array("Hello","Spark") println(a.corresponds(b)(_.equalsIgnoreCase(_))) // 参见 “问题”中相关解说 /* * 偏函数 * 定义 :具有类型PartialFunction[-A,+B]的一种函数。A是其接受的函数类型,B是其返回的结果类型 * 特点:只接受和处理其参数定义域的一个子集 */ def p1:PartialFunction[Int, Int] = { case x if x > 1 => 1 } def p2 = (x:Int) => x match { case x if x > 1 => 1 } println(p2 (0))//这里会抛异常:Exception in thread "main" scala.MatchError: 0 (of class java.lang.Integer) /* * 偏应用函数: 偷懒,实现函数sum的功能-求三个数字之和,函数 parFun_2只需要传递 一个参数 */ def sum(x:Int,y:Int,z:Int)=x+y+z val parFun_1 = sum _ println(parFun_1(1,2,3)) println(parFun_1.apply(1,2,3)) val parFun_2 = sum(1,_:Int,3) println(parFun_2(2)) println(parFun_2(10)) } }
问题

林哥在解说Currying应用的时候以代码段

val a = Array("Hello","World")    val b = Array("Hello","Spark")    println(a.corresponds(b)(_.equalsIgnoreCase(_)))
为例,通过查看 corresponds 方法的源代码:

 def corresponds[B](that: GenSeq[B])(p: (A,B) => Boolean): Boolean = {    val i = this.iterator    val j = that.iterator    while (i.hasNext && j.hasNext)      if (!p(i.next(), j.next()))        return false    !i.hasNext && !j.hasNext  }
解说Currying是如何在语言级别简化scala代码的编写:a.corresponds(b)(_.equalsIgnoreCase(_))  【这里 :_.equalsIgnoreCase(_)  ,编译器利用 CurryIng 能推断出 _ 表示String类型的字符 ? Mr.Snail表示有点蒙圈啊 ,有待后续进一步分析。


0 0
原创粉丝点击