Hi all, I’m new here.
I’m working through an exercise in The Clojure Workshop, and the goal is to create encoding functions that can take a string and convert each of the characters to a number. The instruction is to use clojure.string/replace in the exercise.
Here are my functions:
(defn encode-letter "Encode individual characters to an int" [s] (let [code (Math/pow (int (first (char-array s))) 2)] (str "#" (int code)))) (defn encode-phrase [s] (clojure.string/replace s #"\w" encode-letter))
When playing with these, I noticed that
encode-phrase will work correctly like this as well:
(defn encode-phrase [s] (clojure.string/replace s #"\w" (fn [s] (encode-letter s))))
But not like this:
(defn encode-phrase [s] (clojure.string/replace s #"\w" (encode-letter s)))
In the latter case, the output ends up just being a repeat of the first character of the string. I’m struggling to understand why - would someone mind explaining?