A list in Reason OCaml is a linked list.
A List is divided into a single-element head
and the rest of the list,
called the tail
. Whenever you need random access to element of a collection, an
Array or a Record may be a better structure. A list is a great data container other times,
though, in line with the Rule of Least Power.
The Reason docs for lists are here, and the API docs for the List module are here.
The standard library has a List.length function, but if it didn't already, here is one possible implementation that illustrates pattern matching on Lists:
/* loading */
This shows how pattern matching can select empty lists []
as well as lists
in the [head, ...tail]
syntax. In Reason the ellipsis ...
is meant to remind JS programmers
of Rest parameters,
as in "get the rest of the list."
The head
and tail
variable names are not keywords here, they could be anything.
Try replacing the last case with [foo, ...bar] => addUpLength(bar, currentTotal + 1)
.
This also shows how you can declare a utility function inside a function.
Here we're passing the total along in the parameter to the addUpLength
function
to get Tail Call Optimization, which
is basically a fancy way of saying that it uses less memory since it accumulates
the result in the currentTotal
function parameter.
/* loading */
This example is powered by:
|>
from the Pervasives standard library
Direct from the docs: "Reverse-application operator: x |> f |> g
is exactly equivalent to g(f(x))
,"
or, said another way, the output of x is put into f, and the output of f is put into g.|>
, and the function to execute
on each element is Js.log
./* loading */
This example is powered by pattern matching and the ternery sugar. Many times in ReasonML, the "batteries" that are included is just the pattern matching.
Here are some examples of searching lists.
/* loading */
This example is powered by:
/* loading */
This example is powered by:
|>
as mentioned above/* loading */
In addition to |>
, filter
and iter
from above, this example is powered by:
str1InsideStr2(s1, s2)
twice, first with the parameter "San" to search for, and second as the callback
to filter. Write a function that, given a list,
Image Credit: List by Nik Stanbridge on Flickr
(Edit this post here!)