I have an exercise in Python as follows:
a polynomial is given as a tuple of coefficients such that the powers are determined by the indexes, e.g.: (9,7,5) means 9 + 7*x + 5*x^2
write a function to compute its value for given x
Since I am into functional programming lately, I wrote
def evaluate1(poly, x):
coeff = 0
power = 1
return reduce(lambda accu,pair : accu + pair[coeff] * x**pair[power],
map(lambda x,y:(x,y), poly, range(len(poly))),
0)
which I deem unreadable, so I wrote
def evaluate2(poly, x):
power = 0
result = 1
return reduce(lambda accu,coeff : (accu[power]+1, accu[result] + coeff * x**accu[power]),
poly,
(0,0)
)[result]
which is at least as unreadable, so I wrote
def evaluate3(poly, x):
return poly[0]+x*evaluate(poly[1:],x) if len(poly)>0 else 0
which might be less efficient (edit: I was wrong!) since it uses many multiplications instead of exponentiation, in principle, I do not care about measurements here (edit: How silly of me! Measuring would have pointed out my misconception!) and still not as readable (arguably) as the iterative solution:
def evaluate4(poly, x):
result = 0
for i in range(0,len(poly)):
result += poly[i] * x**i
return result
Is there a pure-functional solution as readable as the imperative and close to it in efficiency?
Admittedly, a representation change would help, but this was given by the exercise.
Can be Haskell or Lisp aswell, not just Python.
for
loops, for example) is a bad goal to aim for in Python. Re-binding variables judiciously and not mutating objects gives you almost all of the benefits and makes the code infinitely more readable. Since number objects are immutable and it only rebinds two local names, your "imperative" solution better realizes functional programming virtues than any "strictly pure" Python code.lambda
, compared to languages with a lighter anonymous syntax function. Part of that probably contributes to the "unclean" appearance.