美文网首页
偏函数中的模式匹配

偏函数中的模式匹配

作者: 抬头挺胸才算活着 | 来源:发表于2021-11-09 11:41 被阅读0次
    • 定义
      偏函数也是一种函数,只不过只有在输入参数更准确的时候才会执行

    • 例子
      second返回输入数组的第二个元素

    val second: PartialFunction[List[Int], Option[Int]] = {
    case x :: y :: _ => Some(y)
    }
    
    • 原理
      case 是用偏函数实现的,它们都是添加满足的时候才执行对应的代码
      跟普通的函数一样,只不过多了一个用于参数检查的函数isDefinedAt,返回类型为Boolean
    val second = new PartialFunction[List[Int], Option[Int]] {
      //检查输入参数是否合格
      override def isDefinedAt(list: List[Int]): Boolean = list match
      {
        case x :: y :: _ => true
        case _ => false
      }
      //执行函数逻辑
      override def apply(list: List[Int]): Option[Int] = list match
      {
        case x :: y :: _ => Some(y)
      }
    }
    
    • 使用
      偏函数不能直接用()调用,因为这会直接调用apply方法,而应该使用applyOrElse:
    second.applyOrElse(List(1,2,3), (_: List[Int]) => None)
    

    applyOrElse 方法的逻辑为 if (ifDefinedAt(list)) apply(list) else default

    相关文章

      网友评论

          本文标题:偏函数中的模式匹配

          本文链接:https://www.haomeiwen.com/subject/drumzltx.html