Skip to content

Instantly share code, notes, and snippets.

@mgreenly
Last active June 3, 2020 01:57
Show Gist options
  • Save mgreenly/6c1b3b5a736a430b5bb6c3f765ab7376 to your computer and use it in GitHub Desktop.
Save mgreenly/6c1b3b5a736a430b5bb6c3f765ab7376 to your computer and use it in GitHub Desktop.
# The point is that only functions and function application are required to create all
# higher level language abstractions. You can use church encoding to turn functions
# into numbers, boolean values, logical operators, math operators, and in this case
# data structures.
fst = -> (a,_) { a } # no matter what 2 values are passed in return the 1st
snd = -> (_,b) { b } # no matter what 2 values are passed in return the snd
# a tuple is a function, that takes a function as an argument and applies it to the constant values of the tuple
tuple1 = ->(f){ f.('alpha', 'omega') }
tuple2 = ->(f){ f.('apple', 'orange') }
# to get a value out of a tuple you pass the function 'fst' or 'snd' to it.
puts tuple1.(fst) # -> alpha
puts tuple2.(snd) # -> orange
# you don't have to squint very hard to see the similarity typical oop code, tuple.fst or tuple.snd
# You can make a tuple constructor to simplify creating tuples
cons = -> (a,b) { ->(f){ f.(a, b) } }
# to use the constructor just pass it 2 values
tuple3 = cons.('fire', 'water')
# Just like before you use `fst` or `snd` to get values out.
puts tuple3.(fst)
puts tuple3.(snd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment