#!/usr/bin/python3 def compose(g, f): """ Create a function g of f which when called will be the same result as calling g(f(x)). Args: g - function or callable f - function or callable Returns: function of the same arguments as f """ return lambda *args: g(f(*args)) def difference(a, b): """ Returns a - b Args: a - number b - number Returns: number """ return a - b def curry_left(f, *args): """ Takes a function and a variable argument list and returns a function like f but with len(args) arguments already applied. To facilitate calling built-ins, f is not inspected, and curry_left has no knowledge of the definition of f, it merely returns a callable. Args: f - function to curry left *args - variable list of arguments to partially apply from left to right """ def curried(*more_args): arglist = args + more_args return f(*arglist) return curried if __name__ == "__main__": # Base 2 formatting for numbers as_binary = "{:b}".format # Print the result of subtracting two numbers in base 2 binary_diff = compose(as_binary, difference) print ("Base 2: 32 - 24 = {:s}, 96 - 79 = {:s}".format(binary_diff(32, 24), binary_diff(96, 79))) # Partially apply difference from the left forty_two_minus = curry_left(difference, 42) print ("Curried difference(42, ...): 42 - 7 = {:d}, 42 - 11 = {:d}".format(forty_two_minus(7), forty_two_minus(11))) # Curried composition with_forty_two_minus = curry_left(compose, forty_two_minus) print ("with_forty_two_minus: f(17, 5) = {:s}".format(as_binary(with_forty_two_minus(sum)(divmod(17, 5)))))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question