Skip to content

Instantly share code, notes, and snippets.

@g-a-v-i-n
Last active July 20, 2018 18:00
Show Gist options
  • Save g-a-v-i-n/ff0ed8dbfd1feebf95894508dfe9f72c to your computer and use it in GitHub Desktop.
Save g-a-v-i-n/ff0ed8dbfd1feebf95894508dfe9f72c to your computer and use it in GitHub Desktop.

decrement

::  input one atom to a gate
|=  a=@
:: make sure input is of type atom
^-  @

:: if input is 0, crash
?:  =(a 0)  ~&  "decrement underflow"  !!

:: c is a counter
=/  c  0
:: loop start point. we need it here to set c to zero once
|-
:: if c + 1 === a, return c
?:  =(+(c) a)
 c
:: increment c
:: $ refers to an arm called $
$(c +(c))

Addition

:: This is a gate that adds two numbers

|=
 [a=@ b=@] :: bar-tis defines a function that takes two inputs
?:
 =(b 0) :: wut-col is an if/else, tis is an equality test
  a :: return a
$(a +(a), b (dec b))

Subtraction


:: make a gate with two inputs that must be atoms
|=  [a=@ b=@]

:: check input, must be atoms
^-  @

:: exit if b is 0 and produce a
?:  =(b 0)
 a

?:  =(a 0)
 ~&  "subtraction underflow"  !!

:: resursivly subtract 1 from each input
$(a (dec a), b (dec b))

Factorial

:: make a gate with one input
|=  [a=@]

:: a must be an atom
^-  @

:: if a is 1, return 1
?:  =(a 1)
  1

:: b is an accumulator, set to 1 once
=/  b  1

:: start a loop
|-

:: exit when a is 0 and return b
?:  =(a 0)
  b

:: recurse
$(a (dec a), b (mul a b))

I didn't get to tail optimization or primes. But I tried to write some other things:

A really bad square root finder


:: make a gate with one input
|=  [a=@]

:: a must be an atom
^-  @

:: a counter
=/  c  0

|-

?:  =((mul c c) a)
 c

$(c +(c))

Power of

:: make a gate with two inputs, b is the power
|=  [a=@ b=@]

:: a and b must be atoms
^-  @

:: loop
|-

:: exit if b is 1, produce current val of a
?:  =(b 1)
 a

$(a (mul a a), b (dec b))

isPrime (June 1 2018)


|=  [a=@]

:: produce a flag
^-  ?

:: set an incrementer
=/  i  2

:: loop
|-

:: if i equals a, the # is prime
?:  =(i a)
  &

:: if mod i divides into a evenly, the # is not prime
?:  =((mod a i) 0)
  |

:: recurse
$(i +(i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment