Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# version of haskell pattern match

How do I do this haskell in F# cleanly?

add 1 2 x = 3 + x
add 1 x y = 1 + x + y
add z x y = z + x + y
like image 356
Jimmy Hoffa Avatar asked Jun 13 '12 13:06

Jimmy Hoffa


1 Answers

You can't overload the function itself, but you can use pattern matching directly:

let add z x y =               // curried multiple parameters
    match z, x, y with        // convert to three-tuple to match on
    | 1, 2, x -> 3 + x
    | 1, x, y -> 1 + x + y
    | z, x, y -> z + x + y

Usage is as expected: add 1 2 3

If you're willing to use tuples as arguments (ie forgo currying and partial application), you can even write it more shorthand:

let add =                     // expect three-tuple as first (and only) parameter
    function                  // use that one value directly to match on
    | 1, 2, x -> 3 + x
    | 1, x, y -> 1 + x + y
    | z, x, y -> z + x + y

Usage now is: add (1, 2, 3)

like image 192
yamen Avatar answered Sep 20 '22 08:09

yamen