Haskell获取项目在列表中的位置

时间:2018-08-10 14:16:08

标签: string list haskell

我才刚刚开始学习Haskell,我对此确实有很多疑问。在我正在做的教程中,我需要开发一个功能,从列表和特定的String中,您将在列表中找到String的位置。在网上搜索时,我找到了此代码,但我真的不明白,有人可以向我解释。

TEST_F

2 个答案:

答案 0 :(得分:7)

lookUp :: [String] -> String -> Int
lookUp [] s = error "..."  -- An empty list does not contain _anything_, in
                           -- particular not the string you're looking for.
lookUp (x:xs) s     -- We've eliminated the empty case, which guarantees there's
                    -- at least one (head) element in the list if we get here.
                    -- Let's examine it!
   | not (x == s) -- If the element isn't the one we were looking for...
       = 1 + (lookUp xs s)   -- then we need to continue the search, i.e. search
                             -- through the _remaining_ elements `xs` and, if `s` is
                             -- found there, report a one higher position (because
                             -- we've already skipped one element).
   | otherwise  -- Else, the element _is_ the one we were looking for...
       = 0   -- IOW, it occurs at position 0 of the (part of) the list we're
             -- currently examining.

再加上几句话:

  • 正如Willem Van Onsem所说,error在这里是一个坏主意:在现实情况下,列表中不包含您要查找的元素,即,这不仅仅是一个“哎呀,流星罢工打破了银行的债权人”之类的东西,但是您应该期待实际的风险。但是error将默认使整个程序崩溃。相反,您应该返回一个Maybe Int,它使您可以通过呼叫者可以轻松处理的方式来表示失败。

    lookUp :: [String] -> String -> Maybe Int
    lookUp [] _ = Nothing
    lookUp (x:xs) s | not(x == s)  = fmap (1 +) (lookUp xs s)
                    | otherwise    = Just 0
    
  • 此函数中的所有内容实际上都不需要列表中的字符串。它与整数,单个字符,布尔值等同样适用。任何允许相等比较的东西。因此,您最好进行签名

    lookUp :: Eq a => [a] -> a -> Maybe Int
    

答案 1 :(得分:1)

lookUp :: [String] -> String -> Int

函数lookUp接受String和返回Int的String的列表

lookUp [] s = error "String no encontrado"

如果第一个参数为空字符串,则返回error ...

lookUp (x:xs) s | not(x == s) = 1 + (lookUp xs s)
                | otherwise = 0

有趣的部分(x:xs)从列表中获取第一个字符串,然后是字符串 |是守卫的,因此如果x中的字符串不等于s字符串return 1 + ( lookup xs s) .. ==>递归调用lookUpxs-不带比较字符串x和字符串s作为参数的字符串列表

最后othervise返回0

手动:

lookUp [] "foo" ==>第一个模式[],因此返回错误

lookUp ["foo"] "foo" ==>第二个模式并运行后卫==> not( "foo" == "foo") = 1 + ( lookUp [] "foo"),该命令以第二行othervise 0结尾,因此它返回正确的位置0

lookUp [ "bar", "foa", "foo", "fao" ] "foo" ==>第二种模式,并扩展为:not ( "bar" == "foo") return 1 + (lookUp ["foa", "foo", "fao"] "foo")然后not( "bar" == "foo") return 1 + (not ("foa" == "foo") = return 1 + (lookUp ["foo", "fao"] "foo"))然后not(“ bar” ==“ foo”)返回1 +(not(“ foa” = =“ foo”)=返回1 +(not(“ foo” ==“ foo”)=返回1).. but because now test is *True* uses othervise = 0 so 1 + 1 = 2 and 2`是列表中正确的字符串位置。

最后一种可能性:

lookUp ["bar"] "foo" ==> not("bar" == "foo") = return 1 + (lookUp [] "foo")lookUp空列表会引发错误