Question

My question is simple: how do I translate this C code :

if (x == y + 1)
  // some code
else if (x == y - 1)
  // some code
else if (x == y + 2)
   ....

Basically I was thinking of using pattern matching which seemed to be appropriate. Unfortunatly a pattern like this doesn't work:

match x with
| y + 1 -> some code
| y - 1 -> some code
| y + 2 -> some code
| _ -> some code

The compiler doesn't seem to be happy and from what I have found out, expressions on pattenr matching like I did are not tolerated. Therefore I tried putting them in values thusly:

let v1 = y + 1 in
let v2 = y - 1 in
let v3 = y + 2 in
match x with
| v1 -> some code
| v2 -> some code
| v3 -> some code
| _ -> some code

Unfortunatly I get warnings saying that my values v1 v2 and v3 are unused and that the the match cases that use them are unused too.

How can I properly match a expression with other expressions?

Thanks

Was it helpful?

Solution

Actually, your C code is almost valid OCaml code.

if x = y + 1 then
  (* some code *)
else if x = y - 1 then
  (* some code *)
else if x = y + 2 then
   ....

Pattern matching is not a replacement for if then, it has a completly different purpose. OCaml allows you to construct types such as type 'a option = None | Some of 'a and pattern matching should be used to deconstruct those types. It sould not be used for other purposes.

OTHER TIPS

If you insist on using a match you can use

match x with
| z when z=y+1 -> ...
| z when z=y-1 -> ...

Thomash is right, this code is naturally expressed by if expressions in OCaml, not by patterns. The reason your examples don't work is that patterns consist of constants and newly-defined variables. If a variable (a name) appears in a pattern, it becomes a newly defined name whose value is the corresponding part of the match expression. Any previous definition of the name is not relevant inside the match.

If you absolutely had to use a match, you could write as follows:

match y - x with
| -1 -> (* some code *)
| 0 -> (* some code *)
| 1 -> (* some code *)
| 2 -> (* some code *)
| _ -> (* some code *)

But I'm with Thomash, I think if expressions would be better here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top