Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The simple "standard" trick is</p> <pre><code>(apply append (map (lambda(x)(if (eq? x 'c) (list x) '())) '(a b c d))) ;Value 12: (c) </code></pre> <p>which returns <code>(c)</code>. The <code>apply append ... map</code> combo is known as <code>mapcan</code> in Common Lisp ("mapcan" for "map and concatenate"):</p> <pre><code>[1]&gt; (mapcan #'(lambda(x)(if (eq x 'c) (list x))) '(a b c d)) (C) </code></pre> <p>MIT Scheme has this function too.</p> <p><code>apply append</code> flattens one level of its argument list, <code>(apply append '((a) () (c) ()))</code> <strong>==</strong> <code>(append '(a) '() '(c) '())</code> <strong>--></strong> <code>(a c)</code>. Since empty lists disappear, it is useful for eliminating elements with <code>map</code>. This achieves the same effect as <code>filter</code> if you have one available (it is not in <a href="http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-15.html#%_chap_Temp_11" rel="nofollow">R5RS</a>, but it is in <a href="http://srfi.schemers.org/srfi-1/srfi-1.html#FilteringPartitioning" rel="nofollow">SRFI1</a>).</p> <p>It can be used for other effects too, like doubling:</p> <pre><code>[2]&gt; (mapcan #'(lambda(x)(if (evenp x) (list x x))) '(1 2 3 4)) (2 2 4 4) </code></pre> <hr> <p>As an aside, <code>mapcan</code> is what's known as list monad's "bind" (with arguments flipped), and <code>(apply append ...)</code> as its "join" operation. Indeed as it must be for any monad, for lists too <code>bind m f == join (map f m)</code>.</p> <p>This is also the basis for e.g. Haskell's <em>list comprehensions</em>: </p> <pre><code>Prelude&gt; [y | x&lt;-[1,2,3,4], even x, y&lt;-[x,x]] [2,2,4,4] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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