In Haskell everything has a type right? So if checks word dict then ...
has a specific type,
in this case (String, Int)
. Imagine if checks word dict
was false, we still need to produce something of type (String, Int)
so what on earth could we do?
To avoid this obvious quagmire, Haskell requires an else
clause always. Its more accurate to think of if then else
as something like C's foo ? bar : baz
(ternary operator).
In a list comprehension however, there's a nice solution. You can put predicates in the body of the comprehension to "guard" what reaches the left side
[(word, scores word) | word <- words, checks word dict]
This basically words by selecting each word in words
and then checking checks word dict
, if this returns false, we "skip" this element.
There's actually a connection to monads and something called MonadPlus
, but I won't mention this because I think it will only serve to confuse you :) It's alright to treat it as magic for a little bit.