Warning

## Lab 1: Introduction to Scheme

The goal of this lab is to make the students familiar with the IDE we will use for Scheme and help them write first simple programs.

#### Dr. Racket IDE

The IDE can be downloaded for free for Linux, Windows, MAC from: https://racket-lang.org/ The students can use the one installed in the lab computers. The teacher may help the students (to a reasonable degree) to get the IDE running on students’ laptops.

Get familiar with the definition window and REPL in DrRacket. The documentation of implemented functions is accessible via Help Desk in the menu.

The language (scheme variant) can be selected via the #lang directive.

1. #lang racket (same as #lang scheme)
2. #lang r5rs (if you wish to follow the R5RS standard)

#### Scheme/Racket basics

Start interaction in REPL. Scheme uses prefix notation for all functions. Let students compute simple formulas, e.g., 2+3/5.

Exercise 1: Write a recursive function my-even? that decides whether a number is even using only functions +, -, = (without mutual recursion).

solution

Exercise 2: Using the function string-append, create a function (copy-str n str) taking as arguments an integer n, a string str and returns a string consisting of n-many copies of str. For example (copy-str 3 “abc”) ⇒ “abcabcabc”.

solution

Exercise 3: Rewrite the function from Exercise 2 so that it uses tail recursion.

solution

Exercise 4: Write a function (consecutive-chars first last) which takes two characters and returns a string consisting of a sequence of consecutive characters starting with first, ending with last and following the order in ASCII table. For example (consecutive-chars #\A #\D) ⇒ “ABCD” or (consecutive-chars #\z #\u) ⇒ “zyxwvu”. For converting characters into positions in ASCII table use functions char->integer and integer->char.

solution

Try to solve the following individual tasks.

Task 1: Write a function num-of-digits which takes an integer n and computes the number of digits n has in the standard decimal representation. For example (num-of-digits 123) ⇒ 3 or (num-of-digits -3456) ⇒ 4.

Hint: The number of digits can be computed by successive dividing the input number by 10. For the integer division, you can use the function quotient.

solution

Task 2: Write a function (num->str n [radix 10]) taking as input an integer n together with radix denoting the number of symbols used to represent the number n (for example 2,10,16 for binary, decimal, hexadecimal representation respectively). This function returns a string containing the representation of n in the corresponding numerical system. For the representation use the standard symbols 0123456789ABCDEF.

Examples:

• (num->str 52) ⇒ “52”,
• (num->str 5 2) ⇒ “101”,
• (num->str 255 16) ⇒ “FF”.

Hint: The representation can be obtained by consecutive division of n by radix and collecting the remainders. The remainder after integer division can be computed by the function remainder.

solution