Skip to content

Instantly share code, notes, and snippets.

@ryohey
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save ryohey/7af153db7f51f2a8f1f7 to your computer and use it in GitHub Desktop.

Select an option

Save ryohey/7af153db7f51f2a8f1f7 to your computer and use it in GitHub Desktop.
next = (value) -> "🐱"+value
back = (value) -> value.slice("🐱".length, value.length)
zero = "🐶"
# next = (value) -> [value]
# back = (value) -> value.pop()
# next = (value) -> -> value
# back = (value) -> value()
# Calculation
add = (n, m) ->
return n if m is zero
return add next(n), back(m)
sub = (n, m) ->
return n if m is zero
return sub back(n), back(m)
mul = (n, m) ->
_mul = (a, b, x) ->
return a if x is zero
return _mul add(a, b), b, back(x)
_mul n, n, back(m)
# zero の次を真、 zero を偽とする
equals = (n, m) ->
return next(zero) if n is zero and m is zero
return zero if n is zero or m is zero
return equals back(n), back(m)
# Reversible
add2 = (n, m) -> [add(n, m), m]
sub2 = (n, m) -> [sub(n, m), m]
# Number Helper
int = (num) ->
return zero if num is 0
return next int(num - 1)
toInt = (n) ->
m = 0
while true
break if n is zero
n = back n
m++
m
console.log toInt zero # 0
console.log toInt next zero # 1
console.log toInt back next zero # 0
# Test Calculation
console.log toInt add(int(1), int(2)) # 3
console.log toInt sub(int(3), int(2)) # 1
console.log toInt mul(int(9), int(2)) # 18
# Reversible Add
[a, b] = [int(4), int(3)]
console.log toInt(a), toInt(b)
[a, b] = add2 a, b
console.log toInt(a), toInt(b) # 7, 3
[a, b] = sub2 a, b
console.log toInt(a), toInt(b) # 4, 3
# Compare
console.log equals int(1), int(1) # true
console.log equals int(11), int(1) # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment