Skip to content

Instantly share code, notes, and snippets.

@tacryt-socryp
Last active May 16, 2018 22:52
Show Gist options
  • Save tacryt-socryp/0503e4bde222cbfab4c5329f6291f19e to your computer and use it in GitHub Desktop.
Save tacryt-socryp/0503e4bde222cbfab4c5329f6291f19e to your computer and use it in GitHub Desktop.
Factorial Calculator with tail call optimization written in Hoon
/+ mylib :: import
=, mylib :: alias to the subject (don't have to type mylib anymore)
|= a=@
^- @
(new-fac a)

Factorial calculator with tail call optimization

Write a gate that takes some integer n and returns n! (i.e., the factorial of n).

0! = 1 1! = 1 2! = 2 x 1 3! = 3 x 2 x 1 4! = 4 x 3 x 2 x 1 and so on...

Make sure your gate is "tail call optimized". Feel free to look up TCO so that you have a strong understanding of it---this is an important concept for functional programming.

Having a TCO gate means, among other things, that any recursion you use shouldn't be embedded within a larger cell. E.g., don't recurse like this:

[one-result $(c new-c)]

|%
++ new-fac
|= a=@
^- @
%- inner-fac [a 1]
++ inner-fac
|= c=[a=@ b=@] :: sample (input mold)
^- @ :: return mold
?: (gte 0 a.c)
1
?: (gte 1 a.c)
b.c
%- inner-fac [(dec a.c) (mul b.c a.c)]
--
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment