Background

ReasonML - Exercism's Bob Exercise

December 29, 2018

ReasonML's syntax can appear very similar to that of Javascript, so this may be quite easy to understand even for those with no experience in ReasonML. This is only the third piece of code I've written with the language so I can't say it's particularly well written or complex code.

I include it here mostly for reference. It's interesting to see how switch statements and types work in ReasonML.

Some of the code seems instinctively bad to me; multiple is else branching logic is rarely the easiest to understand and can be difficult to maintain, for instance.

Reason is an interesting language to use so far, and I look forward to learning more about it and in particular how it can be used with React.

type speechType =
  | Question
  | Shouting
  | ShoutingQuestion
  | Nothing
  | Other;

let isShouting = (input: string): bool => Js.Re.test(input, [%re "/[A-Z]/"])
  && input == String.uppercase(input);

let isQuestion = (input: string): bool => {
  let re = [%re "/\?$/"];
  re |> Js.Re.test(input)
}

let getQuestionType = (input: string): speechType => {
  let trimmed = String.trim(input);

  if (String.length(trimmed) == 0) {
    Nothing;
  } else if (isQuestion(trimmed) && isShouting(trimmed)) {
    ShoutingQuestion;
  } else if (isShouting(trimmed)) {
    Shouting;
  } else if (isQuestion(trimmed)) {
    Question;
  } else {
    Other;
  }
};

let hey = input => {
  let inputType = getQuestionType(input);

  switch (inputType) {
  | ShoutingQuestion => "Calm down, I know what I'm doing!"
  | Question => "Sure."
  | Shouting => "Whoa, chill out!"
  | Nothing => "Fine. Be that way!"
  | Other => "Whatever."
  };
}