在 Haskell 中循环时 [英] While in a loop in Haskell
问题描述
如何在 Haskell 中编写以下伪代码?
How to code the following pseudo-code in Haskell?
x=0
for (i from 0 to 100):
j=0
while ( f(i,j) >0 ):
x+= f(i,j)
j+=1
(f
一些不重要的函数.)
(f
some unimportant function.)
我想出了这样的事情:
a= [x| i<-[0..100], let s = takeWhile (k-> (f i k > 0)) [0..],
j<- s, let x = f i j ]
然后 Sum a
完成工作,但我需要计算 f i j
两次,这有点多余.
Then Sum a
does the work, but I need to compute f i j
two times which is a little bit redundant.
这是否可以通过 f
只计算一次或一些运行速度更快的更好的代码来完成?
Can this be done with f
computed only once or some better codes that run faster?
推荐答案
这里有一种方法,每对只计算一次 f
:
Here's a way that only computes f
once for each pair:
inner i = sum $ takeWhile (> 0) $ map (f i) [0..]
x= sum $ map inner [0..100]
我不喜欢列表推导式,尤其是对于更复杂的表达式,所以我发现您的解决方案难以阅读.主要区别在于,不是存储 j
的列表,使得 f i j >0
,我存储了实际的函数值.由于懒惰,这不再起作用.
I dislike list comprehensions, especially for more complex expressions, so I found your solution difficult to read. The primary difference is that instead of storing a list of j
s such that f i j > 0
, I stored the actual function value. This does no more work due to laziness.
这篇关于在 Haskell 中循环时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!