如何迭代直到Clojure中的一个固定点? [英] How do I iterate until a fixed point in Clojure?

查看:185
本文介绍了如何迭代直到Clojure中的一个固定点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常处于我的代码如下所示的位置:

I'm frequently in the position that my code reads like so:

(iterate improve x)

我正在寻找第一个不再比以前更好的价值。 过滤器 take-while 都不适用于一个明显的解决方案。但是,我犹豫要写出来:

And I'm looking for the first value that no longer is an improvement over the previous. Neither filter nor take-while lend themselves to an obvious solution. However, I'm hesitant to write out:

(loop [current x
       next (improve x)]
  (if (= current next)
    current
    (recur next (improve next))))

或:

(let [improvements (iterate improve x)]
  (->> (map vector improvements (rest improvements))
    (filter (partial apply =))
    (ffirst)))

因为在某些时候这变得重复了,定点迭代肯定是一项基本任务,某些地方必须有某种类型的库支持,对吗?

Because at some point this is becoming repetitive and surely fixed point iteration is such a basic task that there must be some kind of library support somewhere, right?

推荐答案

您可以使用 reduce 减少必要时停止。 减少将参数包装在特殊对象中,其中 reduce 旨在查找并停止处理,立即返回包装的值。

You can use reduce and reduced to stop when necessary. reduced wraps the argument in a special object, which reduce is designed to look for and stop processing immediately returning the wrapped value.

(def vals (iterate improve x))

(reduce #(if (= %1 %2) (reduced %1) %2) vals)

这篇关于如何迭代直到Clojure中的一个固定点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆