zoukankan      html  css  js  c++  java
  • Scala快速入门-函数组合

    compose&andThen

    两个函数组装为一个函数,compose和andThen相反

        def f(test: String):String = {
          "f(" + test + ")"
        }
        def g(test: String):String = {
          "g(" + test + ")"
        }
        val composeFunction = f _ compose g _
        println("compose result:%s".format(composeFunction("compose")))
        val andThenResult= f _ andThen g _
        println("andThen result:%s".format(andThenResult("compose")))
    

    执行结果

    compose result:f(g(compose))
    andThen result:g(f(compose))
    

    PartialFunction

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

        val one: PartialFunction[Int, String] = { case 1 => "one" }
        println(one.isDefinedAt(1))
        println(one.isDefinedAt(2))
        val two: PartialFunction[Int, String] = { case 2 => "two" }
        val three: PartialFunction[Int, String] = { case 3 => "three" }
        val wildcard: PartialFunction[Int, String] = { case _ => "something else" }
        //PartialFunctions可以使用orElse组成新的函数,
        //得到的PartialFunction反映了是否对给定参数进行了定义。
        val partial = one orElse two orElse three orElse wildcard
        println(partial(1))
        println(partial(4))
    

    执行结果:

    true
    false
    one
    something else
    

    广告

    点击Spark加入群Spark,分享更多Spark相关信息

  • 相关阅读:
    CentOS7 PXE安装批量安装操作系统
    004_MySQL 主从配置
    CentOS 桥接网卡配置
    玩转 Jupyter Notebook (CentOS)
    搭建专属于自己的Leanote云笔记本
    wetty 安装(web+tty)
    wget命令详解
    linux 下find---xargs以及find--- -exec结合使用
    Linux 交换分区swap
    Linux 时区的修改
  • 原文地址:https://www.cnblogs.com/jacksu-tencent/p/4216389.html
Copyright © 2011-2022 走看看