buydadip
buydadip

Reputation: 9437

Haskell-a function that applies a function on a list

I am trying to create a function that accepts a function as parameter, and applies that function on every pair of elements in a list. For example, if I call my function foldPairs, then I would use it as so:

foldPairs (+) [1..10]

[3,7,11,15,19]

I tried using foldl in my attempt...

foldPairs :: (a->a->a) -> [a] -> [a]
foldPairs func lis = foldl func lis

However this clearly does not work. I think I might have to use curried and uncurried but I am not quite sure how. Could someone help me out?

Upvotes: 0

Views: 119

Answers (2)

bheklilr
bheklilr

Reputation: 54078

The solution I would go with is to turn [1..10] into [[1,2],[3,4],[5,6],[7,8],[9,10]], then filter out any lists of length 1, convert to tuples, then map your function:

chunks :: Int -> [a] -> [[a]]
chunks n = reverse . go []
    where
        go acc [] = acc
        go acc xs =
            let (h, t) = splitAt n xs
            in go (h:acc) t

Then simply

foldpairs :: (a -> a -> b) -> [a] -> [b]
foldpairs f
    = map (uncurry f)
    . map (\[x, y] -> (x, y))
    . filter ((== 2) . length)
    . chunks 2

Upvotes: 0

Eugene Sh.
Eugene Sh.

Reputation: 18381

Assuming, that for an odd-numbered input list we just discard the last element, the following will do the required:

foldPairs :: (a->a->a) -> [a] -> [a]
foldPairs _ [] = []
foldPairs _ [_] = []
foldPairs f (x:y:xs) = f x y : foldPairs f xs

Upvotes: 2

Related Questions