Manipulate list, one element at a time

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Manipulate list, one element at a time

Martin Drautzburg
Hello all,

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

type Each a = (a->a) -> [a] -> [[a]]

I came up with:

each :: Each a
each f []     = []
each f (x:xs) = (f x : xs) : (map (x:) $  each f xs)

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


but I wonder if there is a more standard way of doing this
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: Manipulate list, one element at a time

Frerich Raabe
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 - [hidden email]
www.froglogic.com - Multi-Platform GUI Testing
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners