DΦC__WTF
DΦC__WTF

Reputation: 105

Pattern matching with logic?

I wonder if there is a way to do something like this (x, y < 0, z) with y < 0

There are three cases in my example y = 0, y < 0 and else.

I know how to implement this function with different approaches, but I just like this way and want to know if this is possible in some way.

let rec f = function
    | (x, 0, y) -> x
    | (x, y < 0, z) -> f (x y z)
    | (x, y, z) -> f (z y x)

Just that you know, I removed the complexity of the tuple in the recursive call, so the function has no purpose right now.

Upvotes: 3

Views: 122

Answers (1)

sepp2k
sepp2k

Reputation: 370162

You can add a condition after a pattern using the when keyword. With that, you can do what you want like this:

let rec f = function
    | (x, 0, y) -> x
    | (x, y, z) when y < 0 -> f (x, y, z)
    | (x, y, z) -> f (z, y, x)

This will cause infinite recursion because f (x, y, z) doesn't change anything about the arguments, but I assume that problem does not exist in your real code.

Upvotes: 5

Related Questions