Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 86f8d60c78
Fetching contributors…

Cannot retrieve contributors at this time

36 lines (29 sloc) 1.114 kb
<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>
Jump to Line
Something went wrong with that request. Please try again.