2012-10-17 31 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