OliverRadini
OliverRadini

Reputation: 6467

Mapping a string using a map

(def conversions {"G" "C"
                  "C" "G"
                  "T" "A"
                  "A" "U"})

(defn to-rna [dna]
  (map conversions dna)
)

(conversions "G") ;; Gives "C"

(to-rna "GC")     ;; Gives (nil nil)

I'm attempting to do an exercise where I convert letters. I have a working solution, but I don't like it. I feel like the above ought to work, but evidently I'm wrong, because it doesn't.

Could someone explain to me why this is, and how I might properly achieve this?

Upvotes: 1

Views: 173

Answers (4)

Alan Thompson
Alan Thompson

Reputation: 29958

As dpassen says, you need to put a java.lang.Character in the map, not a length-1 string. Try this:

(def conversions { \G  \C
                   \C  \G
                   \T  \A
                   \A  \U })

Upvotes: 5

customcommander
customcommander

Reputation: 18901

I'm just starting learning Clojure myself so please take this answer with caution.

In addition to what's been already suggested, I would put the conversions map into a let form to keep your function "isolated". (As is, your function relies on a conversions being defined outside of its scope).

I also read (can't remember where exactly) that a common naming convention when writing functions that "convert" X to Y should be named as follow: x->y.

Finally I'd use a threading macro for improved readability.

(defn dna->rna [dna]
  (let [conversions {\G \C
                     \C \G
                     \T \A
                     \A \U}]
    (->> dna
         (map conversions)
         (string/join ""))))

(dna->rna "GC")
;; "CG"

Upvotes: 4

andy_fingerhut
andy_fingerhut

Reputation: 1516

FYI, Clojure has clojure.string/escape and clojure.string/replace that you might want to look at. escape is probably most similar to what you are doing.

Upvotes: 3

dpassen
dpassen

Reputation: 1306

When mapping over a string, it will treat the string as a sequence of characters. So, your code ends up looking for a \G and a \C entry in the map, which both return nil.

Upvotes: 5

Related Questions