Skip to content

Instantly share code, notes, and snippets.

@cellularmitosis
Last active August 20, 2020 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cellularmitosis/507e1f259573644bdf3c0e2bbfdac375 to your computer and use it in GitHub Desktop.
Save cellularmitosis/507e1f259573644bdf3c0e2bbfdac375 to your computer and use it in GitHub Desktop.
Janet Exercism: Implement map

Blog 2020/8/5

<- previous | index | next ->

Janet Exercism: Implement map

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 [])))
@cellularmitosis
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment