簡體   English   中英

Scala關於F#中“部分函數”和“.orElse”方法的概念

[英]Scala's notion of “partial functions”' & the “.orElse” method in F#

在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"

我需要知道是否有辦法在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"

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

值得注意的是,在你提供的這種人為的情況下,你可以使用一個匹配語句。 我假設你的目標是將你的比賽條件分開。

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

在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"

這里, Choice1Of2意味着我們還沒有找到匹配並包含無與倫比的輸入。 Choice2of2意味着我們找到了匹配並包含輸出值。

我提出了兩個解決方案來實現我的目標。 一種是通過使用活動模式:

let orElse(fallback: 'a -> (unit -> 'b) option) (matcher: 'a -> (unit -> 'b) option) (arg:  'a) :  (unit -> 'b) option = 
    let first = matcher(arg)
    match first with
    | Some(_) -> first
    | None -> fallback(arg)

let (|StringCaseHandler|_|)(arg: obj) = 
    match arg with
    | :? string -> Some(fun () ->  "string")
    | _ -> None

let (|IntCaseHandler|_|)(arg: obj) = 
    match arg with
    | :? int -> Some(fun () ->  "integer")
    | _ -> None

let (|DefaultCaseHandler|_|)(arg: 'a) = 
    Some(fun () -> "other")

let msgHandler = 
    ``|StringCaseHandler|_|`` |> 
        orElse ``|IntCaseHandler|_|`` |> 
        orElse ``|DefaultCaseHandler|_|``

具有活動模式的解決方案是安全的,因為它沒有在沒有正確匹配的情況下拋出MatchFailureException ; 返回一個None

第二個涉及為'a -> 'b類型'a -> 'b函數定義一個擴展方法,並且我也可以接近Scala的“部分函數” orElse行為,如果生成的函數沒有產生正確的匹配,則拋出異常:

[<Extension>]
type FunctionExtension() =
    [<Extension>]
    static member inline OrElse(self:'a -> 'b,fallback: 'a -> 'b) : 'a -> 'b = 
            fun arg -> 
                try 
                    self(arg) 
                with
                | :? MatchFailureException -> fallback(arg)
let intMatcher : obj -> string = function 
                                 | :? int -> "integer"
let stringMatcher : obj -> string = function 
                                    | :? string -> "string"
let defaultMatcher : obj -> string = function 
                                     | _ -> "other"

let msgHandler: obj -> string = intMatcher
                                    .OrElse(stringMatcher)
                                    .OrElse(defaultMatcher)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM