Follow-up to “Simple String template replacement in Scala and Clojure”

后端 未结 3 1796
臣服心动
臣服心动 2021-01-22 00:27

In my previous post, I showed a simple (naive) algorithm for doing a String template replacement.

One of the solutions, provided by mikera, seems like a much better algo

3条回答
  •  北海茫月
    2021-01-22 01:08

    To be honest, your solution looks more like Java in Clojure clothing. Clojure already has the quite flexible clojure.string/replace function which is able to do what you need. Also, your docstring is not matching the Clojure conventions. I would suggest something like this:

    (defn replace-templates
      "Returns a string with each occurrence of the form `{key}` in a
      `template` replaced with the corresponding value from a map
      `m`. Keys of `m` are expected to be keywords."
      [template m]
      (clojure.string/replace template #"\{([^{]+?)\}"
        (fn [[orig key]] (or (get m (keyword key)) orig))))
    

    As one can imagine, replace is already quite optimized, so there is no real reason to roll an own implementation. It's using StringBuffer internally, while you're using StringBuilder, so your implementation might save a few microseconds -- nothing worth talking about.

    If you really care about every microsecond you probably should look into the macro approach. If that is not possible because e.g. you're loading the template from a file then i/o will be a bigger concern anyway. Also in this case I would suggest looking into the Selmer template system, which has a slightly different syntax (with double instead of single curly braces for replacements) but is also much more flexible in what it can do.

提交回复
热议问题