Home » Javascript » Functional programming style pattern matching in JavaScript

Functional programming style pattern matching in JavaScript

Posted by: admin August 19, 2018 Leave a comment

Questions:

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?

Answers: