迭代两个列表进行替换

时间:2015-09-19 02:24:56

标签: haskell

我需要创建一个带两个参数的函数。它们都是字符串列表,一个用作另一个的替换列表。所以函数会像这样被调用 -

subs ["the","quick","brown","the"] ["a","dog"] 

输出将是 - “快速的棕色狗”。因此,只要列表中存在“the”元素,第一个“the”将替换为替换列表的第一个元素,第二个“the”将替换为变电站列表中的第二个元素。我可以使用foldr迭代第一个列表,但我不知道如何跟踪替换列表,以便不再使用已经使用的元素。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

我是否理解subs仅替换输入词列表中"the"的出现?所以:

subs xs ["a", "dog"]

表示将"the"xs的第一次出现替换为"a",将第二次出现"dog"替换为<{1}}?

如果是这样,你应该尝试以下几点:

subs xs [] = ...  -- no more substitutions - the easy case

subs xs (a:as) =
  -- we have a substitution
  -- if xs begins with "the" then substitute with `a` and continue
  -- otherwise ... some sort of recursion ...

以下是您需要涵盖的四个案例:

subs []     [] = ...     -- input is empty and no more subs to make
subs [] (a:as) = ...     -- input is empty and some extra subs left over
subs (x:xs) [] = ...     -- input not empty and no more subs to make
subs (x:xs) (a:as) = ... -- input not empty and still some subs left

如果您能为所有这些案例提供定义,那么您就完成了!

相关问题