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

in OCaml how can I pattern match a function argument while keeping the variable name

I have some code:

let some_func some_arg = (* ... *)

where some_arg really needs to be [| arg1; arg2 |]. I want to pattern match that in the function argument position, like:

let some_func [| arg1; arg2 |] = (* ... *)

but I also want to keep the variable name some_arg in case I want to do something with it directly. How can I do that?

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 :

Function arguments are patterns, so you can use the as construct to name parts (or all) of the pattern:

let some_func ([| arg1; arg2 |] as some_arg) = (* . . . *)

However this pattern isn’t exhaustive as it only matches arrays of length 2. So it’s a brittle function definition, and you’ll get a warning from the compiler.

It might be better just to use a match so you can specify the desired behavior when the array is some length other than 2. Or you can use a type that always has exactly 2 components (such as a tuple).

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