Record a function using recursion functions or higher order

How to write a function that takes a predicate fand a list xx, and reutrns true, if fxtrue for some x∈xs?

For instance:

 ghci>exists (>2) [1,2,3]
     True

This is the function I wrote:

 exists :: (t->Bool)->[t]->Bool
    exists f a []=error
    exists f a (x:xs)
                |if x∈f a  =True
                |otherwise= x:f a xs

I know this is wrong, but I do not know why. Do I need to write this predicate function first f, and then use it inside the function exists. Because I really don’t know how to compare one element of a list xswith a function.

+3
source share
5 answers

If we consider your definition,

exists :: (t -> Bool) -> [t] -> Bool
exists f a []=error
exists f a (x:xs)
            |if x∈f a  =True
            |otherwise= x:f a xs

We see your type

exists :: (t -> Bool) -> [t] -> Bool

, exists , (t -> Bool) [t]. a Bool. .

:

exists f a [] = error

. f [] , a . , :

exists f [] = error

error . , . , exists (<2) []. True False? , - x in [], f x?

exists f a (x:xs)
      |if x∈f a  =True
      |otherwise= x:f a xs

, a , . a, . , if , :

exists f (x:xs)
      | x∈f    = True
      | otherwise = x:f xs

x∈f , f x . , f x true. , , . , , - lo n 'behold, x !

, . otherwise , f x True. , x , .

x : f xs . : , , - - Bool. , . , x , , .

, , , . - xs , exists .

, , - . , : " exists, Bool?".

+6

ghci>exists (>2) [1,2,3]
True

. Google. (< ------ Haskell imho)

( "" ), . - (a -> Bool), - [a]. : Bool

Hoogling, , (a -> Bool) -> [a] -> Bool, any, all find. , any - , "".

find, Maybe a, . Nothing, False, True.

, any p = or . map p.

- , , . map? Hoogle . , , . map or, map.

map _ []     = []
map f (x:xs) = f x : map f xs

. recursiveCall f (x:xs) = f x : recursiveCall f xs map, filter foldl/foldr, . (Stop. Hoogle time. , .)

+15

, , , - any:

Prelude> :t any
any :: (a -> Bool) -> [a] -> Bool
Prelude> any (<3) [1, 2, 3, 4]
True
Prelude> any (<3) [3, 4, 5, 6]
False

, , , , :

any p xs = or (map p xs)

map , [Bool], or, , - True, , , :

Prelude> any (<3) [1, 2..]
True
+4

. , :

exists :: (t -> Bool) -> [t] -> Bool
exists _ [] = False
exists f (x:xs)
            | f x = True
            | otherwise = exists f xs
+2

x f f x, f x if. otherwise Bool: exists .

0
source

Source: https://habr.com/ru/post/1787344/


All Articles