dimitris papadimitriou
dimitris papadimitriou More than 12 years’ experience as full stack developer and Software Architect . Functional javascript with categories.

# Pattern matching

# Pattern matching

Pattern matching

Pattern matching

Pattern matching is the functional way to extract values out of Functors.

Pattern matching is a computer science concept, that means different things in different contexts. So, we are not going to give a definition, but we are going to build an intuitive understanding by looking some examples.

After we wrap a value in a functor and manipulate it with the map, eventually, we want to get the value out of the functor elegantly and consistently. Until now, we could directly access the value directly using the .getValue() function:

1
2
3
4
5
6
7
8
9
10
import { Id } from "./Id.js"
import { Client } from "./Client.js"

var upperCaseName = Id(new Client(1, "jake"))
    .map(client => client.name)
    .map(name => name.toUpperCase())
    .getValue();

console.log(upperCaseName);

Not very pretty. There are some more orthodox ways to extract a value from a Functor, and one of them is pattern matching.

Specifically for the Id Functor we can provide a method (match) that takes a callback:

1
2
3
4
 export const Id = (v) => ({
 ...
  match: callback => callback(v)
});

The Id can pass the value to the callback without violating encapsulation:

1
2
3
4
5
6
7
8
9
import { Id } from "./Id.js"
import { Client } from "./Client.js"

Id(new Client(1, "jake"))
    .map(client => client.name)
    .map(name => name.toUpperCase())
    .match(result => console.log(result));


Run this

That was a simple implementation of Pattern Matching for a simple structure like the Id. In the next section we are going to see how to implement Pattern Matching for the case of Inheritance hierarchies

comments powered by Disqus