Consider the factorial function from the last post:
/* loading */
While an if/else or ternary expression works just fine for two branches, there is another way to express this
in Reason using a switch statement
:
/* loading */
As you can see, the final case of the switch
can be _
, which is Reason OCaml's
syntax for a throwaway variable.
Continuing also from the last post, consider the function we wrote to determine if a character is a vowel:
/* loading */
Let's convert this to using the switch statement:
/* loading */
Here I've also used the String.make
function, which can
make a string from a char.
Consider the Fibonacci series,
1, 1, 2, 3, 5, 8, 13...
, where each number is the sum of the prior two numbers.
To write a function that gives the _n_th Fibonacci number, one can use of pattern matching.
This shows that one doesn't need to discard the default case and can reuse it as a variable
in a subsequent function call:
/* loading */
The complement of pattern matching is variants.
Variants are synonyms or equivalence classes that are constructed with the single bar character: (|
)
/* loading */
Both pattern matching and variants are much more important to Reason than we've let on here.
Before we touch on that we need to introduce more data structures. Hopefully this post gives
a taste of what it's like to use switch
to do make clear code paths.
/* loading */
This example is powered by a Single Argument Match Function.
Use pattern matching to write a function that ...
Image Credit: Wall by Nigel Appleton on Flickr