ben*_*wad 3 search haskell list
我在这里有一个函数,用于查看元组列表,并通过获取第一个值来查找元组中的第二个值.这是迄今为止的功能:
lookup :: String -> [(String,String)] -> String
lookup _ _ [] = "Not found"
lookup x y zs = if (notFound x zs)
then "Not found"
else (head [b | (a,b) <- zs, (a==x)])
Run Code Online (Sandbox Code Playgroud)
如果没有包含给定第一个字符串的元组,则notFound函数只返回一个Bool为true.问题是,我在Hugs中遇到这种类型的错误:
ERROR "find.hs" (line 22): Type error in explicitly typed binding
*** Term : lookup
*** Type : String -> [(String,String)] -> [a] -> String
*** Does not match : String -> [(String,String)] -> String
Run Code Online (Sandbox Code Playgroud)
我认为它与虚拟的"未找到"值有关,它与生成列表中的字符串具有不同的类型,但我不确定.
我认为你的显式类型声明是错误的.你有:
lookup :: String -> [(String,String)] -> String
Run Code Online (Sandbox Code Playgroud)
但我认为应该是
lookup :: String -> String -> [(String,String)] -> String
Run Code Online (Sandbox Code Playgroud)
实际上,在再看一遍之后,看起来你没有使用第二个参数"y".所以你可以删除它和下划线
lookup :: String -> [(String,String)] -> String
lookup _ [] = "Not found"
lookup x zs = if (notFound x zs)
then "Not found"
else (head [b | (a,b) <- zs, (a==x)])
Run Code Online (Sandbox Code Playgroud)
这将允许您保留您拥有的类型声明.
那么,你知道Haskell Prelude已经有一个"查找"功能来查找关联列表中的条目吗?这里是类型签名(它更通用,接受实例Eq的任何键类型):
lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
Run Code Online (Sandbox Code Playgroud)
所以你的功能将完成类似下面的事情
myLookup x zs = Maybe.fromMaybe "Not found" $ lookup x zs
Run Code Online (Sandbox Code Playgroud)