Haskell - Higher Order Functions

1
(a) any :: (a -> Bool) -> [a] -> Bool 

that tests whether a predicate is true for some element of a list; for example:

any odd [1..10] == True

(b) zipWith :: (a->b->c) -> [a] -> [b] -> [c] 

which combines the elements of two lists using a specific function; for example:

zipWith (+) [1,2,3,4,5] [10,20,30,40] == [11,22,33,44].
    
asked by anonymous 14.11.2017 / 00:18

1 answer

0

Here are alternatives for an implementation of the two functions.

myAny is a function that takes as arguments a predicate and a generic list and returns True / True if any of the elements respects the predicate.

The predicate is a a -> Bool function that returns True or False according to the variable passed as parameter. As examples it has odd, even, (2==), (>3) .

myAny:: (a -> Bool) -> [a] -> Bool
myAny f (x:xs) 
              | f x == True = True
              | otherwise = myAny f xs
myAny _ [] = False  

The _ [] = False case is trivial (empty list). When the list has elements, the idea is to iterate over each element until it reaches the end of the list or an element that respects the predicate.

myZipWith is a function that returns a list that results from the application of a function to elements of two lists, elements that occur in the same position.

myZipWith:: (a -> b -> c) -> [a] -> [b] -> [c]                  
myZipWith f (x:xs) (y:ys) = (f x y) : myZipWith f xs ys
myZipWith _ _ _ = []
    
29.11.2017 / 17:14