Scala's notion of "partial functions"' & the ".orElse" method in F#

Viewed 301

In Scala there's the notion of a "partial function" that is fairly similar to what F#'s function keyword allows me to achieve. However Scala's partial functions also allow for composition via the orElse method as shown below:

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"

I need to know if there's a way to achieve the same composition functionality in F#.

3 Answers

I would probably use a partial active pattern here, that way you can use pattern matching. Some(T) matches, None does not match.

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

Its worth noting though, that in this contrived case you provided could just use a single match statement. I'm presuming that your goal is to split your match conditions up.

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

The way you wrote it in Scala is equivalent to using extension methods in C#. It is not particularly idiomatic to functional programming. To strictly use composable functions in F# you might do something like this.

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

Here, Choice1Of2 means that we haven't found a match yet and contains the unmatched input. And Choice2of2 means we found a match and contains the output value.

I came up with two solutions to achieve my exact goal. One is through the use of active patterns:

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|_|``

The solution with active pattern is safe as it doesn't throw a MatchFailureException in case of no proper match; returning a None instead.

The second involves defining an extension method for functions of type 'a -> 'b and is also as close as I could get to the Scala's "partial function" orElse behavior which throws an exception if the resulting function doesn't yield a proper match:

[<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)
Related