If I do
let check n = function
| n -> true
| _ -> false
then I get Warning 11: this match case is unused.
I understand why, since the n
in | n -> true is actually not the argument of check
. It is basically a variable created by the pattern matching.
My question is, in this case, do we have any way to still using pattern matching (instead of if else) to force this check?
I.e., I want to pattern match with the argument n
.
Pattern matching comes up in several places in OCaml: as a powerful control structure combining a multi-armed conditional, unification, data destructuring and variable binding; as a shortcut way of defining functions by case analysis; and as a way of handling exceptions.
Pattern matching. This chapter will cover some of Haskell's cool syntactic constructs and we'll start with pattern matching. Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns.
You can only pattern-match on data constructors, and ++ is a function, not a data constructor. Data constructors are persistent; a value like 'c':[] cannot be simplified further, because it is a fundamental value of type [Char] .
A string enclosed within double quotes ('"') is used exclusively for pattern matching (patterns are a simplified form of regular expressions - used in most UNIX commands for string matching).
You can use when
to have patterns along with boolean conditions:
let check n = function
| x when x = n -> true
| _ -> false
However, this isn't very special: it's just different syntax for using an if
.
OCaml does not support any sort of "dynamic" pattern that lets you match against the value of a variable--patterns are all static. There is a research language called bondi which does support dynamic patterns like this. It's quite similar to OCaml, so if you're interested in this sort of feature you should play around with it.
You get that warning because n
matches the same (any value) as _
, hence you can never reach the second match case. Which hins to possible problems in your program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With