× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Pass multiple arguments to map's func argument

Carsten König
Jul 17, 2015
<h2>using sections</h2> <p>you can use a <em>section</em> like this:</p> <pre><code>Prelude&gt; let func x y = x / y Prelude&gt; map (`func` 2) [2,4,6,8] [1.0,2.0,3.0,4.0] </code></pre> <p>see when you write a function in <em>backticks</em> you make it into an operator - then you can plug in values to the left or to the right to (for <code>x</code> or <code>y</code> here).</p> <p>If you wanted to substitute for <code>x</code> then you could have used <em>normal</em> partial application as well:</p> <pre><code>Prelude&gt; map (func 24) [2,4,6,8] [12.0,6.0,4.0,3.0] </code></pre> <p>which is the same as</p> <pre><code>Prelude&gt; map (24 `func`) [2,4,6,8] [12.0,6.0,4.0,3.0] </code></pre> <h2>using a lambda</h2> <p>of course if you don't like this at all you can always use lambda's:</p> <pre><code>Prelude&gt; map (\x -&gt; func x 2) [2,4,6,8] [1.0,2.0,3.0,4.0] </code></pre> <h2>using list-comprehension</h2> <p>or you can do the same as you did in Python (use a list comprehension):</p> <pre><code>Prelude&gt; [ func x 2 | x &lt;- [2,4,6,8] ] [1.0,2.0,3.0,4.0] </code></pre> <p>ok I think right now I can think of no other (easy) ones ;)</p> <h2>using partial application with <code>flip</code></h2> <p><code>flip</code> and partial application (I think a bit less readable - but I find it kind of funny ;):</p> <pre><code>Prelude&gt; map (flip f 2) [2,4,6,8] [1.0,2.0,3.0,4.0] </code></pre> <h2>remark / <code>div</code></h2> <p>as you only dealt with <code>Int</code>s here you probably would want to use <code>div</code> instead of <code>(/)</code>:</p> <pre><code>Prelude&gt; map (`div` 2) [2,4,6,8] [1,2,3,4] </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31121640/Pass%20multiple%20arguments%20to%20map's%20func%20argument/31121692">Stack Overflow</a>.</p>
comments powered by Disqus