How does one use pattern matching to check if something is even?

I tried:

let rec f n =
match n with
| 0 -> case0
| k -> case1
| (2*k) -> case2;;

but didn’t work…

Im also curious to know in any scenario…

You cannot. OCaml does not bundle a computer algebra system :slight_smile:

To be a bit more serious, 2 * k is not a “pattern”, it is an expression. Patterns are things like literals (2), constructors (like lists, tuples, variants, and records), and variables. 2 * k is an expression that applies the function (*), so you can’t match on it.

match n mod 2 with 
| 0 -> even 
| 1 -> odd
| _ -> assert false

or just if n mod 2 = 0 then even else false

Technically, this is using pattern-matching to check if something is even:

let f = function
  | n when n mod 2 = 0 -> true
  | _ -> false

But the approach you tried won’t work. I’m not sure where you got the idea that it would, to be honest. Haskell used to have something slightly similar, called ‘n+k patterns’, but they were widely recognized as a bad idea and removed: https://prime.haskell.org/wiki/NoNPlusKPatterns

1 Like

I got confused with Coq I guess…

In Coq, the type

type nat = O | S of nat

doesn’t have a (purely) pattern-matching-based implementation of “even” either. It requires induction, which is both pattern-matching AND recursion. In order to implement “even” with only pattern-matching, you’d need a type like:

type nat = Mt | Cons of bit * nat
and bit = Zero | One

… in short, integers represented as lists of bits.

Or at least, it seems like.