I may have an unusual question, but how can I combine a function in F # using pattern matching?
Imagine the following:
I have several function signatures that will be used several times, for example:
binary function: int -> int -> int unary function: int -> int boolean function: int -> int -> bool ...
Now imagine the evaluate function, which itself takes the function f . Signature f must be one of the above. How can I match such a case?
I have tried the following things:
Test No. 1: Using delegates and unions:
type UnaryFunction = delegate of int -> int type BinaryFunction = delegate of (int -> int) -> int type BooleanFunction = delegate of (int -> int) -> bool type Functions = | Unary of UnaryFunction | Binary of BinaryFunction | Boolean of BooleanFunction
Test No. 2: Using pattern matching and delegates:
type UnaryFunction = delegate of int -> int type BinaryFunction = delegate of (int -> int) -> int type BooleanFunction = delegate of (int -> int) -> bool let evaluate f = match f with | ?: UnaryFunction as u -> let test_result = u.Invoke 3 sprintf "the result of the unary function is %d" test_result | ?: BinaryFunction as b -> let test_result = b.Invoke 315 42 sprintf "the result of the binary function is %d" test_result | ?: BooleanFunction as o -> let test_result = o.Invoke 315 42 if test_result then "yeah" else "nope" | _ -> "invalid function type"
<h / "> The problem with these examples is that the delegates from ... will map instead of the actual functions. I would like to see something like this:
let evaluate f = match f with | ?: (int -> int) as u -> let test_result = u 3 sprintf "the result of the unary function is %d" test_result | ?: ((int -> int) -> int) as b -> let test_result = b 315 42 sprintf "the result of the binary function is %d" test_result | ?: ((int -> int) -> bool) as o -> let test_result = o 315 42 if test_result then "yeah" else "nope" | _ -> "invalid function type"
Does F # have special syntax for matching function templates?
And if not, then why? Am I missing something, or is it also not important to be able to map functions in the same way as everything else, since it is a functional language?
source share