【问题标题】:Haskell - Why is it not working? (IO Action wth Lists)Haskell - 为什么它不起作用? (带有列表的 IO 操作)
【发布时间】:2017-02-11 12:01:28
【问题描述】:
combinationIO :: Int -> [a] -> IO [[a]]
combinationIO 0 _ = return [[]]
combinationIO _ [] = return []
combinationIO n (x:xs) = do res <- (map (x:) (combinationIO (n-1) xs)) ++ (combinationIO n xs)
                          putStrLn $ (show n) ++ show " : (" ++ show (x,xs) ++ show ") = " ++ show res
                          return res

我在某个站点上看到了这个示例(如下),我想知道它是如何工作的,所以我在其中添加了一些 IO 操作。但是,ghci 给了我一个类型错误。有什么问题?

combination2 :: Int -> [a] -> [[a]]
combination2 0 _ = [[]]
combination2 _ [] = []
combination2 n (x:xs) = (map (x:) (combination2 (n-1) xs)) ++ (combination2 n xs)

【问题讨论】:

  • 错误是什么?
  • 如果你的代码确实和你放在这里的一样,那么你有一个缩进问题:putStrLnreturn 必须在res &lt;- 开始的位置精确缩进。

标签: list haskell io return monads


【解决方案1】:

主要问题是map++[a] 上工作,而不是IO [a]。我想你想要的是这样的:

combinationIO :: Show a => Int -> [a] -> IO [[a]]
combinationIO 0 _ = return [[]]
combinationIO _ [] = return []
combinationIO n (x:xs) = do
  res1 <- combinationIO (n-1) xs
  res2 <- combinationIO n xs
  let res = (map (x:) res1) ++ res2
  putStrLn $ (show n) ++ " : (" ++ (show (x,xs)) ++ ") = " ++ (show res)
  return res

【讨论】:

  • (\res1 res2 -&gt; map (x:) res1 ++ res2) &lt;$&gt; combinationIO (n-1) xs &lt;*&gt; combinationIO n xs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 2017-11-28
  • 2012-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多