Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are <em>several</em> ways to convert the code in the question to Scheme. The first one I can think of:</p> <pre><code>(define (print-even n) (let loop ((i 0)) (if (&lt;= i n) (begin (print i) (newline) (loop (+ i 2)))))) </code></pre> <p>Notice this:</p> <ul> <li>The solution is written as a recursive procedure</li> <li>Instead of a <code>for</code> loop, I'm using a construct called a <em>named let</em>, which permits the initialization of some iteration variables (<code>i</code> in this case, initialized to <code>0</code>) and the repeated execution of a recursive procedure (<code>loop</code> in this case), producing an effect similar to a <code>for</code>, even in performance</li> <li>The stop condition in the "loop" is handled with essentially the same expression: repeat the body of the iteration as long as <code>(&lt;= i n)</code>, when that condition becomes false, the iteration ends</li> <li>The <code>begin</code> surrounds the body of the "loop", just as the curly braces <code>{}</code> do in the original code</li> <li>The <code>print</code> procedure performs the expected operation; for readability I added a new line after printing each number</li> <li>The increment part of the original loop <code>i += 2</code> is handled by the expression <code>(+ i 2)</code>, inside the recursive call</li> </ul> <p>So you see, the process being executed is essentially the same, only the way to <em>write</em> it (the syntax!) is different. Give it a try, type this:</p> <pre><code>(print-even 6) </code></pre> <p>... And the following will get printed on the screen:</p> <pre><code>0 2 4 6 </code></pre> <p>Another possible way to implement the procedure, more similar to the original code, although (this is completely subjective) less idiomatic than the previous one:</p> <pre><code>(define (print-even n) (do ((i 0 (+ i 2))) ((&gt; i n)) (print i) (newline))) </code></pre> <p>Finally, if you're using <a href="http://racket-lang.org/" rel="nofollow">Racket</a> this will seem even more familiar to you:</p> <pre><code>#lang racket (define (print-even n) (for ((i (in-range 0 (+ n 1) 2))) (print i) (newline))) </code></pre>
    singulars
    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.
 

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