Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The key step you're going to have to make is to think <em>inductively</em>. Your current solution:</p> <pre><code>and :: [Bool] -&gt; Bool and [] = True and [True, True] = True and [False, False] = True and [True, False] = False </code></pre> <p>enumerates some of the possibilities, but it obviously doesn't work for all lists. So how to write one that will work for lists of any length?</p> <p>In Haskell, you can usually write your functions by taking apart a data type. In this case, lists. Lists are defined as:</p> <pre><code>data [a] = [] | a : [a] </code></pre> <p>So, lists have two cases: either the empty list, or a one element with a tail. Let's start writing your <code>and</code> function then, so that it matches those two cases for lists:</p> <pre><code>and [] = True and (a:as) = ... </code></pre> <p>So, the "base case", the empty list, is <code>True</code>. But what should we do for the case of a list with one element, and some tail?</p> <p>Well, we already have the <code>&amp;&amp;</code> function in Haskell:</p> <pre><code>&gt; True &amp;&amp; True True &gt; True &amp;&amp; False False &gt; False &amp;&amp; True False &gt; False &amp;&amp; False False </code></pre> <p>Interesting! So, <code>&amp;&amp;</code> takes two arguments, and correctly determines if both arguments are True. And we are currently have a list with one element, and a list for a tail. And at the same time, we're defining the <code>and</code> function, that results in a single boolean value when applied to a list.</p> <p>So we can make <strong>the inductive step</strong> and use the function we're defining, <code>and</code>, together with the <code>&amp;&amp;</code> binary operator, to finish our definition:</p> <pre><code>and [] = True and (a:as) = a &amp;&amp; (and as) </code></pre> <p>So we evaluate the tail of the list to some value (recursively), and use the <code>&amp;&amp;</code> operator to combined <em>that</em> value with the current value, and that's our function written.</p> <p>Recursion and induction, driven by the recursive structure of the lists, are <em>the</em> key technique to learn in programming. If you can write this, you're making a big step forward.</p>
    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.
    3. VO
      singulars
      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