Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Support for functional pattern matching in Elm

In Elm is there a way to pattern match the arguments of a function to multiple definitions like in Haskell?

Example from Haskell:

factorial :: Int ->
factorial 0 = 1
factorial n = n * factorial (n - 1)
like image 312
lookyhooky Avatar asked May 31 '16 21:05

lookyhooky


People also ask

What is pattern matching in functional programming?

Pattern matching allows you to match a value (or an object) against some patterns to select a branch of the code. From the C++ point of view, it may sound a bit similar to the switch statement. In functional languages, pattern matching can be used for matching on standard primitive values such as integers.

What is lot pattern matching?

Pattern matching is the act of checking one or more inputs against a pre-defined pattern and seeing if they match. In Elm, there's only a fixed set of patterns we can match against, so pattern matching has limited application.

What is pattern matching syntax?

Patterns are written in JME syntax, but there are extra operators available to specify what does or doesn't match. The pattern-matching algorithm uses a variety of techniques to match different kinds of expression.

What is pattern matching give an example?

Pattern matching is the process of specifying a pattern to be searched for within a data set. The data set can be a file, a document, or a database. For example, a pattern match can be used to search for all occurrences of a word, phrase, or number within a document.


1 Answers

There is no equivalent of that syntax in Elm.

The easiest way to achieve similar behavior would be using pattern matching with case statement.

Please consider the following example:

factorial : Int -> Int
factorial n =
  case n of
    0 ->
      1
    _ ->
      n * factorial (n - 1)

The _ from the example above serves as a wildcard to match any pattern, in this case, it's any integer different from 0

like image 78
halfzebra Avatar answered Oct 21 '22 14:10

halfzebra