;; Converting Python functions to Scheme (define (one) 1) (define (two x y z) (+ x (* y z))) (define (three n) (if (= n 0) 0 (+ (remainder n 10) (* 2 (three (quotient n 10)))))) ;; Practice with lambdas ; (((f) 3)) evaluates to 1 (define (f) (lambda (x) (lambda () 1))) ; ((g g) g) evaluates to 42 (define g (lambda (x) (lambda (y) 42))) ;; Pairs practice (define x (cons (cons 1 2) (cons (cons (cons 4 5) (cons 6 7)) 3))) (car (car x)) ;; select 1 (cdr (cdr x)) ;; select 3 (cdr (cdr (car (cdr x)))) ;; select 7 ;; Lists practice (define (append lst1 lst2) (if (null? lst1) lst2 (cons (car lst1) (append (cdr lst1) lst2)))) ;; quicksort (define (filter-comp comp pivot s) (filter (lambda (x) (comp x pivot)) s)) (define (quick-sort s) (if (<= (length s) 1) s (let ((pivot (car s))) (append (quick-sort (filter-comp < pivot s)) (filter-comp = pivot s) (quick-sort (filter-comp > pivot s)))))) ;; turtle graphics (define (triangle) (forward 100) (right 120) (forward 100) (right 120) (forward 100) (right 120)) (define (repeat k fn) (if (> k 0) (begin (fn) (repeat (- k 1) fn)) 'done)) (define (tri fn) (repeat 3 (lambda () (fn) (lt 120)))) (define (sier d k) (tri (lambda () (if (= k 1) (fd d) (leg d k))))) (define (leg d k) (sier (/ d 2) (- k 1)) (penup) (fd d) (pendown))