1

我正在尝试实现我自己的自定义求和函数。目标是有一个名为“sumFromTo”的函数,它接受 4 个参数 * iteratorname * from * to * function

其中“函数”可以是其他一些函数,解决方案是求和。例如

// 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/,也许它有助于理解我的问题。

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

提前致谢!!

4

1 回答 1

0

你需要的是关闭

test = function(x) {
    sumFromTo(i,1,x,i+1) 
}
test(10)
于 2017-02-02T21:30:50.727 回答