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)
答案 0 :(得分:3)
主要问题是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