Перевод "Answers to FP Koans, in OCaml"

Doug Bagley, “Answers to FP Koans, in OCaml”, public translation into Russian from English More about this translation.

Translate into another language.

Participants

Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next next untranslated
1 2 3 4

Answers to FP Koans, in OCaml

Since you can find published answers to the classic koans of Zen Buddhism, I also present answers to these FP Koans. Of course, if you read the answers before you come to understand the koan on your own, then as in Buddhism, you will cheat yourself out of joy of the experience of enlightenment :) The same goes for learning anything, it is far more rewarding to do it on your own than to be told the answer. And that, of course, provides an excellent segue-way into the first koan ...

The Koan of Imperative/Declarative

This one is easy. OCaml is a declarative language, and shares the property of other declarative languages that instead of telling the language the exact steps to solve a problem, instead you give a declaration of the problem at a higher level, and the language makes some decisions on the implementation for you.

In this koan, the poor student was demanding to be told how to achieve knowledge of FP, but Xavier's response is intended to remind the student that not only will he achieve knowledge of FP by learning to program in a declarative manner, but also that when learning, a student benefits more from being guided as what to learn rather than just being given the answers. And on a third level, perhaps you noticed that the student's demand is an "imperative" sentence, while Xavier's response is a "declarative" sentence :)

Perhaps the canonical example for declarative style in FP languages is the quicksort function, and here it is for integers in 2 lines of OCaml:

let rec qsort = function

[] -> [] | h::t -> qsort(filter((>) h) t) @ [h] @ qsort(filter((<=) h) t);;

Of course, I was trying to be terse for the purpose of illustrating the expressive power, so here is the same function, written to be a little more readable:

let rec qsort = function

[] -> []

| head::tail ->

let lesser = qsort (filter ((>) head) tail)

and greater = qsort (filter ((<=) head) tail) in

lesser @ [h] @ greater;;

[Note this may not be the fastest way to write quicksort in OCaml, but the intent is to illustrate the power of being able to express solutions declaratively.]

Pages: ← previous Ctrl next next untranslated
1 2 3 4