Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think the problem is that you need to know the arity of each function, in order to assign the arguments of the "combined" function accordingly.</p> <p>Maybe you can wrap your functions in a class, something like this:</p> <pre><code>class Function: def __init__ (self, arity, f): self.arity = arity self.f = f def __call__ (self, *args): return self.f (*args) def __add__ (self, g): if not isinstance (g, Function): raise Exception ('Here be dragons') def fg (*args): return self.f (*args [:self.arity] ) + g.f (*args [self.arity:] ) return Function (self.arity + g.arity, fg) a = Function (4, lambda x1, x2, x3, x4: (x1 * x2) + (x3 * x4) ) b = Function (2, lambda x1, x2: x1 / x2) print (a (1, 2, 3, 4) ) print (b (10, 20) ) c = a + b print (c (1, 2, 3, 4, 10, 20) ) </code></pre> <hr> <p>Some words on inspection of the arity. The resulting function <code>fg</code> has only one argument, namely <code>*x</code> and its inspected arity will result in 0, hence prohibiting adding already added functions. Take a look here:</p> <pre><code>#Using my original class a = Function (2, lambda x1, x2: x1 * x2) b = Function (2, lambda x1, x2: x1 / x2) c = a + a print (c (1, 2, 3, 4) ) #prints 14 c = c + b print (c (1, 2, 3, 4, 5, 6) ) #prints 14.833333333333334 </code></pre> <p>Now if we use inspection like this (please correct me if you intended another use of it):</p> <pre><code>import inspect class InspectedFunction: def __init__ (self, f): self.f = f def __call__ (self, *args): return self.f (*args) def __add__ (self, g): if not isinstance (g, InspectedFunction): raise Exception ('Here be dragons') arity = len (inspect.getargspec (self.f).args) def fg (*args): return self.f (*args [:arity] ) + g.f (*args [arity:] ) return InspectedFunction (fg) a = InspectedFunction (lambda x1, x2: x1 * x2) b = InspectedFunction (lambda x1, x2: x1 / x2) c = a + a print (c (1, 2, 3, 4) ) #prints 14 c = c + b print (c (1, 2, 3, 4, 5, 6) ) #inspected arity of c is 0 </code></pre> <p>will do this:</p> <pre><code>Traceback (most recent call last): File "nomimporta.py", line 45, in &lt;module&gt; print (c (1, 2, 3, 4, 5, 6) ) File "nomimporta.py", line 30, in __call__ return self.f (*args) File "nomimporta.py", line 37, in fg return self.f (*args [:arity] ) + g.f (*args [arity:] ) File "nomimporta.py", line 37, in fg return self.f (*args [:arity] ) + g.f (*args [arity:] ) TypeError: &lt;lambda&gt;() takes exactly 2 arguments (0 given) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload