Pattern matching variable in OCaml?

If i do

let check n = function | n -> true | _ -> false 

then I get Warning 11: this match case is unused.

I understand why , since n in | n β†’ true is not really a check argument. This is basically a variable created by pattern matching.

My question is , in this case, do we have any way to still use pattern matching (instead of else) to force this check?

Ie, I want to match the image with argument n .

+4
source share
2 answers

You can use when to create patterns along with boolean conditions:

 let check n = function | x when x = n -> true | _ -> false 

However, this is not very important: this is just great syntax for using if .

OCaml does not support any β€œdynamic” template, which allows you to map the value of a variable - templates, all static. There is a bondi research language that supports dynamic patterns like this. This is very similar to OCaml, so if you are interested in such a feature, you should play with it.

+7
source

You get this warning because n matches the same (any value) as _ , so you can never reach the second match case. Which holds back possible problems in your program.

+2
source

Source: https://habr.com/ru/post/1491630/


All Articles