scala - 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# 中实现相同的合成功能。
解决方案
我可能会在这里使用部分活动模式,这样你就可以使用模式匹配。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"
推荐阅读
- r - 如何在 R 数据框中切换这些列和行?
- java - 如何防止 ObjectMapper 成功将纯字符串反序列化为 Object?
- python-3.x - 基于条件的数据框操作python
- r - 在 R4.0.3 上安装 cplexAPI 1.4.0
- sql - 如何在不包括最后一个值(sql)的情况下计算值的平均值?
- angular - 无法用hammerjs绑定数据
- azure - Azure DevOps Release Pipeline 设置静态文件的位置
- python - 注册 Django 应用程序时发生错误:save() 获得了意外的关键字参数“force_insert”
- clingo - cligo:用换行符分隔答案集谓词
- yaml - terraform formatlist 添加 SSH 私钥