簡體   English   中英

GHC IO編譯錯誤

[英]GHC IO compilation error

我在GHC 6.12.3上編譯以下代碼時遇到問題,我不明白為什么。

函數test2的目的是返回一個使用整數從列表中獲取字符串元素的函數(該列表是從成對列表的第一個節點創建的)。

IO位是必需的,因為test2被另一個使用IO的功能所使用。

type PairList = [(String, String)]

test1 :: [String] -> Int -> String
test1 list x = list !! x

test2 :: PairList -> IO (Int -> String)
test2 pl = do
    f <- [fst x | x <- pl] :: IO [String]
    return test1 f

GHC給我這個錯誤:

Test.hs:8:6:
    Couln't match expected type 'IO [String]'
        against inferred type '[a]'
    In a stmt of a 'do' expression:
        f <- [fst x | x <- pl] :: IO [String]
    In the expression:
        do { f <- [fst x | x <- pl] :: IO [String];
            return test1 f }
            ...

編輯:
如果您想直接執行此操作(在計算test2需要額外的IO),則可以執行以下操作

test2 :: PairList -> IO (Int -> String)
test2 pl = do
     putStrLn "Hi Mum!"
     return (test1 [fst x | x <- pl])

您的原始代碼不起作用,因為當您執行f <- [...] ,您正在使用列表單子,就好像它是IO單子一樣。

僅作為示例,您可以這樣使用:

myactions = do
   putStrLn "Please enter a list of (String,String) pairs:"
   pl <- readLn -- which you'd have to write, or derive Read and use readLn
   f <- test2 pl
   putStrLn "please enter a number:"
   n <- readLn
   putStrLn $ f n

這會給你類似的行為

*Main> myactions
Please enter a list of (String,String) pairs:
[("hi","yes"),("oops","bye")]
Hi Mum!
please enter a number:
1
oops

原始答案:

我認為您不需要IO位:

type PairList = [(String, String)]

test1 :: [String] -> Int -> String
test1 list x = list !! x

test2pure :: PairList -> (Int -> String)
test2pure pl = test1 [fst x | x <- pl] 

這樣可以編譯良好,並給出如下結果

test2pure [("a String","ignored"), ("Another String","bye!")] 0
"a String"

如果要在IO中使用它,可以這樣使用:

myactions = do
   pl <- readLn
   let chosen = test2pure pl 3
   putStrLn ("3: " ++ chosen)

或者你可以寫

test2IO :: PairList -> Int -> IO String
test2IO pl n = return (test2pure pl n)

如果您確實想使用IO ()作為返回類型,則可以修復如下編譯錯誤:

test2 pl = return $ test1 [fst x | x <- pl]

正如AndrewC在回答中所說的那樣,您可能不需要此功能的monad。

暫無
暫無

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

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