与高阶函数返回值匹配的 Scala



您好,我试图使用高阶函数进行大小写匹配。 如果函数返回 true,则对 false 执行相同的操作。谢谢。

def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f match
  {
    case true => do something
    case false => do somethingelse
  }
}

看起来是将"andThen"应用于部分函数的好地方:

以下是您可能需要的:

def funk(ls: List[Int], f: Int => Boolean): List[Int] = {
  val z = f.andThen(r => r match {
    case true => List(1, 2) // ..something 
    case false => List(3, 4) // somethingElse
  })
   // function application
  z(5)
}

只需围绕PartialFunction进行一些挖掘:

http://www.scala-lang.org/api/current/scala/PartialFunction.html

您必须

执行函数并将返回值传递给match case

def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f(some integer value) match
  {
    case  true => return a list of integers
    case false => return a list of integers
  }
}

例如

def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f(ls(0)) match
  {
    case  true => List(1,2)
    case false => List(4,3)
  }
}

最新更新