Skip to content

Instantly share code, notes, and snippets.

@cellularmitosis
Last active August 6, 2020 00:00
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/473400a761906d65e61f5000116ee808 to your computer and use it in GitHub Desktop.
Save cellularmitosis/473400a761906d65e61f5000116ee808 to your computer and use it in GitHub Desktop.
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