泛函编程(4)-深入Scala函数类
既然是泛函编程,多了解一下函数自然是免不了的了:
方法(Method)不等于函数(Function)
方法不是函数但可以转化成函数;可以手工转换或者由编译器(compiler)在适当的情况下自动转换。反向转换则不然;函数是无法转换到方法的。先看看下面的例子:
1 scala> def aMethod(x: Int): Int = x + 10 2 aMethod: (x: Int)Int 3 4 scala> val aFunction = (x: Int) => x + 10 5 aFunction: Int => Int = <function1>
aMethod 与 aFunction 在类型上是不同的。再看看下面:
1 scala> aFunction 2 res0: Int => Int = <function1> 3 4 scala> aMethod 5 <console>:9: error: missing arguments for method aMethod; 6 follow this method with `_' if you want to treat it as a partially applied function 7 aMethod
引用方法必须提供完整的参数清单,引用函数则无须。把方法转换成函数呢?在参数位置用 _ 来进行转换:
1 scala> val toFunction = aMethod _ 2 toFunction: Int => Int = <function1> 3 4 scala> toFunction 5 res2: Int => Int = <function1>
aMethod转换成函数toFunctions后具备了函数的特性。
我们称函数为“头等类值”(first class value),可以当作高阶函数的参数或返回值。但方法不是“头等类值”,不能当作参数。那么怎么解释下面例子里的代码呢?
1 def main(args: Array[String]): Unit = { 2 println(formatResult("absolute value", -42, abs)) 3 println(formatResult("factorial", 7, factorial)) 4 println(formatResult("increment", 7, (x: Int) => x + 1)) 5 println(formatResult("increment2", 7, (x) => x + 1)) 6 println(formatResult("increment3", 7, x => x + 1)) 7 println(formatResult("increment4", 7, _ + 1)) 8 println(formatResult("increment5", 7, x => { val r = x + 1; r })) 9 }
在这里abs, factorial都是方法。传入高阶函数formatResult中能行吗?下面是运行后的结果:
1 The absolute value of -42 is 42 2 The factorial of 7 is 5040 3 The increment of 7 is 8 4 The increment2 of 7 is 8 5 The increment3 of 7 is 8 6 The increment4 of 7 is 8 7 The increment5 of 7 is 8
没出错呀。难道方法是可以当作传入参数的吗?实际上这段程序在编译的时候由编译器自动进行了转换。Scala的编译器能针对需要函数的地方把方法转换成函数。
函数就是普通的对象
下面是一个函数文本:
1 scala> (a: Int, b: Int) => a + b 2 res4: (Int, Int) => Int = <function2>
编译时编译器会把它转换成下面的代码:
1 val addThem = new Function2[Int, Int, Int] { 2 def apply(a: Int, b: Int) = a + b 3 }
这里Function2是Scala语言标准类对象,res4(1+2) ===> addThem.apply(1,2)
多态函数
为了示范Scala的多态函数,我们先从下面的一个例子开始:从一个整数数组中找出第一个匹配数的位置:
1 def findFirstInt(arr: Array[Int], target: Int): Int = { 2 def loop(idx: Int): Int = idx match { 3 case l if (l >= arr.length) => -1 //indicate not found 4 case i if (arr(i) == target) => idx 5 case _ => loop(idx + 1) 6 } 7 loop(0) 8 } //> findFirst: (arr: Array[Int], target: Int)Int 9 findFirstInt(Array(2,4,3,9,0),3) //> res53: Int = 2 10 findFirstInt(Array(2,4,3,9,0),7) //> res54: Int = -1
从一个字串数组中找出第一个匹配字串的位置:
1 def findFirstString(arr: Array[String], target: String): Int = { 2 def loop(idx: Int): Int = idx match { 3 case l if (l >= arr.length) => -1 //indicate not found 4 case i if (arr(i) == target) => idx 5 case _ => loop(idx + 1) 6 } 7 loop(0) 8 } //> findFirstString: (arr: Array[String], target: String)Int 9 findFirstString(Array("Hello","My","World"),"My") 10 //> res55: Int = 1 11 findFirstString(Array("Hello","My","World"),"Yours") 12 //> res56: Int = -1
这个函数与上面整数数组例子有许多相似之处,或者说基本上是一致的。这样我们可以通过多态函数把共通点抽象出来:
1 def findFirstA[A](arr: Array[A],target: A)(equ: (A,A) => Boolean): Int = { 2 def loop(idx: Int): Int = idx match { 3 case l if (l >= arr.length) => -1 //indicate not found 4 case i if (equ(arr(i),target)) => idx 5 case _ => loop(idx + 1) 6 } 7 loop(0) 8 9 } //> findFirstA: [A](arr: Array[A], target: A)(equ: (A, A) => Boolean)Int 10 findFirstA[Int](Array(2,4,3,9,0),3)((x,y) => x == y) 11 //> res57: Int = 2 12 findFirstA[String](Array("Hello","My","World"),"My")((x,y) => x == y) 13 //> res58: Int = 1
findFirstA是个多态函数。A是一个类型变量。我们可以说findFirstA是个针对类型变量A的多态函数。注意我们在findFirstA增加了一个参数清单- (equ: (A,A) => Boolean)。这是因为我们还无法确定A的类型。那么我们必须提供A类型的对比函数。我们可以用findFirstA针对整数、字串进行操作。我们也可以对其它类型进行操作,只要我们能提供那种类型的比较函数。
泛函编程说的白点就是摆弄函数。把函数摆过来弄过去的就完成了编程的过程。从下面的例子可以一探端倪:
纯函数是可以部分作用(partially apply)的:对一个多入参函数可以分多次每次作用(apply)一个参数
1 def partialApply[A,B,C](a: A, f: (B,C) => C): B => C
通过函数partialApply可以把一个两个入参的函数f分分两次作用它的参数:引用partialApply是作用参数a,形成一个需要参数B的函数。
两个参数作用(apply)了其中一个,所以称为部分作用。该如何实现:
1 def partialApply[A,B,C](a: A, f: (A,B) => C): B => C = (b: B) => f(a,b) 2 //> partialApply: [A, B, C](a: A, f: (A, B) => C)B => C
我们知道partialApply的结果是一个入参B返回C的函数。所以想办法从匹配类型款式上着手。可以直接用一个函数文本表达这个结果:给我一个B=b,我返回给你一个C=f(a,b);一个典型的lambda表达式。用一个实际的例子来示范:
1 def addTwoParams(a: Int, b: Int) = a + b //> addTwoParams: (a: Int, b: Int)Int 2 addTwoParams(2,5) //> res59: Int = 7 3 val applyOnce = partialApply(2,addTwoParams) //> applyOnce : Int => Int = <function1> 4 applyOnce(5) //> res60: Int = 7
addTwoParams是一个两个入参的函数,applyOnce是向addTwoParams作用了一个参数2后产生的函数,再用参数5再对applyOnce作用后结果等于7. = addTwoParams(2,5)。为什么费那么大的劲把函数变来变去呢?实际上这种函数变形在泛函编程中很普遍,是函数组合(Functional Composition)必须掌握的技巧。
函数变形在泛函编程中是常用的技巧。下面的Curry function就是把一个N个输入参数的函数变成一个参数的N次作用:
f(a,b,c,...n) = f(a)(b)(c)...(n) = a => b => c => ... => n
1 def curryTwo[A,B,C](f: (A,B) => C): A => (B => C)
函数curryTwo把一个两个参数的函数转变成一个参数返回另一个同样是一个参数的函数。用函数文本实现curryTwo后再使用一下来示范(注意返回的类型款式):
1 def curryTwo[A,B,C](f: (A,B) => C): A => (B => C) = (a: A) => ((b: B) => f(a,b)) 2 //> curryTwo: [A, B, C](f: (A, B) => C)A => (B => C) 3 val curriedFunction = curry(addTwoParams) //> curriedFunction : Int => (Int => Int) = <function1> 4 val curryOnce = curriedFunction(2) //> curryOnce : Int => Int = <function1> 5 curryOnce(5) //> res61: Int = 7
把addTwoParams转成curriedFunction Int=>(Int=>Int)。可以马上看到需要填写两次输入参数。我们遇到这种函数变形的问题时通常会用函数文本尝试匹配函数的结果类型款式(type signature)。
uncurry是curry的反向:把curry函数返还到多参数函数:a => b => c => ... => n = f(a,b,c,...n)
1 def uncurry[A,B,C](f: A => B => C): (A,B) => C
结合上面的例子示范uncurry函数实现和使用:
1 def uncurry[A,B,C](f: A => B => C): (A,B) => C = (a: A, b: B) => (f(a))(b) 2 //> uncurry: [A, B, C](f: A => (B => C))(A, B) => C 3 val uncurriedFunction = uncurry(curriedFunction)//> uncurriedFunction : (Int, Int) => Int = <function2> 4 uncurriedFunction(2,5) //> res62: Int = 7
uncurriedFunction又变回去了。
最后,示范一个函数组合的例子:
1 def compose[A,B,C](f: B => C, g: A => B): A => C
compose是将f和g两个函数组合成另一个函数。看看下面实现和使用示范:
1 def compose[A,B,C](f: B => C, g: A => B): A => C = (a: A) => f(g(a)) 2 //> compose: [A, B, C](f: B => C, g: A => B)A => C 3 val fadd = (x: Int) => x + 2 //> fadd : Int => Int = <function1> 4 val fmul = (y: Int) => y * 5 //> fmul : Int => Int = <function1> 5 val mulThenAdd = compose(fadd,fmul) //> mulThenAdd : Int => Int = <function1> 6 mulThenAdd(2) //> res63: Int = 12
把fadd,fmul组合起来形成了一个新的函数。mulThenAdd(2) = (2 * 5) + 2
如果再写的形象一点:
1 (fadd compose fmul)(2) //> res64: Int = 12 2 (fmul compose fadd)(2) //> res65: Int = 20
注意compose右边关联的(right hand associate):fadd compose fmul 中先运算fmul把结果输入fadd进行运算。设计另一个左边关联函数andThen:
1 def andThen[A,B,C](f: A => B, g: B => C): A => C = (a: A) => g(f(a)) 2 //> andThen: [A, B, C](f: A => B, g: B => C)A => C 3 (fadd andThen fmul)(2) //> res66: Int = 20
想想这里面的意义:fadd和fmul可能都是几千行代码的大函数,而我们能够很简洁地把它们连接起来,只需要把类型匹配起来就行了。
转载于:https://www.cnblogs.com/tiger-xc/p/4323430.html
泛函编程(4)-深入Scala函数类相关推荐
- Scala 函数篇笔记(二)
文章目录 基础篇 函数和方法的关系 声明方式 参数个数 噩梦篇 至简原则 地狱篇(重要) 函数可以作为对象赋值给变量 函数可以作为参数传递给其他函数 练习: 小问题 函数作为返回值使用 闭包 Q&am ...
- java 调用scala 类_如何使用java类加载器调用带参数的scala函数?
我正在寻找一些将scala jar加载到java类加载器的指导. 当我使用java jar文件时,下面的函数对我有效. 其中,arr是一个java.net.URL数组,用于我需要加载到类加载器中的所有 ...
- C++初步之核心编程篇五:多态与虚函数类
C++初步之核心编程篇五:多态与虚函数类 文章目录 C++初步之核心编程篇五:多态与虚函数类 1. 多态的概要 2. 多态案例一-计算器类 3. 纯虚函数和抽象类 4. 多态案例二-制作饮品 5. 虚 ...
- C++笔记7:C++提高编程1:模板—[函数模板和类模板]
0820 C++提高编程: 1.模板-[函数模板和类模板] 2.初识STL 3.STL-常用容器 4.STL-函数对象 5.STL-常用算法 C++提高编程引言: C++除了面向对象编程思想,还有泛型 ...
- 类和对象编程(一):类成员函数
C++ 类成员函数 类的成员函数是指那些把定义和原型写在类定义内部的函数,就像类定义中的其他变量一样.类成员函数是类的一个成员,它可以操作类的任意对象,可以访问对象中的所有成员. 让我们看看之前定义的 ...
- C++ 泛型编程/模板 泛函编程/Lambda/λ演算
1.泛型编程(C++模板) 其中,Ada, Delpha, Java, C#, Swift 称之为 泛型/generics; ML, Scala和 Haskell 称之为 参数多态/parametri ...
- Scala 函数声明及调用案例详解
Scala 函数 函数是一组一起执行一个任务的语句. 您可以把代码划分到不同的函数中.如何划分代码到不同的函数中是由您来决定的,但在逻辑上,划分通常是根据每个函数执行一个特定的任务来进行的. Scal ...
- Spark常用的算子以及Scala函数总结
上海站 | 高性能计算之GPU CUDA培训 4月13-15日 三天密集式学习 快速带你晋级 阅读全文 > 正文共11264个字,7张图,预计阅读时间28分钟. Spark与Scala 首先, ...
- C++知识点61——typename与class、模板编程与继承、模板类和友元、类模板与static成员
一.typename与class的异同 1.啥时候既可以使用typename,又可以使用class? 当表示模板参数的时候,二者没有区别 2.啥时候只能使用typename,不能使用class? 当模 ...
最新文章
- MySQL-基础操作之增删改查
- VS 调试断点命中了,程序无法再断点处中断
- python asyncio理解_我实在不懂Python的Asyncio
- HDU - 5187 zhx's contest(快速幂+快速加+组合数学)
- java 微信api框架_Java架构学习(五十二)使用框架开发微信微信框架介绍整合微信开发框架WxJava使用微信返回消息模板接口使用WxJava框架发送模板消息http协议参数转义知识...
- [Spark]Spark RDD 指南二 初始化
- printf格式控制符的完整格式(转载)
- 基于Ymodem协议的IAP上位机(C#)
- 基于米思齐的电磁炮基础代码
- edk2中的全局变量gST和gBS
- JavaWeb项目监听数据表变化并通知前台(数据来源于自身)
- 用友u8服务器无法自动启动,u8服务有的没有启动,启动服务,没有反应-用友U8...
- 高等数学:第八章 多元函数的微分法及其应用(3)全微分
- 中职学校计算机专业的论文,浅谈中职计算机专业教学改革思考论文
- Java实现手机验证码----阿里云
- 计算机丢失quartz.dll什么意思,全民K歌运行时提示quartz.dll文件丢失,如何修复
- python 自动化输入登录密码_selenium+python实现自动登录脚本
- Codeforces Raif Round 1 (Div. 1 + Div. 2) E. Carrots for Rabbits(优先队列+贪心)
- P1522 牛的旅行 Cow Tours(floyd)
- 在python中创建一个具有特定大小的空列表