Matching on variants (beginner question!)

Taking first steps in Ocaml (have some background in Python, Rust, Clojure, etc) but already stumbling on the first hurdle…

When playing around with variants and matching in utop and trying this code:

type rgb_color = Red | Blue | Green;;
type b_or_w = Black | White;;

type any_color =
  | RgbColor of rgb_color
  | BorW of b_or_w;;

let print_color c =
  match c with
    | RgbColor _ -> print_endline "A basic color!"
    | BorW     _ -> print_endline "Black or white!";;

let c = Red;;

print_color c;;

I get:

Error: The value c has type rgb_color but an expression was expected of type
         any_color

Thist is an absolute beginner question, but I can’t seem to get it to work, nor do I really understand why it doesn’t work. I’ve read most of the recommended documentation but I must be missing something really basic here…

Thanks in advance!

Thank you for your question, and welcome!

As the compiler is reporting: the error occurs because c has type rgb_color, but print_color expects a value of type any_color (the type is inferred by the compiler).

Red is a variant constructor of rgb_color variant type; it is not directly a constructor of any_color variant (sum type). To create an any_color value representing red, you need to wrap it with the RgbColor variant constructor (as it is how you defined the types):

let c = RgbColor Red;;

Now c has type any_color, so this works:

print_color c;;

Thanks a lot! Works like a charm!

Still learning…