Note that there are some explanatory texts on larger screens.

plurals
  1. POHaskell. Keeping track of indices in order to generate a new list
    primarykey
    data
    text
    <p>I decided to learn Haskell and also learn to think in a more functional way, so I'm trying to solve very simple exercises trying to use a good approach in this paradigm.</p> <p>I'm trying to achieve this simple exercise in Haskell:</p> <pre><code>Input: [2, 4, 1, 1, 2] Output: [True, True, False, False, False, False, True, False, True, True] </code></pre> <p>So, the elements in the <code>Input</code> list will fall to be <code>False</code> in the <code>Output</code> list, and the odd elements will be <code>True</code>; for each one repeated as much times as the value on the <code>Input</code> list indicates.</p> <p>Traverse the <code>Input</code> list, if the <em>i</em>&thinsp;ᵗʰ item is in a pair position, append to output <code>True</code> <em>i</em> times to <code>Output</code>; if the <em>i</em>&thinsp;ᵗʰ item is in an odd position, append <code>False</code> <em>i</em> times to the <code>Output</code> list.</p> <p>It seems to be a very simple problem, and it is. But for me, without any functional programming background, I don't know how to express that in Haskell.</p> <p>I tried to keep track of the current index by using a λ-function within the list comprehension.</p> <pre><code> row :: [Integer] -&gt; [Bool] row xs = [ (last $ zipWith (\i x -&gt; x) [1..] [0..i]) `mod` 2 == 0 | j &lt;- xs, i &lt;- [0..j-1] ] </code></pre> <p>But I'm not understanding its behavior, so I ended using <code>findIndices</code> as a quick alternative:</p> <pre><code> row :: [Integer] -&gt; [Bool] row xs = [ (head $ findIndices (==j) (xs)) `mod` 2 == 0 | j &lt;- xs, i &lt;- [0..j-1] ] </code></pre> <p>Using this last approach it seems OK:</p> <pre><code> &gt; let xs = [ 1, 4, 3, 2 ] &gt; print $ row xs [True,False,False,False,False,True,True,True,False,False] </code></pre> <p>but the problem is not solved, for the items are not necessarily unique:</p> <pre><code> &gt; let xs = [ 2, 2, 4, 3] &gt; print $ row xs [True,True,True,True,True,True,True,True,False,False,False] </code></pre> <p>because <code>head findIndices</code> only gives the first of the occurrences. (Though I think, event that if worked, that's not a very efficient way of solving this problem.)</p> <p>How can I achieve the result I'm looking for in a <em>Haskellian</em> way?</p>
    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.
 

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