Search code examples
pattern-matchingexpressionocamlunused-variables

Expression matching Ocaml


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


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.