[Haskell-cafe] Replace list item with list.

Markus Läll markus.l2ll at gmail.com
Mon Nov 6 10:24:36 UTC 2017


Yeah, the question is so open that it's hard to answer. Was thinking
recommending to inline the desired list all together, but thought it too
impolite :).

But the `concatMap` is the simplest one (to replace all "z"s that is), and
if the OP is interested, then for lists >>= is defined as concatMap, so:

a = ["x", "y", "z"]
b = ["f", "g"]

f :: String -> [String]
f str = case str of
  "z" -> b
  _ -> [str]

answer = a >>= f

(Didn't run this through the compiler)


On Mon, Nov 6, 2017 at 12:20 AM, Richard A. O'Keefe <ok at cs.otago.ac.nz>
wrote:

>
>
> 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.
>
> _______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.
>



-- 
Markus Läll
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20171106/1856ab5f/attachment.html>


More information about the Haskell-Cafe mailing list