Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try to give the expression a type.</p> <pre><code>xs = [if x &lt; 3 then "bang" else "boom" | x &lt;- xs] </code></pre> <p>So <code>xs</code> is a list, we don't know yet what type its elements have, so let's look at that next. The list elements are</p> <pre><code>if x &lt; 3 then "bang" else "boom" </code></pre> <p>which is an expression of type <code>String</code> (aka <code>[Char]</code>).</p> <p>So <code>xs :: [String]</code>. Since the <code>x</code> from the expression describing the list elements is taken from the list <code>xs</code> itself, it is a <code>String</code> too, and is used in the comparison</p> <pre><code>if x &lt; 3 </code></pre> <p>Now, <code>3</code> is an integer literal, thus it is polymorphic and has type</p> <pre><code>3 :: Num a =&gt; a </code></pre> <p>So from the expression <code>x &lt; 3</code>, we have</p> <ul> <li>a <code>Num</code> constraint from the literal,</li> <li>the type <code>String</code> from the fact that <code>x</code> is drawn from a list of <code>String</code>s.</li> </ul> <p>Thus we need a <code>Num</code> instance for <code>String</code> to have a well-typed expression.</p> <p>Usually, there is no <code>Num</code> instance for <code>String</code> (what would a useful one look like?), so you get a type error.</p> <p>If <code>xs</code> is the argument of a function,</p> <pre><code>boom xs = [if x &lt; 3 then "bang" else "boom" | x &lt;- xs] </code></pre> <p>there is no reason why the type of <code>x</code> should be <code>String</code>, hence that works.</p>
 

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