首页 > 解决方案 > Scala 的“部分函数”概念和 F# 中的“.orElse”方法

问题描述

function在 Scala 中有一个“部分函数”的概念,它与 F# 的关键字允许我实现的非常相似。然而,Scala 的部分函数也允许通过orElse如下所示的方法进行组合:

def intMatcher: PartialFunction[Any,String] = {
  case _ : Int => "Int"
}

def stringMatcher: PartialFunction[Any,String] = {
  case _: String => "String"
}

def defaultMatcher: PartialFunction[Any,String] = {
  case _ => "other"
}

val msgHandler =
  intMatcher
  .orElse(stringMatcher)
  .orElse(defaultMatcher)

msgHandler(5) // yields res0: String = "Int"

我需要知道是否有办法在 F# 中实现相同的合成功能。

标签: scalaf#partialfunction

解决方案


我可能会在这里使用部分活动模式,这样你就可以使用模式匹配。Some(T) 匹配,None 不匹配。

let (|Integer|_|) (str: string) =
   let mutable intvalue = 0
   if System.Int32.TryParse(str, &intvalue) then Some(intvalue)
   else None

let (|Float|_|) (str: string) =
   let mutable floatvalue = 0.0
   if System.Double.TryParse(str, &floatvalue) then Some(floatvalue)
   else None

let parseNumeric str =
   match str with
     | Integer i -> "integer"
     | Float f -> "float"
     | _ -> "other"

https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/active-patterns

值得注意的是,在您提供的这种人为的情况下,您可以只使用一个 match 语句。我假设您的目标是拆分匹配条件。

let msgHandler (x: obj) = 
    match x with
    | :? int -> "integer"
    | :? float -> "float"
    | _ -> "other"

推荐阅读