1

Suppose i want to change a number in a loop to a keyword in order to check an entry in a dict/map:

(def myarray {:p1 "test"})
#'user/myarray
user> (get myarray 
           (keyword ":p1")
           )
nil
user> (get myarray 
           (symbol ":p1")
           )
nil
user> 

I am just getting nil returned. What do i miss here?

1
  • 1
    You can use a number directly (without converting to a keyword) as a key in a map. (get {1 "test"} 1) Commented Jun 28, 2022 at 0:41

2 Answers 2

4

: is the indicator of keyword according to the Clojure guide, and the keyword function adds : automatically according to the Clojure Docs. So the correct code must be (keyword "p1") instead of (keyword ":p1").

Sign up to request clarification or add additional context in comments.

Comments

0

Here is an outline of how you can do it:

(ns tst.demo.core
  (:use demo.core tupelo.core tupelo.test))

(dotest
  (let [m1 {:p1 "a"
            :p2 "b"}
        k1 (keyword (str "p" 1))
        k2 (keyword (str "p" 2))

        v1 (k1 m1)
        v2 (k2 m1)]
    (is= [k1 k2] [:p1 :p2])
    (is= [v1 v2] ["a" "b"])))

Note though, an integer is a perfectly valid map key:

(dotest
  (let [m1 {1 "a"
            2 "b"}
        k1 1
        k2 2

        v1 (get m1 k1) ; this doesn't work: (k1 m1 )
        v2 (get m1 k2)]
    (is= [k1 k2] [1 2])
    (is= [v1 v2] ["a" "b"])))

You just have to use the get function (with the map as 1st arg!).

The above code is based on this template project.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.