[Haskell-beginners] short function to remove and replace an item

Vlad Skvortsov vss at 73rus.com
Wed Apr 1 21:01:55 EDT 2009

Prelude> let replaceItem p n = map (\x -> if p x then n else x)
Prelude> replaceItem odd 100 [1..10]

Michael P Mossey wrote:
> What if I have a list xs, and I want to remove one item and replace it 
> with another? The item to remove can be detected by a predicate 
> function. The order of the items doesn't matter. How about this:
> replaceItem :: (a -> Bool) -> a -> [a] -> [a]
> replaceItem p new xs = new : snd (partition p xs)
> This will actually replace all items that match the predicate with one 
> copy of 'new'. It will also prepend 'new' even if no items match the 
> predicate.
> For another challenge, can someone explain to me how to write this in 
> point-free style?

Vlad Skvortsov, vss at 73rus.com, http://vss.73rus.com

More information about the Beginners mailing list