'How does one use pattern matching to check if something is even in OCAML?
I tried:
let rec f n =
match n with
| 0 -> case0
| k -> case1
| (2*k) -> case2;;
but didn’t work…
https://discuss.ocaml.org/t/how-does-one-us-pattern-matching-to-check-if-something-is-even/4366 https://www.quora.com/unanswered/How-does-one-use-pattern-matching-to-check-if-something-is-even
Solution 1:[1]
Pattern matching is structural in OCaml. So the following code will check if the structure of the value you match is the same as k
, which is always the case, and then the value is bound to k
. So anything not already matching 0
matches k
. Any variables in a match are always bound, never compared to an existing binding.
| k -> case1
Next you have the following but 2*k
is not any structure of a value. It's an expression or it would be a type if you ignore that 2
is an integer literal.
| (2*k) -> case2
If you want to match the value of something you have to use when
like
match n with
| x when x mod 2 = 0 -> even
| _ -> odd
A better match would be to simply match n % 2
against 0 and 1. Or, since this is a match with exactly 2 cases simply use
if n mod 2 = 0 then even
else odd
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chris |