I have been doing some exercises from the O’reilly book, which by the way is very good, and I always end up failing or missing the point of the exercises.
I discovered that the solutions are available in the online version of the text-book ( who would have guessed?), and since then have been confirming my solutions.
This post is about the Lexical Tree exercise.
My struggle has been to understand reset my mind to think recursively and not imperatively. Its hard. I have been a C, C# and Java programmer as long as I remember. I like recursive functions, but its hard for me to think of them as a first approach.
Anyway, after slowing down and think about all the possible cases and criteria’s I was able to find a suitable solution, however, not as good as the one provided by the authors.
The elegance in Ocaml keep amazing me, its so simple.
The functions are all the same after you know how to go though the tree. That’s the elegance.
I will redo the assignment and post here a good solutions and scheme.
For now I just want to record these thoughts and discoveries:
– Recursive always!
– Use pattern matching when possible, to attend the several constraints and cases
– Use the libraries, String in this specific case
– Practice in paper first!
I still can’t think of a good way of redefining values. The functions return a new data structure, a modified data structure but if I don’t use it again, or recursively I loose the information.
Right now, I am using let for re-assigining the values. for ex:
– let d = insert w d;;
– let d = insert w2 d;;
And so on.
After sleeping on this, I realized how stupid I was being by trying to force imperative thinking on this language again.
There is no need for mutable variables, here I have to start thinking about returning a new instance.
Its really hard to think like this, I have been completely formatted for imperative programming.
I just got a small new book to take a look, its called “Thinking Ocaml”. I post later a follow-up on this.