Background

ReasonML - Exercism's Space Age Exercise

January 02, 2019

This challenge is quite simple; but it's really useful to help with understanding more about how things work in reason.

First of all we define a type for planets:

type planet =
  | Mercury
  | Venus
  | Earth
  | Mars
  | Jupiter
  | Saturn
  | Neptune
  | Uranus;

Next up we define how many seconds are in a year on earth.

let earthYearInSeconds: float = 31557600.0;

Different planets have different multipliers, and we can use a simple switch statement to get the multiplier we need:

let getMultiplier = (planet): float => switch (planet) {
   | Mercury => 0.2408467
   | Venus => 0.61519726
   | Mars => 1.8808158
   | Jupiter => 11.862615
   | Saturn => 29.447498
   | Uranus => 84.016846
   | Neptune => 164.79132
   | Earth => 1.0
}

Now we can consolidate this code to get only what we need, the length of a planet's year in seconds:

let getPlanetYearInSeconds = (planet): float => getMultiplier(planet) *. earthYearInSeconds;

Finding the value is then relatively simple:

let ageOn = (planetToCheck: planet, age: float) => age /. getPlanetYearInSeconds(planetToCheck);

One of the most interesting things about this exercise was the float arithmetic operators in Reason, I've not yet encountered a language which uses different operators per type so it's great to learn something new!