Reputation: 83
How can I apply a function to two elements of a list. For example:
Given the list [red,star,blue,oval,orange,hexagon]
I want to apply the function to each pair functionName(red,star)
functionName(blue,oval)
functionName(orange,hexagon)
I'm guessing I would have to use recursion.
Upvotes: 2
Views: 946
Reputation: 499
Complementing Carsten's answer, sometimes in functional programming (or programming in general) you might want to divide the tasks you want to do into several subtasks. So here are 2 tasks:
For the first task, we can simply define a function pairing
that does the followings (and also assuming you want to ignore empty list or singleton list):
pairing :: [a] -> [(a,a)]
pairing [] = []
pairing [x] = []
pairing (x:y:xs) = (x,y) : pairing xs
For example:
pairing [] == []
pairing [1] == []
pairing [1,2,3,4] == [(1,2),(3,4)]
pairing [1,2,3,4,5] == [(1,2),(3,4)]
Then for task 2, there is an operation in Haskell that applies a function to a list of elements called map
(these functions that take a function as an argument are called higher-order functions):
For example:
f x = x^2
map f [0,1,2] == [0,1,4]
So we can now implement the function applyPairwise
like this:
applyPairwise :: ((a,a) -> b) -> [a] -> [b]
applyPairwise f xs = map f (pairing xs)
Or even better using composition:
applyPairwise f = map f . pairing
Upvotes: 1
Reputation: 52280
yes on way is to define a recursive function - what you need to think about (and what we don't know) is what should happen if the input list has uneven item-count? And of course how do you want to collect the results of that function?
Assuming you just ignore the last singe element in an uneven list and that you want to collect the results into another list:
applyPairwise :: (a -> a -> b) -> [a] -> [b]
applyPairwise f (a1 : a2 : rest) = f a1 a2 : applyPairwise f rest
applyPairwise _ _ = []
Example:
> applyPairwise (+) [1..5]
[3,7]
Upvotes: 2