Home > OS >  map function with previous and next list element in Haskell
map function with previous and next list element in Haskell

Time:10-28

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?

CodePudding user response:

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)]

CodePudding user response:

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).

  • Related