Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Do we have any statements like "foreach", or for loop to do what i think? </p> </blockquote> <p>No.</p> <blockquote> <p>or any other suggestions?</p> </blockquote> <p>To iterate over a list in scheme, you'd either use pre-existing functions that iterate over the list (like <code>map</code>, <code>filter</code> or <code>fold-left</code>) or you write your own using recursion. Depending on which Scheme dialect you're using, there might already be a function (called <code>every</code> or <code>andmap</code>) that takes a list and a condition and returns <code>#t</code> iff the condition is true for every item in the list. Otherwise, you'd have to write it recursively or as a fold (though not all Scheme dialects have fold function either).</p> <p>A recursive function that iterates over a list usually looks something like this:</p> <pre><code>(define (do-something-with-list lst) (if (null? lst) (handle-the-case-that-list-is-empty) (combine (some-transformation-on (car lst)) (do-something-with-list (cdr lst))))) </code></pre> <p>For example to sum all numbers in a list that are greater than 5 (without using <code>filter</code> or <code>fold-left</code>), you'd write:</p> <pre><code>(define (sum-all-numbers&gt;5 numbers) (if (null? numbers) ; Sum of the empty list is 0 0 (+ ; If the head of the list is &gt; 5, add the number to the result, else ; add 0 (if (&gt; (car numbers) 5) (car numbers) 0) (sum-all-numbers&gt;5 (cdr numbers))))) </code></pre> <p>You can use the same approach to define your function.</p> <p>PS: <code>(if condition #t #f)</code> is redundant -- you can just write <code>condition</code> (unless <code>condition</code> is something other than a boolean and you need to convert it to a boolean, but I can't think of a scenario where that'd be necessary).</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