Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Conditional (computer programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Pattern matching == {{Main|Pattern matching}} [[Pattern matching]] may be seen as an alternative to both ''if–then–else'', and ''case'' statements. It is available in many programming languages with functional programming features, such as [[Wolfram Language]], [[ML (programming language)|ML]] and many others. Here is a simple example written in the [[OCaml]] language: <syntaxhighlight lang="ocaml"> match fruit with | "apple" -> cook pie | "coconut" -> cook dango_mochi | "banana" -> mix;; </syntaxhighlight> The power of pattern matching is the ability to ''concisely'' match not only actions but also ''values'' to patterns of data. Here is an example written in [[Haskell (programming language)|Haskell]] which illustrates both of these features: <syntaxhighlight lang="haskell"> map _ [] = [] map f (h : t) = f h : map f t </syntaxhighlight> This code defines a function ''map'', which applies the first argument (a function) to each of the elements of the second argument (a list), and returns the resulting list. The two lines are the two definitions of the function for the two kinds of arguments possible in this case – one where the list is empty (just return an empty list) and the other case where the list is not empty. Pattern matching is not strictly speaking ''always'' a choice construct, because it is possible in Haskell to write only one alternative, which is guaranteed to always be matched – in this situation, it is not being used as a choice construct, but simply as a way to bind names to values. However, it is frequently used as a choice construct in the languages in which it is available.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)