2016-10-03 74 views
-1
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给我一个类型错误。问题是什么?Haskell - 为什么它不起作用? (列表中的IO动作)

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

什么是错误? – chepner

+0

如果你的代码的确如你所说的那样,那么你就有一个缩进问题:'putStrLn'和'return'必须在'res <-'开始的级别缩进。 – Tarmil

回答

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 
+0

或'(\ res1 res2 - > map(x :) res1 ++ res2)<$> combinationIO(n-1)xs <*> combinationIO n xs'。 – dfeuer

相关问题