Skip to content

Instantly share code, notes, and snippets.

@tacryt-socryp
Created May 16, 2018 22:35
Show Gist options
  • Save tacryt-socryp/d7ab5520cb9259ab0f26f92db7c0a564 to your computer and use it in GitHub Desktop.
Save tacryt-socryp/d7ab5520cb9259ab0f26f92db7c0a564 to your computer and use it in GitHub Desktop.
Subtraction written in Hoon
|%
++ new-dec
|= a/@
^- @
?: (lte a 0) ::
0
?: (lte a 1)
0
%- inner-dec :+(a 1 0)
++ inner-dec
|= e=[a=@ b=[c=@ d=@]] :: sample (input mold)
^- @ :: return atom
::~& e :: printf
?: (gte c.b.e a.e) :: if (c.b.e >= a.e)
d.b.e :: yes, return result
%- inner-dec :+(a.e .+(c.b.e) .+(d.b.e)) :: no, call inner-dec with tuple of a.e (c.b.e + 1) and (d.b.e + 1)
++ new-add
|= a=[b=@ c=@]
^- @
%- inner-add :+(b.a c.a 0) :: call add function
++ inner-add
|= e=[a=@ b=[c=@ d=@]] :: sample (input mold). a.e = 1st operand, c.b.e = 2nd operand, d.b.e = result.
^- @ :: return atom
::~& e :: printf
?: (gte a.e 1) :: if a.e >= 1
%- inner-add :+((dec a.e) c.b.e .+(d.b.e)) :: yes, call inner-add with a tuple of (a.e - 1), c.b.e, and (d.b.e + 1)
?: (gte c.b.e 1) :: no, check if c.b.e >= 1
%- inner-add :+(a.e (dec c.b.e) .+(d.b.e)) :: yes, call inner-add with a tuple of a.e, (c.b.e - 1), and (d.b.e + 1)
d.b.e :: no, return result
++ new-sub
|= a=[b=@ c=@]
^- @
~& a
?: (gte c.a .+(b.a)) :: if (c.a + 1) >= b.a
!! :: yes, crash
%- inner-sub [b.a c.a] :: no, subtract a from b
++ inner-sub
|= e=[a=@ b=@] :: sample (input mold)
^- @ :: return mold
?: (gte b.e 1)
%- inner-sub [(dec a.e) (dec b.e)]
a.e
--
/+ mylib :: import
=, mylib :: alias to the subject (don't have to type mylib anymore)
|= [a=@ b=@]
^- @
(new-sub a b)

Subtraction

Write a gate that takes two integers g and h and returns (g - h). You may not use sub (or any variant thereof) in the hoon.hoon stdlib, and you may not look at the code for it in hoon.hoon. You may use dec and add if you wish, as long as you've completed 1 and 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment