-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.shlisp
71 lines (60 loc) · 1.89 KB
/
test.shlisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
; T and nil, numbers and strings evaluates to itself
(list T nil () 0 -1 2 "one" "two")
; the length builtin can be used on lists and strings
(mapcar length '(() "" (1 2 3) "some string"))
; reverse only works with lists
(reverse '(first second third fourth fifth))
; Dotted end in defun/defmacro argument list gets bound to "rest"
(defun f (head . rest) (cons head (cons (length rest) rest)))
(f 'first 'second 'third)
(f 'single-argument)
; A single symbol gets bound to all
(defun g all (length all))
(g 1 2 3)
(g)
; quote and backquote
'(quote will stop evaluation)
`(with backquote ,(+ 1 2 3 4) things ,@(list 1 2 3) can be spliced)
`(1 2 ,@3)
; setq will bind existing symbols, or create new ones in global scope
(setq x 10)
(let ((x 14))
(setq y x)
(setq x 78)
x)
x
y
; simple macros can be created
(defmacro double (arg)
(let ((g (gensym)))
`(let ((,g ,arg))
(list ,g ,g))))
; let and lambda creates lexical environments that can contain state
(defun counter-class (val step-size)
(let ((direction 'up)
(step-size (if (> step-size 0) step-size 1)))
(let ((set-step (lambda (x)
(setq step-size (if (> x 0) x 1))))
(get-step (lambda ()
step-size))
(flip (lambda ()
(setq direction (if (eq direction 'up) 'down 'up))))
(step (lambda ()
(setq val (if (eq direction 'up) (+ val step-size) (- val step-size))))))
(lambda (method . args)
(cond ((eq method 'step) (step))
((eq method 'flip) (flip))
((eq method 'set-step) (set-step (car args)))
((eq method 'get-step) (get-step))
(T "No such method"))))))
(setq c1 (counter-class 0 1))
(setq c2 (counter-class 0 7))
(c1 'step)
(c1 'step)
(double (c2 'step))
(double (c2 'step))
(c1 'set-step (* 3 (c1 'get-step)))
(c1 'step)
(c1 'flip)
(c1 'step)
(c1 'step)