Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: Matching with any negative

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

like image 569
nicotine Avatar asked Apr 29 '10 21:04

nicotine


2 Answers

Yes, use a guard:

match n with
    _ when n < 0 -> []
  | _ -> [x] @ clone x (n - 1)
like image 183
Chuck Avatar answered Sep 25 '22 01:09

Chuck


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)
like image 39
zrr Avatar answered Sep 25 '22 01:09

zrr