In the second part I explain some more language features and code.
let keyword
We start with this keyword again as this tripped me up. Moreover one does not
proceed much further without understanding the semantics of this keyword.
choose_randomly_hashtbl returns randomly one of the values from the list corresponding to the key . And we see that n0, n1 and n2 are used after they are defined one by one. This should give a clearer idea about let’s semantics.
User-defined types
As the name implies a UDF is a custom type defined by the user.
Record types
A record type is a step further. It identifies each constituent part of the type by a name identifier like this.
Nested pattern matching Record types
I plan to write about pattern matching concepts in another installment of this series as that is deeper than what would fit in one paragraph.
The third line in the up function shown below matches the head(line) of the list and the tail(above) of the list.
It is nested because the pattern matches the constituent part identified by a name inside a record type. gamegrid is the name identifier of a grid defined by this code. It is a grid made of a list of lists of cell which is another record type.
Partial updates of Record types
In this function G, which is of type gridzipper is updated partially. above and below
are not updated. The keyword with enables us to do this.
Basic containers
As I understand it these are library extensions. We have to install those libraries we require. So, for example, CCList enables us to create a mxn list of lists easily.
This is how I used it.
This create a 2x2 grid which is a list of lists.`List seems to be the workhorse of functional programming languages.
More involved code
Let us use the record types and UDF’s to code a grid using the zipper pattern which is a functional way of coding a grid. The code should serve as a foundation for a game of life representation in the future.
It should be pointed out that none of these functions mutate any data structure. So there is no side-effect. As you see it takes some effort to shed our memory of imperative mutable code. It is hard at the beginning but seems quite natural now.
Some of the following functions are my OCaml port of existing Haskell code. Given that I am not an OCaml expert, this code is far more verbose than the equivalent Haskell code My Haskell chops were not enough and I turned to the IRC for much needed advice.
The code focuses on a cell like this picture shows. There are areas above,below, to the left and to the right. We move over this grid.
The focus is the green square.
Move the focus inside the grid
The left function moves the focus to the left. Similarly the other functions shift the focus
to other grids cells.
Function that tests if the focus stays within the grid. None signifies an exceptional movement outside.
Another Function that tests focuscell, a lower-order function.
References :
Huet, Gerard (September 1997). “Functional Pearl: The Zipper”