I been interested in functional programming for awhile, but the trouble with functional programming is often times the easy things are hard, and it can be hard to identify good projects to work on. However, their is one functional language that has caught my interest, and it is ReasonML.
In many imperative languages, one would do FizzBuzz like this:
While their is nothing wrong with using imperative style loops to solve questions like FizzBuzz. Sometimes, looping is not quite the tool need. ReasonML comes in with its functional background with a concept known as
pattern matching. Pattern matching is the act of looking at a sequence of tokens/variables and only applying a method if the token fits the case. This can be seen below with this idea being applied to FizzBuzz:
To explain this function, FizzBuzz is a function that takes in a integer labeled x, and outputs a string as its result. Then below their is a
switch statement, a way to signify that pattern matching is going on. After the statement, various cases are presented, so when x falls into a certain case, it then outputs the result it matches. However, we are getting ahead of ourselves. While this is a good example of the power of ReasonML, to get to this point, one needs to understand the basics of the language.
Like in most languages, the hello world statement is rather simple:
The virtue of ReasonML/OCaml, is that due to its strong type system, their are several different print statements, each devoted to a different type of variable, from integers to strings.
Variables, like in many functional languages, are immutable. Here is an example of a variable along with basic concatenation:
The strength of the OCaml type system allows one not to declare types, but declaring types in variables is simple and can prove to be helpful, especially with functions.
To look at an example of declaring types, lets using the very common square function example:
If one decided to declare a as a string, the compiler would not let you do that. That proves to be a useful guiding hand when working with functions in ReasonML.
As seen, functions are declared also with a
let statement, but conveniently, befitting a functional programming language, recursion gets treated uniquely when declaring functions. While not needed, a
rec when declaring a ReasonML function shows to you and the compiler that you are declaring a recursive function. To give a simple example of a recursive function, here is fibonacci done in Reason: