如果某个变量小于某个阈值,那么当实现在while循环的每次迭代中检查的算法时,它会发生很多.
在命令式语言中,它看起来像:
while ( x < TRESHOLD ) {
x = usefullStuff();
}
Run Code Online (Sandbox Code Playgroud)
当然有用的东西以某种方式影响x ......
如何将此构造转换为利用函数式编程范例的haskell?
虽然我不知道你的程序是做什么的,但我觉得你会想要以不同的方式构建你的逻辑.有关一些想法,请参阅文章为什么功能编程问题的第4 部分.它涉及类似的情况,涉及使用牛顿方法找到方程的根.在那里划分责任,以便循环逻辑与逐次逼近的生成分离.
如果usefulStuff是monad - 即具有副作用的函数,你将不得不使用这样的东西:
whileLoop x
| x < THRESHOLD = return x
| otherwise = do x <- usefulStuff
whileLoop x
Run Code Online (Sandbox Code Playgroud)
来自Control.Monad.Loops:
iterateWhile :: Monad m => (a -> Bool) -> m a -> m a
iterateWhile p x = do
y <- x
if p y
then iterateWhile p x
else return y
Run Code Online (Sandbox Code Playgroud)
然后,假设有用的lStuff有副作用:
iterateWhile (< threshold) usefullStuff
Run Code Online (Sandbox Code Playgroud)