Question

I'm stumped in Clojure. I'm trying to write a system that transforms certain characters of a string based on simple rules that are encoded in pairs like this : ["A" "B"] is a rule to turn "A" into "B"

I have a function "apply-rules-to-char" which takes a vector of such rules and a char, finds the first rule that matches and applies it. It seems to work

(apply-rules-to-char [["A" "B"]] "C")  produces "C"
(apply-rules-to-char [["A" "B"]] "A")  produces "B"
(apply-rules-to-char [["A" "B"]] "M")  produces "M"

However when I now try to apply this across a string, using map

(map (partial apply-rules-to-char [["A" "B"]]) "CAM")

I get back

(\C \A \M)

In other words, it's run through the string "CAM" but hasn't done the transformation on the "A".

Can anyone explain why this is?

Update: Here's the definition of apply-rules-to-char. I'd guess it's not relevant because it always performs correctly when tested by itself. It's only in the map that it fails.

(defn apply-rules-to-char [rules c]
  (let [rule (first (filter #(applicable % c) rules))]
    (if (nil? rule) c (apply-rule-to-char rule c) )  ))
Was it helpful?

Solution

Your apply-rules-to-char function appears to want a string (e.g. "A"), not a character (e.g. \A), which is what a string is made up of. In other words, your function needs to be able to work as (apply-rules-to-char [["A" "B"]] \A), because that's what it will get from map.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top