简体   繁体   English

Haskell-递归检查关联列表的元素

[英]Haskell- recursively check elements of associative list

Say I have the following associative list: 说我有以下关联列表:

names = [(6548712, "Charlie Brown"), (27378912, "Linux Van Pelt"), (5831457, "Peppermint Patty")]

I want to check if a given tuple, such as... 我想检查给定的元组,例如...

 (6548712, "Charlie Brown")

...exists within the associative list. ...存在于关联列表中。

Here is my function: 这是我的功能:

check :: (String,a) -> [(String,a)] -> Bool
check val (x:xs)
    | x == val = True
    | otherwise = check val xs

The function does not work. 该功能不起作用。 I think the error lies in my first guard, since I do believe my recursive call is correct. 我认为错误在于我的第一个警卫,因为我确实相信我的递归调用是正确的。 I want to be able to do this using recursion, can someone help me out? 我希望能够使用递归来做到这一点,有人可以帮助我吗?

  1. Your data has Number and String but your function reads String and Number. 您的数据具有数字和字符串,但是您的函数读取字符串和数字。 So that has to be changed to this 因此必须更改为此

     check :: (Int, String) -> [(Int, String)] -> Bool 
  2. Your recursion should have a base condition, like this 您的递归应该有一个基本条件,像这样

     check val [] = False 

    It means that if the list is empty (all elements are checked), return False . 这意味着如果列表为空(检查所有元素),则返回False

So your function should look like this 所以你的功能应该像这样

check :: (Int, String) -> [(Int, String)] -> Bool

check val [] = False
check val (x:xs)
    | x == val = True
    | otherwise = check val xs

Online Demo 在线演示


As it is, you can make your function Polymorphic by doing 就这样,您可以通过以下方式使函数变为多态

check :: Eq a => (a, String) -> [(a, String)] -> Bool

To know more about Eq a , please check this excellent answer 要了解有关Eq a更多信息,请检查此出色的答案


Just for the sake of completion, you can always use elem function, like this 只是为了完整起见,您总是可以使用elem函数,像这样

Prelude> elem (6548712, "Charlie Brown") [(6548712, "Charlie Brown"), (27378912, "Linux Van Pelt"), (5831457, "Peppermint Patty")]
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM