Skip to content

Instantly share code, notes, and snippets.

@EduardoRFS
Last active December 25, 2019 17:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EduardoRFS/e765b203435bc092ebb8a7d655621f96 to your computer and use it in GitHub Desktop.
Save EduardoRFS/e765b203435bc092ebb8a7d655621f96 to your computer and use it in GitHub Desktop.

Idea

Reason is faster than JavaScript when using BuckleScript.

Why?

The way that you design APIs are different, JavaScript code and the lack of a type system leads to APIs being designed strictly for humans.

String as type identifier

In JavaScript is quite common to use strings to identify types and branch based on it, but comparing strings is quite slow in fact it is O(n) in case where both strings have the same length, like tomato and orange.

type Fruit = { type: 'tomato' } | { type: 'orange' } | { type: 'grape' }
const fruitColor = (fruit: Fruit) => {
  switch (fruit.type) {
    case 'tomato': return 'red'
    case 'orange': return 'orange'
    case 'grape': return 'purple'
  }
}

On reason we use variants to solve that problem, but the trick is how variants are encoded in the bucklescript, as you can see below, it uses simple integers that already makes it a lot simpler to compare and validate, without loosing any readability.

// Input
type fruits = | Tomato | Orange | Grape
let fruit_color = fun
  | Tomato => "red"
  | Orange => "orange"
  | Grape => "purple"
// Output
function fruit_color(param) {
  switch (param) {
    case /* Tomato */0 : return "red";
    case /* Orange */1 : return "orange";
    case /* Grape */2 : return "purple";
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment