【问题标题】:loop through two variable in Haskell遍历 Haskell 中的两个变量
【发布时间】:2010-11-20 03:43:50
【问题描述】:

haskell 方法是什么?

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

更多背景: 我正在解决 euler problem 27 ,我得到了:

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

下一步是通过遍历所有可能的a和b来得到一个元组列表,然后进行以下处理:

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

但我不知道如何遍历两个变量..谢谢。

【问题讨论】:

    标签: loops haskell recursion tail-recursion


    【解决方案1】:

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

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

    或布局以使嵌套更清晰:

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

    【讨论】:

    • 这个单一的答案让我的haskell小脑袋里有很多东西点击了,谢谢
    【解决方案2】:

    除了 dons 的回答,您还可以使用 list monad:

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

    【讨论】:

      【解决方案3】:

      您也可以使用 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
      

      示例运行:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-24
        • 1970-01-01
        • 2022-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 2010-11-17
        相关资源
        最近更新 更多