Search code examples
javascriptalgorithmfunctional-programmingcompiler-constructionpattern-matching

Functional programming style pattern matching in JavaScript


I'm writing compiler from kind of functional language to JS. Compiler would run in browser. I need to implement pattern matching mechanics in JS, because original language have one. I've found Sparkler and Z. Sparkler can't be executed in browser as far as I know and Z doesn't have all possibilities I need.

So my language have semantics like this:

count x []         <- 0
count x [ x : xs ] <- 1 + count x xs
count x [ y : xs ] <- count x xs

This is what happens in this snippet:

First line is definition of a function, which takes two parameters: some variable x and empty list, and returns zero.

Second line is definition of a function, which also takes two parameters: some variable x and list, which starts with x, and returns 1 + count(x, xs)

Fot this example I want to generate code like this:

const count = (x, list) => {
    match(x, list) => (
        (x, []) => {...}
        (x, [ x : xs ]) => {...}
        (x, [ y : xs ]) => {...}
    )
} 

How properly unfold this kind of pattern matching into ifs and ors?


Solution

  • General case

    There is a proposal for Pattern Matching in ECMAScript, but as of 2018 it's in a very early stage.

    Currently, the Implementations section only lists:

    List case

    Use destructuring assignment, like:

    const count = list => {
      const [x, ...xs] = list;
      if (x === undefined) {
        return 0;
      } else if (xs === undefined) {
        return 1;
      } else {
        return 1 + count(xs);
      }
    }