首页 > 其他 > 详细

scala 偏函数

时间:2018-09-04 00:01:32      阅读:198      评论:0      收藏:0      [点我收藏+]
package com.jason.qianfeng

object PartialFuncTest {
  def div: PartialFunction[Int, Int] = {
    case i if i != 0 => 100 / i
  }

  def r1: PartialFunction[Int, String] = {
    case 1 => "one"
    case 2 => "two"
    case _ => "other"
  }

  def r2: PartialFunction[Int, String] = {
    case 1 => "one"
  }

  def r3: PartialFunction[Int, String] = {
    case 2 => "two"
  }

  def r4: PartialFunction[Int, String] = {
    case _ => "other"
  }

  def r6: PartialFunction[String, String] = {
    case "one" => "haha one"
    case "two" => "wawo two"
  }

  def main(args: Array[String]): Unit = {
    val s = "=" * 10
    println(s"$s test function div $s")
    println(s"div.isDefinedAt(0):" + div.isDefinedAt(0))
    println(s"div.isDefinedAt(1):" + div.isDefinedAt(1))
    println(s"div(2) = " + div(2))

    println(s"$s test function r1 $s")
    println(s"r1(2) = " + r1(2))

    println(s"$s orElse $s")
    val r5 = r2 orElse r3 orElse r4
    println(s"r5(2) = " + r5(2))

    println(s"$s  andThen $s")
    val r7: PartialFunction[Int, String] = r1 andThen r6
    println(s"r7(1) = " + r7(1))
  }
}

执行结果

========== test function div ==========
div.isDefinedAt(0):false
div.isDefinedAt(1):true
div(2) = 50
========== test function r1 ==========
r1(2) = two
========== orElse ==========
r5(2) = two
==========  andThen ==========
r7(1) = haha one

总结

1.什么是偏函数:例如上述的函数div,传入的参数为 int,反汉之也是int,但是函数并不是对所有输入的int都进行处理,而是只处理不为0 的int

2.orElse 方法可以拼接多个偏函数,类似if...else

3.andThen 方法是把多个偏函数串联起来,第一个函数的结果作为参数传给第二个,以此类推

scala 偏函数

原文:https://www.cnblogs.com/jason-dong/p/9581699.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!