Fopa Léon Constantin
Fopa Léon Constantin

Reputation: 12373

how to modify the i-th element of a Haskell List?

I'm looking for a way to modify the i-th element of haskell List. let says foobar is such a function, then the following works.

let xs = ["a","b","c","d"]
foobar xs 2 "baba" -- xs = ["a","b","baba","d"]

thanks for any reply!

Upvotes: 1

Views: 354

Answers (4)

Olathe
Olathe

Reputation: 1895

A simple function to do it directly:

replaceAt _ _ []     = []
replaceAt 0 x (_:ys) = x:ys
replaceAt n x (y:ys) = y:replaceAt (n - 1) x ys

Upvotes: 2

Landei
Landei

Reputation: 54584

change n x = zipWith (\k e -> if k == n then x else e) [0..]

Upvotes: 2

ffriend
ffriend

Reputation: 28552

let xs = ["a","b","c","d"]
take 2 xs ++ ["baba"] ++ drop 3 xs

Upvotes: 3

leftaroundabout
leftaroundabout

Reputation: 120751

You can do it with splitAt:

Prelude> let xs = ["a","b","c","d"]
Prelude> (\(l,_:r)->l++"baba":r) $ splitAt 2 xs
["a","b","baba","d"]

Upvotes: 4

Related Questions