Xiufen Xu
Xiufen Xu

Reputation: 531

How to return a map in clojure

I am wondering how to define a function, which will return a map. Now I have two auxiliary functions. One is :

(string->ascii str) 

which can convert a string into an ascii code, like:

user=> (string->ascii "ouch")
(79 85 67 72)
user=> (string->ascii "gulp")
(71 85 76 80)

the other function is:

(ascii->num96 seq)

which can convert a list into a decimal, like:

user=> (ascii-num96 '(79 85 67 72))
70684008
user=> (ascii-num96 '(71 85 76 80))
63606992

Now, I need to define a function "make-dict" calling these two functions together and returning a map. The result should be:

user=> (make-dict ["ouch" "gulp"])
{"ouch" 70684008, "gulp" 63606992}

I wrote some code, but it does not work, like:

(defn make-dict [vector]
(map (ascii-num96 #(string-ascii %)) vector))

Is there anyone who can teach how to get the result like this? Thank you so much!

Upvotes: 1

Views: 409

Answers (2)

Chris Murphy
Chris Murphy

Reputation: 6509

Or without zipmap:

(into {} (map vector names (map (comp ascii-num96 string->ascii) names)))

Two things going on might be of interest, kind of 'tricks'. One is that you can use map with many input sequences, your 'mapping function' just needs to be able to handle the same number of arguments. Here the mapping function is vector, which takes a word and a number and puts them together, like this: ["gulp" 34234].

The other thing is that the function into interprets a vector as a key / value pair.

Upvotes: 3

Elango
Elango

Reputation: 108

How about this?

(defn make-dict [words]
  (zipmap words (map (comp ascii-num96 string->ascii) words)))

You basically take 2 seqs -- words and (map (comp ascii-num96 string->ascii) words) -- and zip them up into a map.

Upvotes: 3

Related Questions