Richard Suchenwirth 2004-02-27 - Reading Numerical array operations, I began to dream of simple yet generic code that allows (four species) arithmetics on whole lists / matrices / trees, in a way similar to expr, and simpler than my own takes in A matrix gadget and Playing APL.
Well, Tcl is the language in which my dreams come true most easily, so here it is -it takes two operands and an expr operator in between, all separated by whitespace. Each of the operands may be scalar (a single number), or a list (at any nesting); but if both operands are lists, they must have the same length (recursively down).
proc lexpr {a op b} {
set res {}
set la [llength $a]
set lb [llength $b]
if {$la == 1 && $lb == 1} {
set res [expr $a $op $b]
} elseif {$la==1} {
foreach j $b {lappend res [lexpr $a $op $j]}
} elseif {$lb==1} {
foreach i $a {lappend res [lexpr $i $op $b]}
} elseif {$la == $lb} {
foreach i $a j $b {lappend res [lexpr $i $op $j]}
} else {error "list length mismatch $la/$lb"}
set res
}#--- Testing:
% lexpr {{1 2} {3 4}} * 2
{2 4} {6 8}
% lexpr {{1 2} {3 4}} + 0.1
{1.1 2.1} {3.1 4.1}
% lexpr {{1 2} {3 4}} * {{10 100} {1 0}}
{10 200} {3 0}
% lexpr {1 2 3} + {10 20 30}
11 22 33
% lexpr {1 2 3} * {4 5 6 7}
error: list length mismatch 3/4See also
AMB - 2025-05-25 02:31:04
I have been working on a Tcl package for working with vectors, matrices and higher-dimensional tensors. It is called ndlist, and it provides the command "nexpr", which is similar to "lexpr". To demonstrate, here are the lexpr examples, but with the nexpr command:
package require -exact ndlist 0.11
namespace import ndlist::nexpr
set x {{1 2} {3 4}}
set y {{10 100} {1 0}}
nexpr {@x * 2}; # {2 4} {6 8}
nexpr {@x + 0.1}; # {1.1 2.1} {3.1 4.1}
nexpr {@x * @y}; # {10 200} {3 0}
set a {1 2 3}
set b {4 5 6 7}
nexpr {@a * @b}; # error: incompatible dimensions