函数式编程 - 用于递增计数器的简单 for 循环

Functional Programming - Simple For Loop For Incrementing Counter

本文关键字:计数器 简单 for 循环 编程 用于 函数      更新时间:2023-09-26

我们在函数式编程中不使用for loop,而是使用map,filter,reduce等higher order functions。这些非常适合遍历数组。

但是,我想知道如何做一个简单的计数器循环。

let i = 0;
for( i; i < 10; i++) {
  console.log( "functional programming is a religion")
};

那么,在函数式编程中如何做到这一点呢?

不要使用"while"或"for"来控制命令式编程而不是功能编程的流。

Array(10).fill("functional programming is not a religion")
.map((msg) => {
  console.log(msg);
  return msg;
});

一种函数式方法是编写一个 HOF,该 HOF 创建一个调用底层函数 n 次的函数:

function repeatTimes(fn, n) {
  return function() {
    while (n--) fn(...arguments);
  };
}

现在,您将按如下方式调用函数:

function myFunc() { console.log("functional programming is a religion"); }
const tentimes = repeatTimes(myFunc, 10);
tentimes();

可以通过概括继续重复调用的条件来扩展此方法。我们将传递一个函数来决定何时停止,而不是固定的数字 n。我们将向该函数传递迭代计数:

function repeatWhile(fn, cond) {
  return function() {
    var count = 0;
    while (cond(count++)) fn(...arguments);
  };
}

现在我们称之为

const tentimes = repeatWhile(myFunc, i => i < 10);
tentimes();
我们

可以通过创建条件函数的函数进一步简化它,我们称之为lessThan

function lessThan(n) { return i => i < n; }

现在调用可以写成

const tentimes = repeatWhile(myFunc, lessThan(10));
tentimes();

那么,在函数式编程中如何做到这一点呢?

它实际上并没有做太多事情,您仍然可以通过一些解决方法使用forEach

Array.apply(null, Array(5)).forEach(function(){
 console.log( "funtional programming is a religion")
});

5 是要迭代的次数。

重点是使大部分代码可测试。对于您的示例,我想最好的方法是在不打印的情况下创建文本。

function unFold(fnStopPredicate, fnTerm, fnGenerate, aSeed) {
    var arr = [];
    while( ! fnStopPredicate(aSeed) ){
        arr.push(fnTerm(aSeed));
        aSeed = fnGenerate(aSeed);
    }
    return arr;
}

你可能会说这不起作用,这是真的,但它有一个功能接口。它不会改变它的参数,返回的值始终是它初始参数的直接结果。

var strValues = unFold(x => x > 10,
                       x => "functional programming is a religion",
                       x => x+1,
                       0).join("'n");
// Real side effect goes here
console.log(strValues);

这里的要点是,只要您提供的功能本身不产生副作用,您就可以对 unFold 的使用进行单元测试。

为什么不为数字构建一个高阶函数

Number.prototype.repeat = function (fn) {
    var i,
    n = Math.abs(Math.floor(this)) || 0;
    for (i = 0; i < n; i++) fn(i, this);
};
(10).repeat(function (i, n) { document.write(i + ' of ' + n + ': your claim<br>'); });
(NaN).repeat(function (i, n) { document.write(i + ' of ' + n + ': your claim<br>'); });

您还可以

使用 some()every() 来中断或继续您的功能循环。像这个例子一样,我使用 some() 继续return falsereturn true中断。

Array(10).fill("message").some((msg,index) => {
            
    //like continue loop
    if(index === 5) return false 
    //like break loop
    if(index === 9) return true
    console.log(msg, index)
})

这个怎么样?

/*forLoop takes 4 parameters
 1: val: starting value.
 2: condition: This is an anonymous function. It is passed the current value.
 3: incr: This is also an anonymous function. It is passed the current value.
 4: loopingCode: Code to execute at each iteration. It is passed the current value.
*/
var forLoop = function(val, condition, incr, loopingCode){
  var loop = function(val, condition, incr){
    if(condition(val)){
        loopingCode(val);
        loop(incr(val), condition, incr);
    }
  };
  loop(val, condition, incr);
}

然后按如下方式调用循环:

    forLoop(0, 
      function(x){return x<10},
      function(x){return ++x;}, 
      function(x){console.log("functional programming is a religion")}
      );

输出:函数式编程是一种宗教

函数式编程是一种宗教

函数式编程是一种宗教

函数式编程是一种宗教

函数式编程是一种宗教

函数式编程是一种宗教

函数式编程是一种宗教

函数式编程是一种宗教

函数式编程是一种宗教

函数式编程是一种宗教

请让我知道你对这个答案的看法。

此函数调用回调 Fn 计数次数。

const times = (count, callbackFn) => {
   if (count === 0) {return}
   callbackFn();
   times(count-1, callbackFn);
}
times(10, () => console.log("Functional Programming is a Religion"));

此函数的工作方式类似于 for 循环

const forLoop = (initialValues, conditionFn, newValsFn, bodyFn) => {
   if (!conditionFn(initialValues)) {return}
   bodyFn(initialValues);
   forLoop(newValsFn(initialValues), conditionFn, newValsFn, bodyFn);
}
forLoop({i: 0}, ({i}) => i < 10, ({i}) => ({i: i+1}), ({i}) => {
   console.log(i, "Functional Programming is a Religion.");
});

在这里,上述函数用于打印斐波那契级数的前n

const forLoop = (initialValues, conditionFn, newValsFn, bodyFn) => {
   if (!conditionFn(initialValues)) {return}
   bodyFn(initialValues);
   forLoop(newValsFn(initialValues), conditionFn, newValsFn, bodyFn);
}
const fibPrint = (n) => {
   let n1 = 0, n2 = 1, nextTerm;
    
   forLoop({i: 1}, ({i}) => i <= n, ({i}) => ({i: i+1}), () => {
      console.log(n1);
      nextTerm = n1 + n2;
      n1 = n2;
      n2 = nextTerm;
   });
}
fibPrint(10);

迭代次数非常大时,在函数中调用相同的函数需要大量的模因。 进一步的 CPU 时间也会增加。 英特尔和ARM等公司会喜欢这种方法,因为他们正在煽动软件公司推出资源匮乏计划

无论如何,现在我们正处于人工智能时代,需要猛犸象来解决问题,我认为这不会成为问题。我正在教微处理器和微控制器,可能我的担心是由于这个。努尔

使用简单的递归函数

function counter(value) {
    var i = value;
    if(i<10){
        console.log( "functional programming is a religion");
    }else{
        return;
    }
        counter(++i);    
}
  counter(0);