Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching a 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 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.

like image 358
Jackson Tale Avatar asked Jul 16 '13 10:07

Jackson Tale


People also ask

How does pattern matching work in OCaml?

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.

What is pattern matching syntax?

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.

Why ++ is not allowed in pattern matching?

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] .

What is matching string pattern?

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).


2 Answers

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.

like image 183
Tikhon Jelvis Avatar answered Nov 30 '22 16:11

Tikhon Jelvis


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.

like image 35
Ingo Avatar answered Nov 30 '22 15:11

Ingo