zoukankan      html  css  js  c++  java
  • learning scala PartialFunction

    Partial函数的定义

    scala> val isVeryTasty: PartialFunction[String, String] = { case "Glazed Donut" | "Strawberry Donut" => "Very Tasty"}
    isVeryTasty: PartialFunction[String,String] = <function1>

    scala> isVeryTasty("Glazed Donut")
    res3: String = Very Tasty

    Partianl函数的组合使用:

    code :

      println("
    Step 1: How to define a Partial Function named isVeryTasty")
      val isVeryTasty: PartialFunction[String, String] = { case "Glazed Donut" | "Strawberry Donut" => "Very Tasty"}
    
    
    
      println("
    Step 2: How to call the Partial Function named isVeryTasty")
      println(s"Calling partial function isVeryTasty = ${isVeryTasty("Glazed Donut")}")
      // NOTE: you will get scala.MatchError
    
    
    
      println("
    Step 3: How to define PartialFunction named isTasty and unknownTaste")
      val isTasty: PartialFunction[String, String] = {
        case "Plain Donut" => "Tasty"
      }
    
      val unknownTaste: PartialFunction[String, String] = {
        case donut @ _ => s"Unknown taste for donut = $donut"
      }
    
    
    
      println("
    Step 4: How to compose PartialFunction using orElse")
      val donutTaste = isVeryTasty orElse isTasty orElse unknownTaste
      println(donutTaste("Glazed Donut"))
      println(donutTaste("Plain Donut"))
      println(donutTaste("Chocolate Donut"))

    result:

    Step 1: How to define a Partial Function named isVeryTasty
    
    Step 2: How to call the Partial Function named isVeryTasty
    Calling partial function isVeryTasty = Very Tasty
    
    Step 3: How to define PartialFunction named isTasty and unknownTaste
    
    Step 4: How to compose PartialFunction using orElse
    Very Tasty
    Tasty
    Unknown taste for donut = Chocolate Donut
  • 相关阅读:
    Objective-C中的Block回调模式
    [LINUX-02]linux内存管理
    Linux设备模型(8)_platform设备
    Face Alignment
    dlib 人脸识别论文 One Millisecond Face Alignment with an Ensemble of Regression Trees
    linux内核函数kmap_atomic用法
    [LINUX-01]对比LINUX和CORTEX-M启动流程
    -02-建立PetaLinux工程
    linux内核启动流程(文章最后流程图)
    uboot笔记:uboot命令分析+实现
  • 原文地址:https://www.cnblogs.com/lianghong881018/p/11174823.html
Copyright © 2011-2022 走看看