Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How OCaml match works?

(* Data type definitions *)
type t =
  | True
  | False
  | If of t * t * t
  | Zero
  | Succ of t
  | Pred of t
  | IsZero of t

let rec isNumber t =
  match t with 
    Zero -> true 
  | Succ t1 -> isNumber t1 
  | _ -> false

When we call isNumber give pattern (Succ (Succ (Succ (Succ Zero)))), how this works?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The t type is recursive. As you’ve seen, it can be constructed with Succ which takes another value of type t, which could itself be constructed with Succ, and so on.

The isNumber function is likewise recursive. If it finds the Succ t1 pattern, it calls isNumber on t1.

For your sample value of Succ (Succ (Succ (Succ Zero))) it looks like:

isNumber (Succ (Succ (Succ (Succ Zero))))
isNumber (Succ (Succ (Succ Zero)))
isNumber (Succ (Succ Zero))
isNumber (Succ Zero)
isNumber Zero
true
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading