Skip to content

Instantly share code, notes, and snippets.

@nbeirne
Last active November 28, 2024 22:58
Show Gist options
  • Select an option

  • Save nbeirne/f34c8c33f288e54b8859f17ca3c1d100 to your computer and use it in GitHub Desktop.

Select an option

Save nbeirne/f34c8c33f288e54b8859f17ca3c1d100 to your computer and use it in GitHub Desktop.
fizzbuzz_pretty.py
# define true and false values as function application. f(a,b): a is true, f(a,b): b is false
true = lambda a: lambda b: a
false = lambda a: lambda b: b
# define a number `n` as a function `f` applied n times. 0 == f is called no times
_0 = lambda f: lambda x: x
# given a number we can get the next one or previous one with function application
succ = lambda n: lambda f: lambda x: f(n(f)(x))
pred = lambda n: lambda f: lambda x: n(lambda g: lambda h: h(g(f)))(lambda u: x)(lambda u: u)
# define more numbers
_1=succ(_0)
_2=succ(_1)
_3=succ(_2)
_4=succ(_3)
_5=succ(_4)
# basic numberic operations
add = lambda a,b: lambda f: lambda x: a(f)(b(f)(x))
mult = lambda a,b: lambda f: lambda x: a(b(f))(x)
subtract = lambda a,b: b(pred)(a)
iszero = lambda n: n(lambda x: false)(true)
divides = lambda a,b: iszero(subtract(a(lambda n: iszero(subtract(b,n))(_1)(succ(n)))(_1),_1))
# define a function which takes a number (as previously defined), and returns a string (or int)
# values
v_add = lambda a: lambda b: a + b
toint = lambda n: (lambda x: subtract(n,_1)(v_add(x))(x))(1) # toint is kinda weird. To avoid having '0' its off-by-one, so we use 1 and subtract.
tochr = lambda n: chr(toint(n))
# these are the ascii conversions of a few characters required for printing
# 102 f
# 105 i
# 122 z
# 122 z
# 98 b
# 117 u
# 122 z
# 122 z
_100 = mult(mult(_5,_5),_4)
_98 = subtract(_100,_2)
_102 = add(_100,_2)
_105 = add(_100,_5)
_117 = subtract(add(_100,mult(_5,_4)),_3)
_122 = add(_117,_5)
# defining the strings
fizz = v_add(v_add(v_add(tochr(_102))(tochr(_105)))(tochr(_122)))(tochr(_122))
buzz = v_add(v_add(v_add(tochr(_98))(tochr(_117)))(tochr(_122)))(tochr(_122))
fizzbuzz = v_add(fizz)(buzz)
# takes a number, and chooses which string function to return
stringify = lambda n:\
divides(n,_3)\
(divides(n,_5)\
(fizzbuzz)\
(fizz))\
(divides(n,_5)\
(buzz)\
(toint(n)))
# this runs stringify 100 times, starting at 1
# It works by constructing a combinator (for_loop) which does two things:
# 1. gets the next number
# 2. runs some function on the current number.
for_loop = lambda f,i: (lambda a,b: a)(succ(i), f(i))
_100(lambda x: for_loop(lambda n: print(stringify(n)), x))(_1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment