2012-10-17 27 views
2

我得到一個文件的內容,並將其轉換爲形式的列表:使用IO列表查找?

[("abc", 123), ("def", 456)] 

與READFILE,線條和文字。

現在,我可以設法將結果列表轉換爲類型IO [(String,Int)]

我的問題是,當我試圖做這樣的功能:

check x = lookup x theMap 

我得到這個錯誤,我也不太清楚如何解決:

Couldn't match expected type `[(a0, b0)]' 
      with actual type `IO [(String, Int)]' 
In the second argument of `lookup', namely `theMap' 

theMap是實際上這樣的:

getLines :: String -> IO [String] 
getLines = liftM lines . readFile 

tuplify [x,y] = (x, read y :: Int) 

theMap = do 
    list <- getLines "./test.txt" 
    let l = map tuplify (map words list) 
    return l 

和文件內容爲:

abc 123 
def 456 

任何人都可以解釋我做錯了什麼和或給我一個更好的解決方案?幾小時前我剛剛開始與monads玩耍,並且一路上遇到了一些顛簸。

感謝

回答

4

你會從IO到 「解包」 theMap。請注意如何你已經這樣做是爲了getLines

do 
    list <- getlines 
    [...] 
    return (some computation on list) 

所以你可以有:

check x = do 
    m <- theMap 
    return . lookup x $ m 

這是,事實上,反模式(雖然是示意性一,),你會使用函子實例更好,即。 check x = fmap (lookup x) theMap

+0

謝謝!我應該注意到這個:( – noko