6

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

CharlesB
  • 86,532
  • 28
  • 194
  • 218
nicotine
  • 2,519
  • 3
  • 19
  • 15

3 Answers3

11

Yes, use a guard:

match n with
    _ when n < 0 -> []
  | _ -> [x] @ clone x (n - 1)
Chris Conway
  • 55,321
  • 43
  • 129
  • 155
Chuck
  • 234,037
  • 30
  • 302
  • 389
9

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)
zrr
  • 907
  • 4
  • 6
  • But while we're doing all this, we also introduce a bug where `n = 0` is mapped to `0 :: clone x (-1)` instead of `[]`. It's generally better to try to answer the question, as in Chuck's answer, both to avoid this and in case the real situation is more complicated. – Daniel H Jun 25 '13 at 13:42
0

There is the keyword when. By head (I can't test right now)

let y = match n with | when n < 0 -> 0 | 0 -> [] | _ -> [x] @ clone x (n - 1)

However, even your example shouldn't work. As on one side you return an int, and on the other a list.

Tristram Gräbener
  • 9,601
  • 3
  • 34
  • 50
  • No, both paths in the match are lists. The `@` operator has the type `'a list -> 'a list -> 'a list`. – Chuck Apr 29 '10 at 21:44
  • I think you are misunderstanding my code, the if statement is just an additional line of code to set the value for the match statement for when n is less than 0. It's just supposed to do the same thing as the 0 case and return an empty list. – nicotine Apr 29 '10 at 21:52
  • Oh indeed! It was way too late for me to answer on SO yesterday... My bad :/ – Tristram Gräbener Apr 30 '10 at 13:01