While in a loop in Haskell

前端 未结 2 1012
臣服心动
臣服心动 2021-01-28 20:11

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

(<

2条回答
  •  自闭症患者
    2021-01-28 21:11

    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]
    

    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 js such that f i j > 0, I stored the actual function value. This does no more work due to laziness.

提交回复
热议问题