I find your example code far less readable than just writing out the loops
in the appropriate functions, especially for matrix_multiply.
On Mon Feb 10 2014 at 10:51:35 AM, Alex Rodrigues
Over the last few days I've been considering a lot of what we talked about regarding Python scoping and inline functions. Today I found a further use case for inline functions (one which is a fair bit harder to replicate using standard techniques). I was working on writing a basic linear algebra calculator for school and one of the annoying things about doing it is that every time you want to do an element-wise operation on the matrix (which is a list of lists) you have to nest what is essentially one line of code inside a pair of for loops. Below I've done three basic linear algebra functions which are written as if there was a builtin "inline()" which transformed a standard function into an inline function and also assuming that python had more powerful lambdas. I feel that these represent a good use case, because the inline function serves to make the code both shorter and clearer.
import copy
@inline def element_wise(func): func = inline(func) for i, row in enumerate(matrix): result.append([0]*len(row)) for j, el in enumerate(row): func()
def is_symmetric(matrix): element_wise(lambda: if matrix[i][j] != matrix[j][i]: return False) return True
def matrix_add(matrix, matrix2): result = copy.deepcopy(matrix) element_wise(lambda: result[i][j] = matrix[i][j] + matrix2[i][j]) return result
def matrix_multiply(matrix, matrix2): result = copy.deepcopy(matrix) element_wise(lambda: result[i][j] = sum([a*b for a,b in zip(matrix[i], [r[j] for r in matrix2])])) return result _______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/