Skip to content

Instantly share code, notes, and snippets.

@cellularmitosis

cellularmitosis/Makefile

Last active Aug 6, 2020
Embed
What would you like to do?
Janet Exercism: Reverse a string

Blog 2020/8/4

<- previous | index | next ->

Janet Exercism: Reverse a string

Here are Janet solutions (recursive and iterative) to the exercism "reverse a string" problem.

The rules are that you are not allowed to use any built-in reverse functions.

default: test-all bin-all
test-all: test-recur test-iter
test-recur:
./rev-str-recur.janet
test-iter:
./rev-str-iter.janet
bin-all: rev-str-recur rev-str-iter
rev-str-recur: rev-str-recur.janet
jpm quickbin rev-str-recur.janet rev-str-recur
rev-str-iter: rev-str-iter.janet
jpm quickbin rev-str-iter.janet rev-str-iter
clean:
rm -f rev-str-recur.c rev-str-recur rev-str-iter rev-str-iter.c
.PHONY: default test-all test-recur test-iter bin-all clean
#!/usr/bin/env janet
# reverse a string, without using the built-in reverse functions.
(defn rev-str-iter [s]
(var b @"")
(var i (length s))
(while (> i 0)
(buffer/push-byte b (get s (- i 1)))
(-- i))
b)
(defn main [& args]
(print (rev-str-iter ""))
(print (rev-str-iter "a"))
(print (rev-str-iter "ab"))
(print (rev-str-iter "abc")))
#!/usr/bin/env janet
# reverse a string, without using the built-in reverse functions.
# conceptually, what we want is this:
# (defn reverse [s]
# (join (last s) (reverse (all-but-last s))))
(defn reverse-str [s]
(defn join [& ss]
(string (splice ss)))
(defn last [s]
(string/slice s -2 -1))
(defn all-but-last [s]
(string/slice s 0 -2))
(if (= 0 (length s))
""
(join (last s) (reverse-str (all-but-last s)))))
(defn main [& args]
(print (reverse-str ""))
(print (reverse-str "a"))
(print (reverse-str "ab"))
(print (reverse-str "abc")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.