【问题标题】:Haskell: looking up the second value of a tuple in a list based on the first valueHaskell:根据第一个值在列表中查找元组的第二个值
【发布时间】:2010-10-23 08:09:06
【问题描述】:

我在这里有一个函数,用于查看元组列表并通过获取第一个值来查找元组中的第二个值。到目前为止的功能如下:

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)])

如果没有包含给定第一个字符串的元组,notFound 函数只会返回一个 Bool 作为真。问题是,我在 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

我认为这与虚拟“未找到”值与生成列表中的字符串具有不同类型有关,但我不确定。

【问题讨论】:

    标签: list search haskell


    【解决方案1】:

    我认为您的明确类型声明是错误的。你有:

    lookup :: String -> [(String,String)] -> String
    

    但我认为应该是

    lookup :: String -> String -> [(String,String)] -> String
    

    实际上,再看一遍后,您似乎没有使用第二个参数“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)])
    

    这将允许您保留您拥有的类型声明。

    【讨论】:

      【解决方案2】:

      顺便说一句,你知道 Haskell Prelude 已经有一个“查找”功能来查找关联列表中的条目吗?这是类型签名(它更通用,接受任何实例 Eq 的密钥类型):

      lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
      

      所以你的函数会完成类似下面的事情

      myLookup x zs = Maybe.fromMaybe "Not found" $ lookup x zs
      

      【讨论】:

        【解决方案3】:

        乍一看,似乎应该删除第二个参数('y' 和第二个下划线)?声明lookup 接受两个参数,而不是三个。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-22
          • 1970-01-01
          相关资源
          最近更新 更多