added userlib reduce function
Signed-off-by: Ava Hahn <ava@sunnypup.io>
This commit is contained in:
parent
3f75157fac
commit
4f6622730a
3 changed files with 28 additions and 1 deletions
|
|
@ -507,7 +507,6 @@ Note: this section only tracks the state of incomplete TODO items. Having everyt
|
||||||
- Custom ast pretty print
|
- Custom ast pretty print
|
||||||
- Implement Compose for lambdas
|
- Implement Compose for lambdas
|
||||||
Document this in relevant readme sections
|
Document this in relevant readme sections
|
||||||
- Userlib Reduce function
|
|
||||||
- File operations
|
- File operations
|
||||||
- read-to-string
|
- read-to-string
|
||||||
- write-to-file
|
- write-to-file
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,7 @@
|
||||||
(let ((test-val 0))
|
(let ((test-val 0))
|
||||||
(set (q test-val) 3)
|
(set (q test-val) 3)
|
||||||
(eq? test-val 3))))
|
(eq? test-val 3))))
|
||||||
|
|
||||||
('prepend prepends to list'
|
('prepend prepends to list'
|
||||||
(quote
|
(quote
|
||||||
(let ((list (2 3 4))
|
(let ((list (2 3 4))
|
||||||
|
|
@ -48,6 +49,12 @@
|
||||||
(adder (lambda (x) (add 1 x))))
|
(adder (lambda (x) (add 1 x))))
|
||||||
(eq? (map adder list) (2 3 4)))))
|
(eq? (map adder list) (2 3 4)))))
|
||||||
|
|
||||||
|
('reduce function adds numbers'
|
||||||
|
(quote
|
||||||
|
(let ((list (1 2 3))
|
||||||
|
(adder (lambda (x y) (add x y))))
|
||||||
|
(eq? (reduce adder list) (add 1 2 3)))))
|
||||||
|
|
||||||
;; add more test cases here
|
;; add more test cases here
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -64,3 +64,24 @@ result is added to a new list. Returns the new list.'
|
||||||
(set (q result) (cons result current-res))
|
(set (q result) (cons result current-res))
|
||||||
(set (q list-iter) (pop remaining))))
|
(set (q list-iter) (pop remaining))))
|
||||||
result))
|
result))
|
||||||
|
|
||||||
|
(def reduce
|
||||||
|
'Takes two arguments: a function and a list.
|
||||||
|
The function is expected to take two arguments:
|
||||||
|
* the current list item
|
||||||
|
* the previous result
|
||||||
|
Initially the function will take element1 and element2, outputting result1.
|
||||||
|
Then the function will take result1 and element3, outputting result2.
|
||||||
|
this will continue iuntil the list is exhausted.'
|
||||||
|
(func list)
|
||||||
|
(let ((list-iter (pop list))
|
||||||
|
(result (car list-iter)))
|
||||||
|
(set (q list-iter) (pop (cdr list-iter)))
|
||||||
|
(if (lt? (len list) 2)
|
||||||
|
(echo "list too short!")
|
||||||
|
(while (gt? (len list-iter) 1)
|
||||||
|
(let ((current (car list-iter))
|
||||||
|
(remaining (cdr list-iter)))
|
||||||
|
(set (q result) (func result current))
|
||||||
|
(set (q list-iter) (pop remaining)))))
|
||||||
|
result))
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue