【问题标题】:Replacing multiple substrings with respective replacements用各自的替换替换多个子串
【发布时间】:2012-07-23 20:32:55
【问题描述】:

我有一个String,它包含多个${...} 形式的标签(其中... 可以是任何不包含} 字符的字符串),例如foo ${bar} baz ${qux}

我想替换这些标签,但要做到这一点,我需要以下形式的函数:

replace :: [String] -> [String] -> String -> String
--           tags    replacements  target    result
replace ["${bar}", "${qux}"] ["abc", "def"] "foo ${bar} baz ${qux}" == "foo abc baz def"

(当给定数组作为参数时,这类似于 PHP 的 str_replace 函数。)

我在任何包中都找不到这样的替换功能。有没有这样的功能,如果没有我怎么写(指向正确的方向就够了;我正在学习Haskell)?

【问题讨论】:

    标签: haskell replace


    【解决方案1】:

    作为单行:

    Prelude Data.Text> Prelude.foldr (uncurry Data.Text.replace) "foo ${bar} baz ${qux}" $ Prelude.zip ["${bar}", "${qux}"] ["abc", "def"]
    "foo abc baz def"
    

    换句话说:

    replace as bs x = Prelude.foldr (uncurry Data.Text.replace) x $  Prelude.zip as bs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-06
      • 2019-11-20
      • 2012-04-18
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 2019-01-17
      相关资源
      最近更新 更多