Is there a way to get pattern matching to match my value with any negative number? It does not matter what the negative number is I just need to match with any negative.
I have accomplished what I want with this simple code:
let y = if(n < 0) then 0 else n in
match y with
0 -> []
| _ -> [x] @ clone x (n - 1)
But I want to eliminate that if
statement and just get it to check it as another case in the match
statement
Yes, use a guard:
match n with
_ when n < 0 -> []
| _ -> [x] @ clone x (n - 1)
You can make your code a little cleaner like this:
match n < 0 with
| true -> []
| false -> [x] @ clone x (n - 1)
Even better would be:
if n < 0 then [] else [x] @ clone x (n - 1)
Generally, if statements are clearer than matches for simple logical tests.
While we're at it, we might as well use ::
in place of @
:
if n < 0 then [] else x :: clone x (n - 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With