Conditionals & Locals

Today we extend our language with conditionals and locals.

But first…

Some forms in Racket

(+ 4 3)

(* (+ 2 3)
   (+ 4 5))

(if (= 3 4)
    (+ 5 6)
    (* 7 8))

(+ (+ 5 6)
   (* 7 8))

(define (foo n)
  (+ (* 2 n) 3))

(define foo (lambda (n)
              (+ (* 2 n) 3)))

(foo 7)

((lambda (n)
   (+ (* 2 n) 3))
 7)

(lambda (n)
  (+ (* 2 n) 3))

+

(define + -)

(+ 4 3)

Some forms in Lisp

(defvar foo ( + 3 4))

(defun foo (n)
  (+ (* 2 n) 3))

foo

(foo foo)

(function foo)

(funcall (function foo) 4)

(funcall 'foo 4)

(funcall #'foo 4)

Mapcar and Reduce

(mapcar #'foo '(1 2 3 4))

(mapcar (lambda (n)
          (+ (* 2 n) 3))
        '(1 2 3 4))

(reduce (lambda (x y)
          (list 'p x y))
        '(1 2 3 4)
        :initial-value 'v)

(reduce (lambda (x y) (list 'p x y))
        '(1 2 3 4)
        :initial-value 'v
        :from-end t)

(reduce #'cons
        '(1 2 3 4)
        :initial-value nil
        :from-end t)

(reduce #'cons
        '(1 2 3 4)
        :from-end t)

(defun snoc (a b)
  (cons b a))

(reduce #'snoc
        '(1 2 3 4)
        :initial-value nil)

(reduce #'+ '(1 2 3 4))

(defun bar (x y)
  (+ x (* 2 y)))

(reduce #'bar '(1 2 3 4))

(reduce #'bar '(1 2 3 4)
        :initial-value 100)

let and let*

(let ((x (+ 3 4)))
  (* 2 x))

(let ((x 3))
  (let ((x 2))
    (* 2 x)))

(let ((x 3))
  (* x
     (let ((x 2))
       (* 2 x))))

(let ((x (+ 3 4))
      (y (* 5 6)))
  (+ x y))

(let ((x (+ 3 4))
      (y (* 5 6)))
  (let ((x (+ 3 y))
        (y (* 5 x)))
    (+ x y)))
(let* ((x (+ 3 4)))
  (* 2 x))

(let* ((x 3))
  (let* ((x 2))
    (* 2 x)))

(let* ((x 3))
  (* x
     (let* ((x 2))
       (* 2 x))))

(let* ((x (+ 3 4))
       (y (* 5 6)))
  (+ x y))

(let* ((x (+ 3 4))
       (y (* 5 6)))
  (let* ((x (+ 3 y))
         (y (* 5 x)))
    (+ x y)))

let and lambda

(let ((x (+ 3 4)))
  (* 2 x))

((lambda (x) (* 2 x))
 (+ 3 4))

Exercises

generalized boolean n. an object used as a truth value, where the symbol nil represents false and all other objects represent true. See boolean.

  • Add a full-fledged let to your language. It should be able to interpret this correctly.

    (let ((x 1)
          (y 2))
      (let ((x y)
            (y x))
        (- x y)))
    
  • Add a full-fledged let* to your language.

Author: Breanndán Ó Nualláin <o@uva.nl>

Date: 2025-04-24 Thu 11:05