Created
January 22, 2013 20:08
-
-
Save Shou/4597959 to your computer and use it in GitHub Desktop.
filthy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# foldr applies the first argument, a function which takes two arguments, to | |
# the accumulator z, whose value changes on each for-loop iteration, and x, | |
# which is the current iteration's element of the xs list. | |
def foldr(f, z, xs): | |
for x in xs: z = f(z, x) | |
return z | |
# A version of foldr that takes no starting value, z, and instead uses the first | |
# argument in the list as the starting value. | |
# Raises an exception when an empty list is passed. | |
def foldr1(f, xs): | |
if len(xs) > 0: return foldr(f, xs[0], xs[1:]) | |
else: raise Exception("WHAT THE FUCK ARE YOU DOING YOU ARE INSANE") | |
# Function composition. | |
# Take two functions and return a function that takes one argument and applies | |
# the first function to the result of the second one. Both functions can only | |
# take one argument. | |
def compose(f, g): | |
return lambda x: f(g(x)) | |
# Compose on steroids. It can take an unlimited amount of arguments. | |
def co(*fs): | |
return foldr1(compose, fs) | |
# Function currying. | |
# Takes a function that takes two arguments and its first argument and returns | |
# a new function that takes its last argument. | |
def cu(f, x): | |
return lambda y: f(x, y) | |
def flip(f): return lambda x, y: f(y, x) | |
# Print and return some data. | |
def trace(x): | |
print x | |
return x | |
# Aliases for operators so we can pass them around | |
def plus(n, m): return n + m | |
def multiply(n, m): return n * m | |
def divide(n, m): return n / m | |
# crazy | |
def main(): | |
co(trace, cu(plus, "moro "), str, trace, int, trace, cu(flip(divide), 4.16), trace, cu(plus, 10), trace, cu(multiply, 55), trace)(8) | |
# magic | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
no use