文章目录
函数组合
让我们来创建两个函数
scala> def f(s: String) = "f(" + s + ")"
f: (String)java.lang.String
scala> def g(s: String) = "g(" + s + ")"
g: (String)java.lang.String
compose方法
compose组合其他函数形成一个新的函数f(g(x))
scala> val fComposeG = f _ compose g _
fComposeG: (String) => java.lang.String = <function>
scala> fComposeG("yay")
res0: java.lang.String = f(g(yay))
andThen
andThen和compose很像,只不过调用顺序是先调用第一个函数,然后调用第二个,最后得到的结果是g(f(x))
scala> val fAndThenG = f _ andThen g _
fAndThenG: (String) => java.lang.String = <function>
scala> fAndThenG("yay")
res1: java.lang.String = g(f(yay))
柯里化(Currying )和偏应用(Partial Application)
case 语句
那么究竟什么是case语句?
这是一个名为PartialFunction的函数的子类。
多个case语句的集合是什么?
它们组合在一起形成了多个PartialFunctions
理解PartialFunction
对给定的输入参数类型,函数可接受该类型的任何值。换句话说,一个(Int) => String 的函数可以接收任意Int值,并返回一个字符串。
对给定的输入参数类型,偏函数只能接受该类型的某些特定的值。一个定义为(Int) => String的偏函数可能不能接受所有Int值为输入。
isDefinedAt 是PartialFunction的一个方法,用来确定PartialFunction是否能接受一个给定的参数。来看下下面的例子:
scala> val one: PartialFunction[Int, String] = { case 1 => "one" }
one: PartialFunction[Int,String] = <function1>
scala> one.isDefinedAt(1)
res0: Boolean = true
scala> one.isDefinedAt(2)
res1: Boolean = false
然后我们可以如下调用这个偏函数:
scala> one(1) res2: String = one
PartialFunctions可以使用orElse组成新的函数,得到的PartialFunction反映了是否对给定参数进行了定义。
scala> val two: PartialFunction[Int, String] = { case 2 => "two" }
two: PartialFunction[Int,String] = <function1>
scala> val three: PartialFunction[Int, String] = { case 3 => "three" }
three: PartialFunction[Int,String] = <function1>
scala> val wildcard: PartialFunction[Int, String] = { case _ => "something else" }
wildcard: PartialFunction[Int,String] = <function1>
scala> val partial = one orElse two orElse three orElse wildcard
partial: PartialFunction[Int,String] = <function1>
scala> partial(5)
res24: String = something else
scala> partial(3)
res25: String = three
scala> partial(2)
res26: String = two
scala> partial(1)
res27: String = one
scala> partial(0)
res28: String = something else
case 之谜
我们在通常应该使用函数的地方看到了一个case语句,具体如下:
scala> case class PhoneExt(name: String, ext: Int)
defined class PhoneExt
scala> val extensions = List(PhoneExt("steve", 100), PhoneExt("robey", 200))
extensions: List[PhoneExt] = List(PhoneExt(steve,100), PhoneExt(robey,200))
scala> extensions.filter { case PhoneExt(name, extension) => extension < 200 }
res0: List[PhoneExt] = List(PhoneExt(steve,100))
这段代码为什么可以工作?
filter可以接收一个函数,在这个例子中是一个谓词函数:(PhoneExt) => Boolean。
PartialFunction是Function的子类型,所以filter也可以使用PartialFunction!
本文翻译自:https://twitter.github.io/scala_school/pattern-matching-and-functional-composition.html
本博客文章除特别声明,全部都是原创!原创文章版权归过往记忆大数据(过往记忆)所有,未经许可不得转载。
本文链接: 【Scala模式匹配和函数组合】(https://www.iteblog.com/archives/1660.html)

