Scheme is a minimalist dialect of the Lisp family consisting of a small core for language extension.
Scheme follows the “Prefix Notation”, where operations use the format (* 5 5)
instead of (5 * 5)
. For example, if we wanted to add a lot of numbers together, we conventionally do 2 + 3 + 4 + 6 + 11
, in Scheme we would instead write (+ 2 3 4 6 11)
, which is much more concise.
Arithmetic
A pair of parentheses indicates one step of calculation. A function name comes after the open parenthesis followed by arguments. Tokens are reparated by spaces, tabs and newlines.
(/ (* (+ 2 3) (- 5 3)) 2)
Other included arithmetic operators are:
quotient | sin | exp | asin |
remainder | cos | log | acos |
modulo | tan | sqrt | atan |
Variables
To define a variable, use define
, to print the value of an expression, use display
.
(define color "red") (display color)
Functions
To define a function, use define
, to add parameters to the function, use lambda
. The following functions can thereafter be used like (greet "Alex")
.
(define greet (lambda (name) (string-append "Hello " name "!")))
Another example:
(define add-three (lambda (a b c) (+ a b c)))
The previous example can also be defined using the following short-form:
(define (add-three a b c) (+ a b c))
List
You can create a list of items, and access items in the list by id:
(define colors (list red yellow green cyan)) (list-ref colors 2) ; yellow
Logic
Logic operations are in the format of (if true this that)
where the result of the operation will be this
if the second parameter is true
, otherwise will be that
. In Scheme, true is indicated as #t
, and falseis indicated as #f
.
(define (min a b) (if (< a b) a b))
Compare
eq? | Compares addresses of two objects and returns #t if they are same. |
---|---|
eqv? | Compares types and values of two object stored in the memory space and returns #t if they are same. |
equal? | Compares sequences such as list or string and returns #t if they are same. |