Posted to tcl by Florentis at Sat Sep 26 18:17:13 GMT 2026view pretty

# Rework of a Tcl lib math polynomial proc
# the proc is in arithmetic syntax
# and use commands lmap, foreach, return

proc multPolyn_ari {polyn1 polyn2} {(

    [llength $polyn1] == 1 && [string is double -strict $polyn1] ? ( polyn1 = [polynomial $polyn1] ):;
    [llength $polyn2] == 1 && [string is double -strict $polyn2] ? ( polyn2 = [polynomial $polyn2] ):;

    [lindex $polyn1 0] != "POLYNOMIAL" || [lindex $polyn2 0] != "POLYNOMIAL"  ?
    [return -code error "Both arguments must be polynomials or a real number"] :;

    coeffs1 = [lindex $polyn1 1];
    coeffs2 = [lindex $polyn2 1];

    #
    # Take care of the null polynomial
    #
    $coeffs1 == {} || $coeffs2 == {} ? [ return [polynomial ""] ]:;

    zeros = lmap c $coeffs1 {(0.0)};
    
    new_coeffs = [lrepeat [( [llength $zeros]+[llength $coeffs2]-1 )] 0.0];

    idx = 0;
    foreach c $coeffs1 {(
        term_coeffs = lmap c2 $coeffs2 {($c*$c2)};
        term_coeffs = [lreplace $zeros $idx $idx {*}$term_coeffs];	
        sum_coeffs = lmap t $term_coeffs n $new_coeffs {($t+$n)};
        new_coeffs=$sum_coeffs;
        [incr idx];
    )};

    return [list POLYNOMIAL $new_coeffs];
)}