Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through two variable in Haskell

What is the haskell way to do this?

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:

 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:

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.

like image 568
pierrotlefou Avatar asked Aug 17 '09 05:08

pierrotlefou


2 Answers

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

[ (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]
]
like image 125
Don Stewart Avatar answered Nov 20 '22 04:11

Don Stewart


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

do 
  i <- [0 .. 999]
  j <- [0 .. 999]
  return (foo i j)
like image 14
Alexey Romanov Avatar answered Nov 20 '22 04:11

Alexey Romanov