从文件中收集行

qzc*_*zcx 3 clojure

这应该是一个简单的问题,但我花了几个小时,我仍然不明白如何在Clojure中正确使用集合.我正在尝试读取文件并将每行存储在一个集合中.到目前为止这是我的代码.

(def dictionary #{})
  ;(conj dictionary "hi")
  (defn readDictionary []
    (doseq [line (clojure.string/split-lines 
       (slurp "C:\\Working\\Other\\dictionary.txt"))]
      (println line)
      (conj dictionary line)))
  (readDictionary)

  (println dictionary)
Run Code Online (Sandbox Code Playgroud)

我可以将"hi"字符串附加到集合中,并且每行都在doseq中打印出来,但是当我打印出来时,该集合最终会变成空白.

我对OO编程非常熟悉,但函数式编程对我来说是新的.

Thu*_*ail 6

问题不在于集合本身.问题是conj,像极了核心库的,并不会有副作用.所以表达式:

(conj dictionary line)
Run Code Online (Sandbox Code Playgroud)

... 评估,以dictionaryline添加到它,离开dictionary(和line)相当不变.因此doseq产生一系列集合,每个集合包含一行.

电话

(readDictionary)
Run Code Online (Sandbox Code Playgroud)

...评估这个单成员集序列,然后丢弃它,因为它没有绑定任何东西.因此,呼叫没有净效应.

我想你想要这样的东西(未经测试):

(defn readDictionary [file-name]
  (into #{} (clojure.string/split-lines (slurp file-name))))

(def dictionary (readDictionary "C:\\Working\\Other\\dictionary.txt"))

(doseq [line dictionary] (println line))
Run Code Online (Sandbox Code Playgroud)

在Clojure中,您必须习惯使用在不可变/持久数据结构上运行的纯(无副作用)函数.

  • 我从[*The Little Schemer*](http://www.ccs.neu.edu/home/matthias/BTLS/)开始 - 一个关于递归的基础知识的问答和Scheme方言中的列表.至于Clojure:[Try Clojure](http://tryclj.com/)让你在浏览器中玩REPL; [4Clojure](http://www.4clojure.com/)提供了一个从初级到硬级的问题的阶梯(还有一些要做... grrrrrr).官方文档有一个[Getting Started](http://clojure.org/getting_started)页面,它引用了这些和其他.请享用! (2认同)
  • @qzcx ......当你通过这些工作时,你会明白为什么[KobbyPemson的解决方案](http://stackoverflow.com/a/25085714/1562315)比我们的更好. (2认同)