List comprehensions: Difference between revisions
Remove outdated and no longer supported OCaml solutions
(Remove outdated and no longer supported OCaml solutions) |
|||
Line 1,651:
=={{header|OCaml}}==
As of OCaml 4.08 (2019), [https://v2.ocaml.org/manual/bindingops.html binding operators] were added to the language syntax. A general notion of "comprehension syntax" can be recovered using them.
[http://batteries.forge.ocamlcore.org/ OCaml Batteries Included] has uniform comprehension syntax for lists, arrays, enumerations (like streams), lazy lists (like lists but evaluated on-demand), sets, hashtables, etc.▼
<code>[
We can rewrite it using binding operators like so
if not condition then empty else
return expression
For instance, we can write the required Pythagorean triples comprehension:
- : int Enum.t = <abstr></syntaxhighlight>▼
<syntaxhighlight lang="ocaml"># [? List: 2 * x | x <- 0 -- 100 ; x * x > 3];;▼
- : int PSet.t = <abstr></syntaxhighlight>▼
<syntaxhighlight lang="ocaml">let pyth n =
let* x = 1 -- n in
let* y = x -- n in
let* z = y -- n in
if x * x + y * y <> z * z then [] else
[x, y, z]
where the <code>(let*)</code> and <code>(--)</code> operators are defined for the <code>List</code> module like so:
▲<syntaxhighlight lang="ocaml"># #camlp4o;;
▲<syntaxhighlight lang="ocaml">
let (--) a b = List.init (b-a+1) ((+)a)
=====Historical note=====
▲- : int list = [6; 8]</syntaxhighlight>
:OCaml never had a built-in list-comprehension syntax. However, there have been a couple of preprocessing syntax extensions which aimed to add list comprehensions sugar to the language. One of which was shipped directly with [https://github.com/camlp4/camlp4 camlp4], a tool for syntax extensions that was bundled with the OCaml compiler distribution, up to version 4.02 (2014), and was completely deprecated after version 4.08 (2019).
▲:Another, [
=={{header|Oz}}==
|