Haskell - Higher Order Functions

Asked

Viewed 155 times

1

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

that test 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 gets; for example:

zipWith (+) [1,2,3,4,5] [10,20,30,40] == [11,22,33,44].
  • Please state your question better.

1 answer

1

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 function a -> Bool that returns True or False according to the variable passed as parameter. As examples you have odd, even, (2==), (>3).

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

The case _ [] = False is trivial (empty list). When the list has elements, the idea is to iterate over each of the elements until reaching 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 the elements of two lists, elements that occur at the same position.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.