簡體   English   中英

Haskell-為什么不起作用? (列出的IO操作)

[英]Haskell - Why is it not working? (IO Action wth Lists)

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)

主要問題是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM