I'm presenting some aspects of functional programming to my students. We are using python as our main language. To me, composing functions is one of the main aspects of functional programming. To illustrate this i proposed the following example, nothing but classic.
import dis
def f(x):
return 2*x+1
def g(x):
return x**2
def comp(fun1, fun2):
return lambda x:fun1(fun2(x))
dis.dis(f)
dis.dis(g)
dis.dis(comp(f,g))
I was just wondering, is there a way to get back the expression for comp(f,g)
with the dis
module. I understood there are parameters to tune the level of recursive calls sommehow, but I did not spend enough time exploring. I also came across the ast
module which looked a bit tedious at first glance.
So I thought this was a question for Stackoverflow : way before any idea of symbolic calculcation, is there a way to get dis
describe comp(f,g)
being lambda x:2*x**2+1
or ast
displaying the abstract syntax tree for this expression ?
Thank's for any advice.
As far as I am aware, what you want isn't possible just through typical usage of the ast
or dis
packages. This is because as far as the AST or bytecode of the comp
is concerned, the implementation of the functions to be called are irreverent, it just need to know to load functions that are being referenced and call them.
If you're willing to dig a little deeper, you could simulate substituting calls for their implementation just to model the function composition if you're willing to sacrifice accuracy of how the execution actually works by building and manipulating the AST, replacing the calls within comp
with the implementations of the function they're calling.
I put together a small example of the kind of thing you'd have to do here https://gist.github.com/buckley-w-david/e9c67cca7070282ddb5ab8d37de06f4e (Requires python 3.9+, and has a lot of assumptions on the structure of the program it's supposed to work on baked in), but it's a little opaque if you're not familiar with working with ASTs in Python.