Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The previous solutions do compile, but won't give the expected result. The function <code>f</code> is never applied to the arguments. A correct code is:</p> <pre><code>let rec list_map f ?(accum = []) l = match l with | head :: tail -&gt; list_map f ~accum:(f head :: accum) tail | [] -&gt; accum;; </code></pre> <p>The inferred type is:</p> <pre><code>val list_map : ('a -&gt; 'b) -&gt; ?accum:'b list -&gt; 'a list -&gt; 'b list = &lt;fun&gt; </code></pre> <p>... in contrast to the wrong one:</p> <pre><code>val list_map : 'a -&gt; ?accum:'b list -&gt; 'b list -&gt; 'b list = &lt;fun&gt; </code></pre> <hr> <p>Please note, that the result list is reversed:</p> <pre><code># list_map ( ( ** ) 2.) [1.;2.;3.;4.];; - : float list = [16.; 8.; 4.; 2.] </code></pre> <p>... and equals the function <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html#VALrev_map" rel="nofollow noreferrer">rev_list from the List module</a>:</p> <pre><code># List.rev_map ( ( ** ) 2.) [1.;2.;3.;4.];; - : float list = [16.; 8.; 4.; 2.] </code></pre> <hr> <p>So you may want to change your function into:</p> <pre><code>let rec list_map f ?(accum = []) l = match l with | head :: tail -&gt; list_map f ~accum:(f head :: accum) tail | [] -&gt; List.rev accum;; </code></pre> <p>... which should be tail-recursive as well (according to the manual) and returns the list in the original order:</p> <pre><code># list_map ( ( ** ) 2.) [1.;2.;3.;4.];; - : float list = [2.; 4.; 8.; 16.] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload