sha*_*yan 3 f# scala partialfunction
在Scala中,"部分功能"的概念与F#的function关键字允许我实现的功能非常相似.然而,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"
Run Code Online (Sandbox Code Playgroud)
我需要知道是否有办法在F#中实现相同的组合功能.
我可能会在这里使用部分活动模式,这样你就可以使用模式匹配.一些(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"
Run Code Online (Sandbox Code Playgroud)
https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/active-patterns
值得注意的是,在你提供的这种人为的情况下,你可以使用一个匹配语句.我假设你的目标是将你的比赛条件分开.
let msgHandler (x: obj) =
match x with
| :? int -> "integer"
| :? float -> "float"
| _ -> "other"
Run Code Online (Sandbox Code Playgroud)
在Scala中编写它的方法相当于在C#中使用扩展方法.它不是特别惯用于函数式编程.要在F#中严格使用可组合函数,您可能会执行类似这样的操作.
// reusable functions
let unmatched input = Choice1Of2 input
let orElse f =
function
| Choice1Of2 input -> f input
| Choice2Of2 output -> Choice2Of2 output
let withDefault value =
function
| Choice1Of2 _ -> value
| Choice2Of2 output -> output
// problem-specific functions
let matcher isMatch value x =
if isMatch x then Choice2Of2 value
else Choice1Of2 x
let isInt (o : obj) = o :? int
let isString (o : obj) = o :? string
let intMatcher o = matcher isInt "Int" o
let stringMatcher o = matcher isString "String" o
// composed function
let msgHandler o =
unmatched o
|> orElse intMatcher
|> orElse stringMatcher
|> withDefault "other"
Run Code Online (Sandbox Code Playgroud)
在这里,Choice1Of2意味着我们还没有找到匹配并包含无与伦比的输入.并且Choice2of2意味着我们找到了匹配并包含输出值.