OCaml: matching any negative

Is there a way to get the pattern matching according to my value with any negative number? It doesn't matter which negative number I just have to match any negative.

I did 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 exclude this if and just ask it to check it as another case in the match statement

+4
source share
3 answers

Yes, use security:

 match n with _ when n < 0 -> [] | _ -> [x] @ clone x (n - 1) 
+9
source

You can make your code a little cleaner like this:

 match n < 0 with | true -> [] | false -> [x] @ clone x (n - 1) 

Even better:

 if n < 0 then [] else [x] @ clone x (n - 1) 

Generally, if the statements are more understandable than the correspondences for simple logical tests.

While we are doing this, we can use :: instead of @ :

 if n < 0 then [] else x :: clone x (n - 1) 
+8
source

There is a when keyword. On the head (I can’t check right now)

let y = correspond to n with | when n <0 β†’ 0 | 0 β†’ [] | _ β†’ [x] @clone x (n - 1)

However, even your example should not work. As on one side you are returning int, and on the other - a list.

0
source

Source: https://habr.com/ru/post/1308407/


All Articles