Blog 2020/8/5
<- previous | index | next ->
Here are Janet solutions (recursive and iterative) to the exercism "implement map without using map" problem.
For some reason, the exercism folks call this problem "accumulate".
| test-all: mymap-iter mymap-recur mymap-iter.janet mymap-recur.janet | |
| chmod +x mymap-recur.janet mymap-iter.janet | |
| ./mymap-recur.janet | |
| ./mymap-recur | |
| ./mymap-iter.janet | |
| ./mymap-iter | |
| mymap-iter: mymap-iter.janet | |
| jpm quickbin mymap-iter.janet mymap-iter | |
| mymap-recur: mymap-recur.janet | |
| jpm quickbin mymap-recur.janet mymap-recur | |
| clean: | |
| rm -f mymap-recur mymap-iter mymap-recur.c mymap-iter.c | |
| .PHONY: clean test-all |
| #!/usr/bin/env janet | |
| (defn mymap-iter [f arr] | |
| (var arr2 @[]) | |
| (each x arr | |
| (array/push arr2 (f x))) | |
| arr2) | |
| (defn square [x] | |
| (* x x)) | |
| (defn main [& args] | |
| (pp (mymap-iter square [1 2 3])) | |
| (pp (mymap-iter square []))) |
| #!/usr/bin/env janet | |
| # conceptually, what we want is this: | |
| # (defn mymap [f arr] | |
| # (join (f (head arr)) (mymap f (tail arr)))) | |
| (defn mymap-recur [f arr] | |
| (if (= 0 (length arr)) | |
| [] | |
| (tuple (f (first arr)) (splice (mymap-recur f (slice arr 1)))))) | |
| (defn square [x] | |
| (* x x)) | |
| (defn main [& args] | |
| (pp (mymap-recur square [1 2 3])) | |
| (pp (mymap-recur square []))) |
Recursion with an index, some sort of middle ground.