[英]Haskell isMember function error
isMember:: a -> [a] -> Bool
isMember y [] = False
isMember y (x:xs) =
if y == x then
True
else
isMember y xs
Trying to create a function that will identify whether something is a member of a list. 尝试创建一个函数来识别某些东西是否是列表的成员。 For example:
例如:
isMember 6 [1,2,3,4,5,6]
>True
However I keep getting a complier error stating 'no instance for (Eq a) arising from the use of '==' 但是我一直得到一个编译器错误,声明'因使用'=='而导致的(Eq a)没有实例
Help would be appreciated (I'm new to Haskell & Recursion in functional languages so explain like I'm five.) 帮助将不胜感激(我是函数语言中的Haskell和Recursion的新手,所以解释为我五岁。)
you are almost there 你快到了
isMember :: Eq a => a -> [a] -> Bool
isMember _ [] = False
isMember y (x:xs) =
if y == x then True else isMember y xs
What the compiler tells you that you promised to accept any type of list members - but later you use the function ==
which is not available for all types (for example functions). 编译器告诉您,您承诺接受任何类型的列表成员 - 但稍后您使用函数
==
,它不适用于所有类型(例如函数)。
By adding Eq a =>
you say I accept all input which have an equals method. 通过添加
Eq a =>
您说我接受所有具有等于方法的输入。
You can (re)write the last line as 您可以(重新)将最后一行写为
isMember y (x:xs) = (y == x) || isMember y xs
which is equivalent to your implementation (thanks @chi for the comment). 这相当于你的实现(感谢@chi的评论)。 What is nice about your version is that it is tail recursive.
你的版本有什么好处,它是尾递归的。
Another point to note - the pattern: 另一点需要注意 - 模式:
isMember _ [] = False
) isMember _ [] = False
) isMember y (x:xs) = ...
) isMember y (x:xs) = ...
) happens to turn up a lot and has been abstracted into the family of fold
-functions ( foldl
, foldr
...). 碰巧出现了很多,并被抽象为
fold
-functions系列( foldl
, foldr
......)。 Putting it in your use case it looks like 把它放在你的用例中就好了
isMember y xs = foldl False (\x b -> (x == y) || b) xs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.