Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The main indendation rule in Haskell is that if you want to continue a definition on another line, it has to be further indented than the the thing you're defining. In this case the guards for your <code>add</code> function are <em>less</em> indented, so that's what the compiler is complaining about.</p> <p>Disregarding the other errors in your code, the indentation should be something like this:</p> <pre><code>addNums key num = add [] key num where add res a:as b:bs | a == [] = res | otherwise = add res:(a+b) as bs </code></pre> <p>Also note that the exact amount of indentation does not matter, only the indentation of the continuing lines relative to the thing being defined.</p> <p>Another syntactic problem with your code is that you seem to have misunderstood the precedence rules of Haskell. In Haskell, function application binds <em>tighter than any operator</em>, so <code>add res a:as b:bs</code> is parsed as <code>(add res a):(as b):bs</code>, while you meant <code>add res (a:as) (b:bs)</code>.</p> <p>The final problems are type errors. The <code>(:)</code> operator has the type <code>a -&gt; [a] -&gt; [a]</code>, which means that it takes <em>an element</em> and <em>a list</em>, and produces <em>a list</em>. In your code <code>res:(a+b)</code>, you appear to have this reversed, as <code>res</code> is a list and <code>a+b</code> is the element. Since there is no operator in Haskell to append a single element to the <em>end</em> of a list, you'll have to use the list concatenation operator <code>(++) :: [a] -&gt; [a] -&gt; [a]</code> instead: <code>res ++ [a+b]</code>.</p> <p>You're also comparing the <em>element</em> <code>a</code> to the <em>list</em> <code>[]</code> in your guard. This is probably not what you meant, and the pattern <code>(a:as)</code> would not match if the list was empty. The easiest solution to this is to add another pattern instead of your guard.</p> <p>Putting all of this together, this code should hopefully do what you intended:</p> <pre><code>addNums key num = add [] key num where add res [] _ = res add res (a:as) (b:bs) = add (res ++ [a+b]) as bs </code></pre> <p>P.S. Repeatedly appending to the end of a list is not very efficient. In fact, it's O(n<sup>2</sup>). You might want to add to the front instead and reverse the list when you're done. This is O(n).</p> <hr> <p>References:</p> <ul> <li><a href="http://en.wikibooks.org/wiki/Haskell/Indentation" rel="nofollow">Indentation</a></li> <li><a href="http://en.wikibooks.org/wiki/Haskell/Pattern_matching" rel="nofollow">Pattern matching</a></li> </ul>
 

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