[Haskell-beginners] Manipulate list, one element at a time

Frerich Raabe raabe at froglogic.com
Tue Oct 24 10:59:57 UTC 2017


On 2017-10-24 12:18, martin wrote:
> How can I do something to each element of a list, but only modify one 
> element at at time, so the result is a list of
> lists, where each sublist is the original list with one element altered.
> 
> Something like

[..]

> λ> each (*10) [1..3]
> [[10,2,3],[1,20,3],[1,2,30]]

You could make use of the 'inits' and 'tails' functions from Data.List:

λ: inits [1..3]
[[],[1],[1,2],[1,2,3]]
λ: tails [1..3]
[[1,2,3],[2,3],[3],[]]

Using this, you could build a little list comprehension which takes every 
head and every tail and produces a list in which the two are concatenated, 
except that the first element of the tail has some function applied to it:

λ: let each f xs = [i ++ f t:ts | (i, t:ts) <- zip (inits xs) (tails xs)]
λ: :t each
each :: (a -> a) -> [a] -> [[a]]
λ: each (*10) [1..3]
[[10,2,3],[1,20,3],[1,2,30]]

-- 
Frerich Raabe - raabe at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing


More information about the Beginners mailing list