【问题标题】:Loop until... with Ramda循环直到...与 Ramda
【发布时间】:2018-09-07 15:17:02
【问题描述】:

我试图使用 Ramda 重构几段代码,我想知道,在 Ramda/函数式编程中解决以下代码的好方法是什么:

let arrayOfSomething = initArray();

for(let i = 0; SOME_INDEX_CONDITION(i)|| SOME_CONDITION(arrayOfSomething); i++) {
    const value = operation(arrayOfSomething);
    const nextValue = anotherOperation(value);

   arrayOfSomething = clone(nextValue)
}

所以基本上我想在 arrayOfSomething 上迭代并应用相同的管道/操作组合,直到满足其中一个条件。将最后一个值 (nextValue) 作为对 forLoop 组合的反馈,这一点很重要。

【问题讨论】:

  • 100 在这里代表什么?
  • 100 || SOME_CONDITION(arrayOfSomething) 中没有除 100 以外的其他值,并且从不评估默认值。
  • @ScottSauyet 好吧,100 只是 forLoop 的退出条件,因此它将遍历循环 100 次或直到满足依赖于 arrayOfSomething 的 SOME_CONDITION
  • @NinaScholz 该代码的算法与任何值无关,我将对其进行编辑,因此 100 不代表任何值。

标签: javascript functional-programming ramda.js


【解决方案1】:

我不知道这是否符合您的要求,但 Ramda 的 until 可能是您需要的:

const operation = ({val, ctr}) => ({val: val % 2 ? (3 * val + 1) : (val / 2), ctr: ctr + 1})

const indexCondition = ({ctr}) => ctr > 100
const valCondition = ({val}) =>  val === 1
const condition = R.either(indexCondition, valCondition)

const check = R.until(condition, operation)

const collatz = n => check({ctr: 0, val: n})

console.log(collatz(12)) 
// 12 -> 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 //=> {"ctr": 9, "val": 1}
console.log(collatz(5)) 
// 5 -> 16 -> 8 -> 4 -> 2 -> 1 //=> {"ctr": 5, "val": 1}
console.log(collatz(27)) 
//27 -> 82 -> 41 -> 124 -> 62 -> .... //=> {"ctr": 101, "val": 160}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

【讨论】:

  • 啊,真丢脸,我发现 2014 年的一个问题 (github.com/ramda/ramda/issues/564) 有点被驳回,但我实际上并没有两次检查文档。谢谢
  • collatz的漂亮编码
  • @naomik:谢谢。我不会经常拿出那个答案!
【解决方案2】:

您似乎正在寻找一个反向折叠,或unfold

大多数人都熟悉reduce:它接受一组值并将其减少为单个值 - unfold 则相反:它接受一个值并展开 它是一个值的集合

如果库中已经存在类似的函数,其他更熟悉 Ramda 的人可以发表评论

const unfold = (f, init) =>
  f ( (x, next) => [ x, ...unfold (f, next) ]
    , () => []
    , init
    )

const nextLetter = c =>
  String.fromCharCode (c.charCodeAt (0) + 1)

const alphabet =
  unfold
    ( (next, done, c) =>
        c > 'z'
          ? done ()
          : next (c, nextLetter (c))
    , 'a'
    )

console.log (alphabet)
// [ a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z ]

unfold 很强大

const fib = (n = 0) =>
  unfold
    ( (next, done, [ n, a, b ]) =>
        n < 0
          ? done ()
          : next (a, [ n - 1, b, a + b ])
    , [ n, 0, 1 ]
    )

console.log (fib (20))
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765 ]

我们可以使用unfold 实现您的iterateUntil

const unfold = (f, init) =>
  f ( (x, acc) => [ x, ...unfold (f, acc) ]
    , () => []
    , init
    )
    
const iterateUntil = (f, init) =>
  unfold
    ( (next, done, [ arr, i ]) =>
        i >= arr.length || f (arr [i], i, arr)
          ? done ()
          : next (arr [i], [ arr, i + 1 ])
    , [ init, 0 ]
    )
  
const data =
  [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]
  
console.log (iterateUntil ((x, i) => i > 3, data))
// [ 'a', 'b', 'c', 'd' ]

console.log (iterateUntil ((x, i) => x === 'd', data))
// [ 'a', 'b', 'c', 'd' ]

我们可以使用asyncawait 轻松支持异步。下面我们使用asyncUnfold 执行从单个节点ID 0 开始的递归数据库查找

  • db.getChildren 接受节点 id 并仅返回该节点的立即子节点

  • traverse 接受节点 id 并递归获取所有后代子节点(深度优先顺序)

const asyncUnfold = async (f, init) =>
  f ( async (x, acc) => [ x, ...await asyncUnfold (f, acc) ]
    , async () => []
    , init
    )

// demo async function
const Db =
  { getChildren : (id) =>
      new Promise (r => setTimeout (r, 100, data [id] || []))
  }

const Empty =
  Symbol ()

const traverse = (id) =>
  asyncUnfold
    ( async (next, done, [ id = Empty, ...rest ]) =>
        id === Empty
          ? done ()
          : next (id, [ ...await Db.getChildren (id), ...rest ])
    , [ id ]
    )
    
const data =
  { 0 : [ 1, 2, 3 ]
  , 1 : [ 11, 12, 13 ]
  , 2 : [ 21, 22, 23 ]
  , 3 : [ 31, 32, 33 ]
  , 11 : [ 111, 112, 113 ]
  , 33 : [ 333 ]
  , 333 : [ 3333 ]
  }

traverse (0) .then (console.log, console.error)
// => Promise
// ~2 seconds later
// [ 0, 1, 11, 111, 112, 113, 12, 13, 2, 21, 22, 23, 3, 31, 32, 33, 333, 3333 ]

其他适合unfold的程序

  • “以页面URL/开始,爬取所有后代页面”
  • “从搜索"foo"和页面1开始,收集所有页面的结果”
  • “从用户Alice开始,显示她的朋友,以及她所有朋友的朋友”

【讨论】:

  • 我虽然关于展开,但在这种情况下它太强大了,而且比 R.until 更难理解,正如另一个答案中所建议的那样。无论如何+1纯JS方法!我会保证它的安全,并且将来可能会对我有所帮助
  • Ramda 确实有一个unfold,但它确实需要一些工作。这是一个很好的答案!
猜你喜欢
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多