[Haskell-cafe] Replace list item with list.
Richard A. O'Keefe
ok at cs.otago.ac.nz
Sun Nov 5 23:20:43 UTC 2017
On 4/11/17 11:48 PM, mirone wrote:
> Hello everyone!
> If I have a list A : ["x", "y", "z"]
> and a list B: ["f", "g"].
> Here is my question:
> What's the simplest way to replace "z" in the list A by list B, and get
> ["x", "y", "f", "g"] ?
f _ _ = ["x","y","f","g"]
That's a joke, but it really isn't clear what the question means.
One possibility is
f a b = init a ++ b
f [1,2,3,4,5] [9,8,7] => [1,2,3,4,9,8,7]
If you mean that you want to replace "z" by ... wherever it occurs,
something like
-- (f needle straws haystack) replaces each occurrence of needle as
-- an element of haystack with the elements of straws.
f :: Eq t => t -> [t] -> ([t] -> [t])
f needle straws =
concatMap (\straw -> if straw == needle then straws else [straw])
f "z" ["f","g"] ["x","z","y","z"] => ["x","f","g","y","f","g"]
Your question admits of too many generalisations for us to be really
helpful.
More information about the Haskell-Cafe
mailing list