zoukankan      html  css  js  c++  java
  • Scala学习(四)——模式匹配与函数组合

    函数组合

    让我们创建两个函数:

    def f(s: String) = "f(" + s + ")" 
    def g(s: String) = "g(" + s + ")" 

    compose

    compose 组合其他函数形成一个新的函数 f(g(x))

    val fComposeG = f _ compose g _ 
    fComposeG("yay") // f(g(yay)) 

    andThen

    andThen 和 compose很像,但是调用顺序是先调用第一个函数,然后调用第二个,即g(f(x))

    val fAndThenG = f _ andThen g _ 
    fAndThenG("yay") // g(f(yay)) 

    柯里化 vs 偏应用

    case 语句

    那么究竟什么是case语句?

    这是一个名为PartialFunction的函数的子类。

    多个case语句的集合是什么?

    他们是共同组合在一起的多个PartialFunction。

    理解PartialFunction(偏函数)

    对给定的输入参数类型,函数可接受该类型的任何值。换句话说,一个(Int) => String 的函数可以接收任意Int值,并返回一个字符串。

    对给定的输入参数类型,偏函数只能接受该类型的某些特定的值。一个定义为(Int) => String 的偏函数可能不能接受所有Int值为输入。

    isDefinedAt 是PartialFunction的一个方法,用来确定PartialFunction是否能接受一个给定的参数。

    注意 偏函数PartialFunction 和我们前面提到的部分应用函数是无关的。

    val one: PartialFunction[Int, String] = { case 1 => "one" } 
    one.isDefinedAt(1) // true  
    one.isDefinedAt(2) // false 

    您可以调用一个偏函数。

    one(1) // one 

    PartialFunctions可以使用orElse组成新的函数,得到的PartialFunction反映了是否对给定参数进行了定义。

    val two: PartialFunction[Int, String] = { case 2 => "two" } 
    val three: PartialFunction[Int, String] = { case 3 => "three" } 
    val wildcard: PartialFunction[Int, String] = { case _ => "something else" } 
    val partial = one orElse two orElse three orElse wildcard 
    partial(5) // something else  
    partial(3) // three  
    partial(2) // two  
    partial(1) // one  
    partial(0) // something else 

    case 之谜

    上周我们看到一些新奇的东西。我们在通常应该使用函数的地方看到了一个case语句。

    case class PhoneExt(name: String, ext: Int) defined class PhoneExt  
    val extensions = List(PhoneExt("steve", 100), PhoneExt("robey", 200)) 
    extensions.filter { case PhoneExt(name, extension) => extension < 200 } // List(PhoneExt(steve,100)) 

    为什么这段代码可以工作?

    filter使用一个函数。在这个例子中是一个谓词函数(PhoneExt) => Boolean。

    PartialFunction是Function的子类型,所以filter也可以使用PartialFunction!

  • 相关阅读:
    oracle 数据库服务名怎么查
    vmware vsphere 6.5
    vSphere虚拟化之ESXi的安装及部署
    ArcMap中无法添加ArcGIS Online底图的诊断方法
    ArcGIS中字段计算器(高级计算VBScript、Python)
    Bad habits : Putting NOLOCK everywhere
    Understanding the Impact of NOLOCK and WITH NOLOCK Table Hints in SQL Server
    with(nolock) or (nolock)
    What is “with (nolock)” in SQL Server?
    Changing SQL Server Collation After Installation
  • 原文地址:https://www.cnblogs.com/wmx24/p/9362733.html
Copyright © 2011-2022 走看看