zoukankan      html  css  js  c++  java
  • Scala Partial Function从官方文档解析

    A partial function of type PartialFunction[A, B] is a unary function where the domain does not necessarily include all values of type A.

    一个PartialFunction[A, B]类型的偏函数是一个一元函数。它的输入值的范围并不包含所有A类型的值。

    The function isDefinedAtallows to test dynamically if a value is in the domain of the function.

    给定一个A类型的值,isDefinedAt函数可以用来动态地检测这个值是否属于此偏函数的输入范围。

    Even if isDefinedAt returns true for an a: A, calling apply(a) may still throw an exception, so the following code is legal:

    val f: PartialFunction[Int, Any] = { case _ => 1/0 }

    如果有一个a: A,虽然isDefinedAt返回true,但apply(A)可能会返回一个异常。

    It is the responsibility of the caller to call isDefinedAt before calling apply, because if isDefinedAt is false, it is not guaranteed apply will throw an exception to indicate an error condition. If an exception is not thrown, evaluation may result in an arbitrary value.

    调用者有责任在调用apply之前先调用isDefinedAt来做检查。因为如果isDefinedAt返回了false,apply方法并不能保证能做出抛异常的回应,有可能返回了意料之外的值。

    The main distinction between PartialFunction and scala.Function1 is that the user of a PartialFunction may choose to do something different with input that is declared to be outside its domain. For example:

    偏函数和Function1的区别是,偏函数的用户可以选择对输入域以外的输入值做一些特殊的处理。

    val sample = 1 to 10
    val isEven: PartialFunction[Int, String] = {
      case x if x % 2 == 0 => x+" is even"
    }
    
    // the method collect can use isDefinedAt to select which members to collect
    val evenNumbers = sample collect isEven
    
    val isOdd: PartialFunction[Int, String] = {
      case x if x % 2 == 1 => x+" is odd"
    }
    
    // the method orElse allows chaining another partial function to handle
    // input outside the declared domain
    val numbers = sample map (isEven orElse isOdd)
  • 相关阅读:
    [转]Java compiler level does not match解决方法
    Ubuntu使用MyEclipse闪退的解决办法
    支付宝AR红包引出Python中的PIL小试
    Neural Style学习3——操作
    Neural Style学习2——环境安装
    Neural Style学习1——简介
    mac下需要安装旧 Java SE 6 才能打开程序解决办法
    Linux system 函数的一些注意事项
    关于在android 4.2.2 上运行runlmbench
    linux kernel 字符设备详解
  • 原文地址:https://www.cnblogs.com/shuada/p/5039133.html
Copyright © 2011-2022 走看看