开发者

OCaml: Matching with any negative

开发者 https://www.devze.com 2022-12-28 11:35 出处:网络
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开发者_StackOverflow just need to match 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开发者_StackOverflow 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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号