Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This function can be written using do notation. I don't feel bad presenting this because <strong>you probably won't get credit for submitting this</strong> as an answer, because it does not use explicit recursion:</p> <pre><code>import Control.Monad (guard) getIndicesFor :: (a -&gt; Bool) -&gt; [a] -&gt; [Int] getIndicesFor f xs = do (n, x) &lt;- zip [0..] xs guard (f x) return n -- in fact you could write it compactly as a list comprehension -- though I personally avoid list comprehensions, as I find "do" syntax clearer -- getIndicesFor f xs = [n | (n, x) &lt;- zip [0..] xs, f x] </code></pre> <p>Testing...</p> <pre><code>ghci&gt; take 5 $ getIndicesFor even [0 ..] [0, 2, 4, 6, 8] ghci&gt; take 5 $ getIndicesFor even [2, 4 ..] [0,1,2,3,4] </code></pre> <p>So the concept is simple, right? pick an element from the list, test it with the specified function, and add its index to the list if it passes.</p> <p>If you must write this function using explicit recursion, then you will need to handle the two cases differently: does this particular element pass or fail the test? If it passes, then you add its index to the list of results. If it fails, <em>then you don't</em>. This is the main problem with what I see in your code right now.</p> <pre><code>getIndicesFor x (y:ys) = blahblah : getIndicesFor x ys </code></pre> <p>You <em>always</em> add <em>something</em>, whether or not <code>y</code> passes or fails the test. This is wrong. Try using an <code>if</code> or <code>case</code> statement to differentiate the two different cases. Also, if you are using explicit recursion, then you must handle the empty list case explicitly:</p> <pre><code>getIndicesFor x [] = ??? </code></pre>
    singulars
    1. This table or related slice is empty.
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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