Skip to content
This repository
tree: 86f8d60c78
Fetching contributors…

Cannot retrieve contributors at this time

file 35 lines (29 sloc) 1.114 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
<h3>Iterators</h3>

<p>What is really fun is that you can now mix anonymous functions and
iterators.
Let's take an example with list. If you want to increment all elements
of a list, you will use <code>List.map</code>:</p>
<p><code>List.map (fun x -> x + 1) [ 1; 2; 3; 4 ]</code></p>
<br />
<p>Here, <code>x</code> is an element of the list, <code>x + 1</code>
is the operation that will be done on <code>x</code>. The result will
be a list with all its elements incremented by 1.</p>

<br />
<p>Here is an example with <code>fold_left</code>. If you want to
compute the sum of all elements of a list:</p>
<pre><code>List.fold_left
     (fun acc x -> acc + x)
     0
     [ 1; 2; 3; 4 ]
</code></pre>

<p>If we have :</p>
<p><code>let plus = fun acc x -> acc + x</code></p>
<p>then:</p>
<p><code>List.fold_left plus 0 [ 1; 2; 3; 4 ]</code></p>
<p>is equivalent to:</p>
<p><code>plus (plus (plus (plus 0 1) 2) 3) 4</code></p>

<br />
<p>To finish, you may need to print values from a list:</p>
<p><code>List.iter print_int [ 1; 2; 3; 4 ]</code></p>


<br />
<p>You can do the same sort of things on arrays too.</p>
Something went wrong with that request. Please try again.