Joe
Joe

Reputation: 343

map function with previous and next list element in Haskell

I have a list e.g. [1,2,3,4,5] where I need to know not only the current element but also the predecessor and successor elements. Is there any map function which can be used as follows:

map (\prev cur next -> ...) [1,2,3,4,5]

Or maybe you have another idea to solve the problem?

Upvotes: 1

Views: 169

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

You can use tails and then process each three items:

import Data.List(tails)

[ … | (x₀ : x₁ : x₂ : _) <- tails [1, 2, 3, 4, 5] ]

for example:

import Data.List(tails)

[ (x₀, x₁, x₂) | (x₀ : x₁ : x₂ : _) <- tails [1, 2, 3, 4, 5] ]

Here the (x₀, x₁, x₂) parameters will thus work with (1, 2, 3), (2, 3, 4) and (3, 4, 5).

Upvotes: 4

Iceland_jack
Iceland_jack

Reputation: 7014

You can zip the lists together and drop one element of each

>> as = [1..5]
>> zipWith3 (\prev cur next -> (prev, cur, next)) as (drop 1 as) (drop 2 as)
[(1,2,3),(2,3,4),(3,4,5)]

Upvotes: 4

Related Questions