Home > Software engineering >  Printing each number in new line in Scheme
Printing each number in new line in Scheme

Time:11-14

I need a help to convert this Pascal code to Scheme code:

program reverseorder;
type
arraytype = array [1..5] of integer;

var
arr:arraytype;
i:integer;

begin

for i:=1 to 5 do
    arr[i]:=i;

for i:=5 downto 1 do
    writeln(arr[i]);
    
end.

I want to accesses to a specific atom and its seems there aren't iteration method in Scheme.

CodePudding user response:

There are many ways to tackle this problem. With the online interpreter you're using you'll be limited to vanilla Scheme, and the solution will be more verbose than needed, using recursion:

(define lst '(1 2 3 4 5))

(let loop ((rev (reverse lst)))
  (when (not (null? rev))
    (display (car rev))
    (newline)
    (loop (cdr rev))))

With Racket, which is aimed at beginners, you can write a much simpler (albeit non-standard) solution:

(define lst (range 1 6))

(for ([e (reverse lst)])
  (displayln e))

Either way, notice that the procedure for reversing a list is already built in the language, and you don't need to reimplement it - naturally, it's called reverse. And if it wasn't obvious already, in Scheme we prefer to use lists, not arrays to represent a sequence of elements - it's recommended to stop thinking in terms of indexes, array lengths, etc. because that's not how things are done in Scheme.

  • Related