{{ message }}

Instantly share code, notes, and snippets.

# cellularmitosis/Makefile

Last active Aug 20, 2020
Janet Exercism: Implement map

Blog 2020/8/5

# 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 [])))

### andrewchambers commented Aug 6, 2020 • edited

 Recursion with an index, some sort of middle ground. ``````(defn map-into [f a ind &opt from] (default from 0) (if (>= from (length ind)) a (do (array/push a (f (in ind from))) (map-into f a ind (inc from))))) (defn map [f ind] (map-into f @[] ind)) (pp (map inc [1 2 3])) ``````

### cellularmitosis commented Aug 6, 2020

 @andrewchambers nice!