开发者

Create a CSV from a Vector in Clojure

开发者 https://www.devze.com 2023-03-17 16:01 出处:网络
I have this (defstruct book :title :year) (def e [ (struct book \"John\" 123) (struct book \"Ashwani\" 456)

I have this

(defstruct book :title :year)
(def e [
        (struct book "John" 123)
        (struct book "Ashwani" 456)
        ])

I want to create a CSV file which has 2 rows from this Vector

John,123
Ashwani,456

I can produce this result on console by using doseq

(doseq [x e]
  ( println (x :title) ","  (x :year)  ))

I am trying to use clojure.contrib.duck-streams/spit to create this CSV but I am not able to iterate thought and create a string and pass it to开发者_JAVA技巧 spit.

What is the best way to achieve this . I was hoping to come up with some reduce function and then pass it to spit and create this csv. (In C# I would open a stream and write each line and in the end close the stream and save the file and my brain is making me think in the foreach way but I am sure there must be some functional way to achieve this)


You could do it with a reduce and duck-streams/spit.

But probably better to use duck-streams/write-lines. That way you don't have to worry about using the proper O/S dependent line separator.

(use 'clojure.contrib.duck-streams)

(write-lines f
  (map #(str (% :title) ","  (% :year)) e))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号