Haskell 以递归方式正确编写exists函数

Haskell 以递归方式正确编写exists函数,haskell,recursion,Haskell,Recursion,如何修复此存在'函数,使其按要求工作 测试列表中的任何元素是否满足给定条件 exists' :: (a -> Bool) -> [a] -> Bool exists' p [] = False exists' p (x:xs) | p == x = True | otherwise = exists' p xs 只需在ward上的值上检查函数: exists' :: (a -> Bool) -> [a] -> Bool exists' _ []

如何修复此
存在'
函数,使其按要求工作

测试列表中的任何元素是否满足给定条件

exists' :: (a -> Bool) -> [a] -> Bool

exists' p [] = False
exists' p (x:xs)
   | p == x = True
   | otherwise = exists' p xs

只需在ward上的值上检查函数:

exists' :: (a -> Bool) -> [a] -> Bool
exists' _ [] = False
exists' f (x:xs)
   | f x       = True
   | otherwise = exists' f xs
f
的类型是
(a->bool)
x
的类型是
a
因此
f a
将返回bool,如果它的计算结果为True,那么您也只需“返回”True,否则您将按原样进行递归调用

正如他在回答中所说的,问题是你写的是
p==x
而不是
px
,因此,你不是调用列表头上的谓词,而是检查谓词是否等于列表头。因此,
x
的类型也应该是
a->Bool
(或者
p
的类型是
a
),并且
p
x
的类型应该由
Eq
类的实例决定

您可以使代码更加优雅,如:

exists' :: (a -> Bool) -> [a] -> Bool
exists' _ [] = False
exists' p (x:xs) = p x || exists' p xs

请注意,您不必自己编写
exists'
。这里有一个语义等价的
any::Foldable t=>(a->Bool)->ta->Bool
函数。

谢谢。帮了大忙!
exists' :: (a -> Bool) -> [a] -> Bool
exists' p = helper
    where helper [] = False
          helper (x:xs) = p x || helper xs