[Haskell-cafe] Replace list item with list.

Richard A. O'Keefe ok at cs.otago.ac.nz
Sun Nov 5 23:36:12 UTC 2017



On 6/11/17 12:20 PM, Richard A. O'Keefe 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"] ?
> Your question admits of too many generalisations for us to be really
> helpful.

Here are some questions that might help.

Let's suppose for the sake of argument that you want a
function
   f needle straws {-B-} haystack {-A-}
such that
   f "z" ["f","g"] ["x","y","z"] => ["x","y","f","g"]

What should f n s h do when n does not occur in h?
What should f n s h do when n is the first element of h?
What should f n s h do when n occurs more than once in h?
What should f n s h do when n occurs in s?
What should f n s h do when h has 0, 1, 2, 4 or more elements?
May f assume that h is in sorted order?
May f use compare at all?
May f use ==?
What if we want to match more than one element; should we be
looking for an *element* equal to "z" or a *prefix* equal to ["z"]
in this case but possibly longer in others?

With different answers to these questions, you might get

f' :: Eq t => [t] -> [t] -> [t] -> [t]
f' needles straws haystack
    | needles `isPrefixOf` haystack =
      straws ++ (length needles `drop` haystack)
f' needles straws [] = []
f' needles straws (item:items) =
      item : f' needles straws items

f' ["z"] ["f","g"] ["x","y","z","z"] => ["x","y","f","g","z"]


More information about the Haskell-Cafe mailing list