Last active
February 23, 2018 20:01
-
-
Save nicksspirit/aabae4591472be8d199c7a6833e6e457 to your computer and use it in GitHub Desktop.
Create a compose function similar to rambda.js's compose function
This file contains hidden or 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
from functools import reduce, partial | |
import random | |
import math | |
def calcMean(iterable): | |
return sum(iterable) / len(iterable) | |
def formatMean(mean): | |
return round(float(mean), 2) | |
def adder(val, value): | |
return val + value | |
def multiplier(val, value): | |
return val * value | |
def isEven(val): | |
return val % 2 == 0 | |
def compose(*fargs): | |
if not all(callable(f) for f in fargs): | |
raise TypeError("Function is not callable") | |
def inner(arg): | |
return reduce(lambda arg, func: func(arg), fargs, arg) | |
return inner | |
if __name__ == '__main__': | |
# Ex1 | |
rand_range = [random.randint(0, 10000) for x in range(0, 10000)] | |
isRandIntEven = compose(calcMean, formatMean, | |
partial(adder, value=0), math.floor.__call__, isEven) | |
print(isRandIntEven(rand_range)) | |
# Ex2 | |
classyGreeting = lambda firstName, lastName: "The name's " + \ | |
lastName + ", " + firstName + " " + lastName | |
yellGreeting = compose(partial( | |
classyGreeting, "James".upper()), str.upper.__call__) | |
print(yellGreeting("Bond")) | |
# Ex3 | |
print(compose(partial(multiplier, value=2), | |
partial(adder, value=1), | |
math.fabs)(-4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment