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

matching multiple patterns at once in ocaml

Having a custom variant type as below:

type yolo = 
| A of string
| B of yolo
| C of yolo * yolo
| D of yolo * yolo

I also have a function that performs some operations on instances of yolo similar to this:

let rec swag y = 
  match y with
  | A _ -> 1
  | B _ -> 2
  | C (left,right) -> (swag left) + (swag right)
  | D (left,right) -> (swag left) + (swag right)

Since operations for cases C and D are exactly the same I would like to merge them, is it possible?

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

>Solution :

A pattern like pat1 | pat2 matches either of the two patterns:

let rec swag y = 
match y with
| A _ -> 1
| B _ -> 2
| C (left,right) | D (left,right) -> (swag left) + (swag right)

Naturally the two patterns must bind the same names (left and right in this case) with the same types.

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