2016-10-03 73 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

相關問題