Addem
Addem

Reputation: 3919

OCaml pattern matching on integers

I have an assignment to fill in the following code stub:

let quad (x,y) = 
  match (x,y) with 
  | ... -> ...
  ...

where the quad function is supposed to take a tuple of ints as its argument, and return an algebraic data type representing the quadrant that the coordinates lie in. I know exactly how to do it using if-clauses, but how would one do this using matching? Is there a way to match integers with their sign? I know I could even do it by matching on the value of a sign function. I could write a function sign such that sign 10 = 1 and sign (-10) = -1 and so on, and then match on these values, but according to the code stub I shouldn't even do that. Any hint on how to accomplish this? Should I only do my matching on 0, and then if it's not 0 use if-clauses after the ->? Or is there some use of matching that can detect positive and negative integers?

Upvotes: 1

Views: 1052

Answers (1)

Konstantin Strukov
Konstantin Strukov

Reputation: 3019

Ugly solution but fits the code stub :)

let quad (x,y) = 
  match (x,y) with 
  | (0, 0) -> `Center
  | _ -> begin
    let sign = function
      | 0 -> 0
      | x -> if x < 0 then -1 else 1
    in
    match (sign x), (sign y) with
    | -1, -1 -> `LeftBottom
    | -1, 1 -> `LeftTop
    | 1, -1 -> `RightBottom
    | 1, 1 -> `RightTop
  end

(I would never solve the task this way in real life)

UPD. As @Virgile mentioned in comments, the code above is not complete. There is an edge case which is not processed properly: when the point belongs to x- or y-axis (e.g. only one of its coordinates is zero). These cases can be obviously matched either in the outer match

...
| (0, _) -> `YAxis
| (_, 0) -> `XAxis
...

or in the inner match with clauses like

| 0, -1 | 0, 1 -> `YAxis
...

(or even in a more detailed manner if necessary - with different variants for positive and negative semiaxis)

Upvotes: 1

Related Questions