(define member
(lambda (mem l)
(cond
((null? l) #f)
((eq? mem (car l)) #t)
(else (member mem (cdr l)))
)
)
)
(member 3 `(1 2 3 4))
Write a recursive fucntion the returns the length of a list
From The Scheme Programming Language
(letrec ([sum (lambda (ls)
(if (null? ls)
0
(+ (car ls) (sum (cdr ls)))))])
(sum '(1 2 3 4 5)))
(define old+ +)
(set! + -)
Rewrite the function below to not use set!
(define quadratic-formula
(lambda (a b c)
(let ([root1 0] [root2 0] [minusb 0] [radical 0] [divisor 0])
(set! minusb (- 0 b))
(set! radical (sqrt (- (* b b) (* 4 (* a c)))))
(set! divisor (* 2 a))
(set! root1 (/ (+ minusb radical) divisor))
(set! root2 (/ (- minusb radical) divisor))
(cons root1 root2))))
(define closureName (lambda ()
(let ((varToClose val))
(lambda ()
update varToClose
)
)
)
(define counter (lambda()
(let ((count 0))
(lambda ()
(set! count (+ count 1))
count))))
From http://people.cs.aau.dk/~normark/prog3-03/html/notes/oop-scheme_themes-classes-objects-sec.html
(define (send message obj . par)
(let ((method (obj message)))
(apply method par)))
(define point (lambda(x y)
(letrec ((getx (lambda () x))
(gety (lambda () y))
(add (lambda (p)
(point
(+ x (send 'getx p))
(+ y (send 'gety p)))))
(type-of (lambda () 'point))
)
(lambda (message)
(cond ((eq? message 'getx) getx)
((eq? message 'gety) gety)
((eq? message 'add) add)
((eq? message 'type-of) type-of)
(else (error "Message not understood")))))))
(define p1 (point 10 20))
(define p2 (point 1 2))
(send 'gety p1)
(send 'getx p2)
(send 'add p1 p2)
Last class to pass a list as the parameters to a function I used this trick
(eval (append `(+) x) )
This is a common need, so there is a function than handles this, apply
The general syntax is
(apply function list)
(apply + `(1 2 3 4 5))
(apply * `(1 2 3 4 5))
(apply string-append `("This" "is" "one"))
What if instead of passing a list as parameters, we wanted to apply a function to each element in the list?
map allows us to do this, returning a list of values from applying the function to each element
The geneneral syntax of map is
(map function list1 list2 ... listn)
(map abs '(1 2 -3 -4 -5))
(map + '(1 2 3) '(3 2 1))
(map (lambda(x) (* x x)) `(1 2 3 4 5))
(filter predicate list)
(filter odd? `(1 2 3 4))
(filter (lambda (x) (string=? (substring x 0 1) "A")) `("Alamo" "alaska" "Baltimore" "Austin" "boston" "Alabama"))
(define file (open-input-file "turing.txt"))
(define readFile
(lambda (p)
(let f ((x (read p)))
(if (eof-object? x)
'()
(cons x (f (read p)))))))
(readFile file)
(define file (open-output-file "schemeOut2.txt"))
(write `("A" "small" "little" "text" "file") file)
(define file (open-output-file "schemeOut2.txt"))
(map (lambda (x) (write x file)) `("A" "small" "little" "text" "file"))