Added cond function to Userlib
Added the cond function to Userlib, also added the associated tests and documentation.
This commit is contained in:
parent
fb724ccee4
commit
bd23198009
3 changed files with 68 additions and 1 deletions
|
|
@ -55,6 +55,36 @@
|
|||
(adder (lambda (x y) (add x y))))
|
||||
(eq? (reduce adder list) (add 1 2 3)))))
|
||||
|
||||
('cond evaluates the first branch that returns true'
|
||||
(quote
|
||||
(let ((switch-one false)
|
||||
(switch-two false)
|
||||
(switch-three false))
|
||||
(cond (q
|
||||
((false (toggle switch-one))
|
||||
(true (toggle switch-two))
|
||||
(true (toggle switch-three)))))
|
||||
(and (not switch-one) switch-two (not switch-three)))))
|
||||
|
||||
('cond doesnt do anything if all the branches are false'
|
||||
(quote
|
||||
(let ((switch-one false)
|
||||
(switch-two false)
|
||||
(switch-three false))
|
||||
(cond (q
|
||||
((false (toggle switch-one))
|
||||
(false (toggle switch-two))
|
||||
(false (toggle switch-three)))))
|
||||
(and (not switch-one) (not switch-two) (not switch-three)))))
|
||||
|
||||
('cond returns the result of the branch that is evaluated'
|
||||
(quote
|
||||
(let ((variable false))
|
||||
(set (q variable)
|
||||
(cond (q
|
||||
((true true)))))
|
||||
variable)))
|
||||
|
||||
('contains? finds elem in list'
|
||||
(quote
|
||||
(contains? (1 2 3) 1)))
|
||||
|
|
|
|||
|
|
@ -84,6 +84,20 @@ this will continue iuntil the list is exhausted.'
|
|||
(set (q list-iter) (pop remaining)))))
|
||||
result))
|
||||
|
||||
(def cond
|
||||
'Takes one argument: a list of pairs consisting of a form returning a bool and a form to execute
|
||||
The function iterates over the list checking if the first form of a pair evaluates to true, in which
|
||||
case it will execute the second form of the pair, returning its result, and stop the loop.'
|
||||
(list)
|
||||
(let ((iter list))
|
||||
(while (gt? (len iter) 0)
|
||||
(let ((current (car iter))
|
||||
(remaining (pop iter)))
|
||||
(if (eval (car current))
|
||||
(car (pop ((set (q iter) ())
|
||||
(eval (cdr current)))))
|
||||
(set (q iter) (cdr remaining)))))))
|
||||
|
||||
(def contains?
|
||||
'Takes two arguments: a list and an element.
|
||||
Returns true if the list contains the element.'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue