循环遍历Haskell中的两个变量

时间:2022-09-04 17:03:59

What is the haskell way to do this?

haskell的方法是什么?

for (int i = 0 ; i < 1000 ; i++)
      for (int j = 0 ; j < 1000 ; j++)
              ret =  foo(i , j )           #I need the return value.

More background: I am solving euler problem 27 , and I have got:

更多背景:我正在解决欧拉问题27,我得到了:

 value a  b =
     let l = length $ takeWhile (isPrime) $ map (\n->n^2 + a * n + b) [0..]
     in (l, a ,b)

The next step is to get a list of tuple by looping through all the possible a and b and then do the following processing:

下一步是通过循环遍历所有可能的a和b来获取元组列表,然后执行以下处理:

foldl (\(max,v) (n,a,b)-> if n > max then (n , a * b) else (max ,v) ) (0,0) tuple_list

but I have no idea how to loop through two variables ..Thanks.

但我不知道如何循环两个变量..谢谢。

3 个解决方案

#1


24  

Use a nested list comprehension. Here 'foo' is '(,)'':

使用嵌套列表推导。这里'foo'是'(,)'':

[ (i,j) | i <- [0 .. 999], j <- [0 .. 999] ]

Or laid out to make the nesting clearer:

或者布置以使嵌套更清晰:

[ foo i j
| i <- [0 .. 999]
, j <- [0 .. 999]
]

#2


14  

As well as dons' answer, you can use the list monad:

除了dons的答案,你可以使用list monad:

do 
  i <- [0 .. 999]
  j <- [0 .. 999]
  return (foo i j)

#3


8  

You can also do this nicely using Control.Applicative

您也可以使用Control.Applicative很好地完成此操作

module Main where

import Control.Applicative

main :: IO ()
main = mapM_ putStrLn (foo <$> [0..3] <*> [0..3])

foo :: Int -> Int -> String
foo a b = "foo " ++ show a ++ " " ++ show b

Example run:

示例运行:

C:\programming>ghc --make Main.hs
[1 of 1] Compiling Main             ( Main.hs, Main.o )
Linking Main.exe ...

C:\programming>main
foo 0 0
foo 0 1
foo 0 2
foo 0 3
foo 1 0
foo 1 1
foo 1 2
foo 1 3
foo 2 0
foo 2 1
foo 2 2
foo 2 3
foo 3 0
foo 3 1
foo 3 2
foo 3 3

#1


24  

Use a nested list comprehension. Here 'foo' is '(,)'':

使用嵌套列表推导。这里'foo'是'(,)'':

[ (i,j) | i <- [0 .. 999], j <- [0 .. 999] ]

Or laid out to make the nesting clearer:

或者布置以使嵌套更清晰:

[ foo i j
| i <- [0 .. 999]
, j <- [0 .. 999]
]

#2


14  

As well as dons' answer, you can use the list monad:

除了dons的答案,你可以使用list monad:

do 
  i <- [0 .. 999]
  j <- [0 .. 999]
  return (foo i j)

#3


8  

You can also do this nicely using Control.Applicative

您也可以使用Control.Applicative很好地完成此操作

module Main where

import Control.Applicative

main :: IO ()
main = mapM_ putStrLn (foo <$> [0..3] <*> [0..3])

foo :: Int -> Int -> String
foo a b = "foo " ++ show a ++ " " ++ show b

Example run:

示例运行:

C:\programming>ghc --make Main.hs
[1 of 1] Compiling Main             ( Main.hs, Main.o )
Linking Main.exe ...

C:\programming>main
foo 0 0
foo 0 1
foo 0 2
foo 0 3
foo 1 0
foo 1 1
foo 1 2
foo 1 3
foo 2 0
foo 2 1
foo 2 2
foo 2 3
foo 3 0
foo 3 1
foo 3 2
foo 3 3