views:

73

answers:

3

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

A: 

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
No, both paths in the match are lists. The `@` operator has the type `'a list -> 'a list -> 'a list`.
Chuck
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
Oh indeed! It was way too late for me to answer on SO yesterday...My bad :/
Tristram Gräbener
+6  A: 

Yes, use a guard:

match n with
    _ when n < 0 -> []
  | _ -> [x] @ clone x (n - 1)
Chuck
Oh I see, I will have to go do some research on guards. Thanks!
nicotine
+8  A: 

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