从字符序列中创建字符串 [英] Make String from Sequence of Characters

查看:150
本文介绍了从字符序列中创建字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码无法按预期工作。你能解释为什么吗?

This code does not work as I expected. Could you please explain why?

(defn make-str [s c]
    (let [my-str (ref s)]
    (dosync (alter my-str str c))))

(defn make-str-from-chars
    "make a string from a sequence of characters"
    ([chars] make-str-from-chars chars "")
    ([chars result]
        (if (== (count chars) 0) result
        (recur (drop 1 chars) (make-str result (take 1 chars))))))

谢谢!

推荐答案

将一个字符的序列传递给 make-str 函数,而不是字符本身。使用首先而不是采取应该给你想要的效果。

You pass a sequence with one character in it to your make-str function, not the character itself. Using first instead of take should give you the desired effect.

也没有必要使用引用。实际上,你对它们的使用是对它们的粗暴滥用。您已在函数中使用累加器,因此可以直接使用 str

Also there is no need to use references. In effect your use of them is a gross misuse of them. You already use an accumulator in your function, so you can use str directly.

(defn make-str-from-chars
  "make a string from a sequence of characters"
  ([chars] (make-str-from-chars chars ""))
  ([chars result]
    (if (zero? (count chars))
      result
      (recur (drop 1 chars) (str result (first chars))))))

当然 count ,因为它总是必须走遍整个序列以确定其长度。因此,您不必要地遍历输入序列几次。通常使用 seq 来标识序列何时用尽。我们还可以使用 next 而不是 drop 来节省创建不必要的序列对象的开销。请务必捕获 seq 的返回值,以避免以后创建对象的开销。我们在 if-let 中这样做。

Of course count is not very nice in this case, because it always has to walk the whole sequence to figure out its length. So you traverse the input sequence several times unnecessarily. One normally uses seq to identify when a sequence is exhausted. We can also use next instead of drop to save some overhead of creating unnecessary sequence objects. Be sure to capture the return value of seq to avoid overhead of object creations later on. We do this in the if-let.

(defn make-str-from-chars
  "make a string from a sequence of characters"
  ([chars] (make-str-from-chars chars ""))
  ([chars result]
     (if-let [chars (seq chars)]
       (recur (next chars) (str result (first chars)))
       result)))

像这样的函数,只要在完全消耗其输入时返回累加器,则为 reduce

Functions like this, which just return the accumulator upon fully consuming its input, cry for reduce.

(defn make-str-from-chars
  "make a string from a sequence of characters"
  [chars]
  (reduce str "" chars))

好和短,但在这种特殊情况下,我们可以做一些更好的使用 apply 。然后 str 可以使用底层的 StringBuilder 达到它的全部功能。

This is already nice and short, but in this particular case we can do even a little better by using apply. Then str can use the underlying StringBuilder to its full power.

(defn make-str-from-chars
  "make a string from a sequence of characters"
  [chars]
  (apply str chars))

希望这有帮助。

这篇关于从字符序列中创建字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆