(load library)(d f(q((n)(i(e n 1)0(inc(f(i(even? n)(/ n 2)(inc(* 3 n
Try it online! (Note that the repl auto-closes parentheses; on TIO, they have to be explicitly closed, which I've done in the footer.)
This is the same recursive solution as, e.g., Carcigenicate's Clojure answer. Because tinylisp has only addition and subtraction built in, I load the standard library to get even?
, /
, and *
(and inc
, which is the same length as a 1
but looks nicer). Other library functions would make the code longer; for instance, I'm defining the function manually with (q((n)(...)))
rather than using (lambda(n)(...))
. Here's how it would look ungolfed and indented:
(load library)
(def collatz
(lambda (n)
(if (equal? n 1)
0
(inc
(collatz
(if (even? n)
(/ n 2)
(inc (* 3 n))))))))
Going the other direction, here's a 101-byte solution that doesn't use the library. The E
function returns n/2
if n
is even and the empty list (falsey) if n
is odd, so it can be used both to test evenness and to divide by 2.*
(d E(q((n _)(i(l n 2)(i n()_)(E(s n 2)(a _ 1
(d f(q((n)(i(e n 1)0(a 1(f(i(E n 0)(E n 0)(a(a(a n n)n)1
* Only works for strictly positive integers, but that's exactly what we're dealing with in this challenge.