满足条件时如何摆脱迭代循环? [英] How to get out of iterate loop when a condition is met?
本文介绍了满足条件时如何摆脱迭代循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用 iterate
遍历函数 g
.当我运行代码时,循环将无限运行.满足条件时是否有可能脱离循环?
I want to iterate over a function g
with iterate
. When I run my code the loop runs infinitely. Is there any possibility to get out of the loop when a condition is met?
类似于 if g x>100,然后停止
.
我的代码:
f x = iterate g x
g x = 2 * x
推荐答案
是的,您可以使用 takeWhile(不是.p)
来实现,等同于
Yes, you either use takeWhile (not . p)
for that, equivalent to
foldr (\x r -> if (not (p x)) then (x:r) else []) []
或者有时以下有用,
takeUntil p = foldr (\x r -> if (not (p x)) then (x:r) else [x]) []
如果您也想在序列中包含最后一个元素.
if you want to include the last element into the sequence, as well.
在您的情况下,您将编写 takeWhile(不是.(> 100)).迭代(* 2)
或 takeUntil(> 100).重复(* 2)
.
In your case, you'd write takeWhile (not . (> 100)) . iterate (*2)
, or takeUntil (> 100) . iterate (*2)
.
(不是.(> 100))
当然与(< = 100)
相同.
这篇关于满足条件时如何摆脱迭代循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文