4
\$\begingroup\$

Given the following code, I have written a for loop that returns a key and value (0 or 1) of file names passed. 1 means present, and 0 means not present.

Is there a way to construct a flat map without having to use into?

(defn kind-stat
 [filename expected-type]
 (let [f (File. filename)
 s (cond
 (.isFile f) "f"
 (.isDirectory f) "d"
 (.exists f) "o" 
 :else "n" )]
 (if (= expected-type s)
 0
 1)))
(defn look-for 
 [filename expected-type]
 (let [find-status (kind-stat filename expected-type)]
 find-status))
(defn all-files-present?
"Takes a list of real file names, and returns a sequence of maps 
 indicating the file name and its availability status 1 for present 
 and 0 for not present. Please note look-for returns 0 for success, 
 so its return logic needs to be reversed for the return sequence 
 of maps."
 [file-seq]
 (for [fnam file-seq
 :let [stat-map {(keyword fnam) 
 (if (= (look-for fnam "f") 0)
 1
 0)}]]
 stat-map))
(into {} 
 (all-files-present? '("Makefile" "build.sh" "real-estate.csv")))
{:Makefile 1, :build.sh 1, :real-estate.csv 0}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Dec 27, 2012 at 16:55
\$\endgroup\$
0

1 Answer 1

5
\$\begingroup\$

You could use zipmap:

(defn all-files-present?
 [file-seq]
 (let [f #(bit-flip (look-for % "f") 0)]
 (zipmap (map keyword file-seq) (map f file-seq))))

or juxt:

(defn all-files-present?
 [file-seq]
 (let [f #(bit-flip (look-for % "f") 0)]
 (into {} (map (juxt keyword f) file-seq))))

Note that I use bit-flip instead of the if to flip 1<->0.


It would be nicer if kind-stat would just return a boolen value, so you would simply use

(defn kind-stat
 [filename expected-type]
 (let [f (File. filename)]
 (= expected-type 
 (cond
 (.isFile f) "f"
 (.isDirectory f) "d"
 (.exists f) "o" 
 :else "n"))))
(defn all-files-present?
 [file-seq]
 (let [f #(if (kind-stat % "f") 1 0)]
 (into {} (map (juxt keyword f) file-seq))))

I removed look-for, since it is virtually useless.

answered Feb 14, 2013 at 15:41
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.