Mathjs 自定义求和函数



我正在尝试实现我自己的自定义求和函数。目标是有一个名为"sumFromTo"的函数,它接受 4 个参数* 迭代器名称*从*自*功能

其中"函数"可以是其他函数,解决方案是将所有函数相加。例如

// works 
  sumFromTo(i,1,10,i+1)  // = 65

但是如果我把它包装到另一个函数中,它会破坏,因为mathjs不知道"x"

// works not because x is undefined
test(x) = sumFromTo(i,1,x,i+1) 
test(10)

我的导入如下所示:

function sumFromTo(iteratorName, from, to, toString, f) {
    var total = 0;
    var toVal = typeof to == "number" ? to : to.length;
    for (var iterator = from; iterator <= toVal; iterator++) {
        mathScope[iteratorName] = iterator;
        mathScope[toString + "_" + iterator] = to[iterator];
        total += math.eval(f, mathScope);
    }
    return total;
}
sumFromTo.transform = function (args, math, scope) {
    /*   Iterator    */
    var iteratorName = "notfound";
    if (args[0] instanceof math.expression.node.SymbolNode) {
        iteratorName = args[0].name;
    } else {
        throw new Error('First argument must be a symbol');
    }
    /*    Startvalue of Iterator    */
    if (args[1] instanceof math.expression.node.ConstantNode) {
        if (args[1].value == 0) {
            throw new Error('Sum must counting from >=1: 0 given');
        }
    }
    /*    to: Array to loop    */
    if (args[2] instanceof math.expression.node.SymbolNode) {
        var toString = args[2].name;
    }
    /*    compile    */
    var from = args[1].compile().eval(scope);
    scope[iteratorName] = from;
    var to = args[2].compile().eval(scope);
    if (to.constructor.name == "Matrix") {
        to = to.toArray();
        scope[toString] = to;
    }else{
        if(typeof to == "object"){
            to = to.toArray();
        }
    }
    return sumFromTo(iteratorName, from, to, toString, args[3].toString());
};
sumFromTo.transform.rawArgs = true;
math.import({sumFromTo: sumFromTo}, {override: true});

我创建了一个小提琴 https://jsfiddle.net/o49p4zwa/2/,也许这有助于理解我的问题。

有人知道我错过了什么或我做错了什么吗?

提前感谢!!

你需要的是闭包

test = function(x) {
    sumFromTo(i,1,x,i+1) 
}
test(10)

最新更新