2016-10-03 3 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는 나에게 유형 오류를줍니다. 문제가 무엇입니까?하스켈 - 왜 작동하지 않습니까? (IO 작업 wth 목록)

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

가장 큰 문제는 [a]map++ 작업하지 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) <$> 조합 IO (n-1) xs <*> 조합 IO n xs'. – dfeuer