OCaml Pattern Matching Evaluation of boolean expressions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

We define the type of boolean expressions whose atoms are identified by strings as

type expr =
| Atom of string
| Not of expr
| And of expr * expr
| Or of expr * expr

and can evaluate these expressions using an oracle : string -> bool giving the values of the atoms we find as follows:

let rec eval oracle = function
| Atom(name) -> oracle name
| Not(expr) -> not(eval oracle expr)
| And(expr1, expr2) -> (eval oracle expr1) && (eval oracle expr2)
| Or(expr1, expr2)  -> (eval oracle expr1) || (eval oracle expr2)

See how the function is clear and easy to read. Thanks to correct use of pattern matching, a programmer reading this function needs little time to ensure it is correctly implemented.



Got any OCaml Question?