如何操纵记录?

时间:2012-04-03 07:25:44

标签: clojure

如何操纵记录?

我在哪里可以找到一些例子?

我想对记录制作一个序列。 例如:

(defrecord Point [x y])

如何从'[[1 2] [3 4] [5 6]]'制作一系列点数?

如果数据存储在文件中:

1 2
3 4
5 6

如何将这些内容读入记录?

(with-open [rdr (clojure.java.io/reader file)]
  (doall (? (line-seq rdr))))))

谢谢!

2 个答案:

答案 0 :(得分:5)

Clojure的defrecord为所定义的类型生成一些辅助函数。他们的目的是让这种类型的建造者成为一流的Clojure公民。特别是defrecord Point会生成map->Point,它会获取一个地图并且(这可能是您需要的)->Point采用位置参数。所以这个:

(defrecord Point [x y])
(map (partial apply ->Point) [[1 2] [3 4]])

产生这个:

(#user.Point{:x 1, :y 2} #user.Point{:x 3, :y 4})

答案 1 :(得分:1)

您的defrecord声明是正确的。

然后,您可以使用(Name. <args>)表格

创建积分的实例
;=> (defrecord Point [ x y ])
user.Point
;=> (def p (Point. 1 2)
#user.Point{:x 1, :y 2}

; records have access of members 'as-if' they were a hash 
; (but more efficient)
;=> (:x p)
1

; sequence of points...    
;=> [(Point. 1 2)(Point. 3 4)(Point. 5 6)]
[#user.Point{:x 1, :y 2} #user.Point{:x 3, :y 4} #user.Point{:x 5, :y 6}]

; read from a whitespace separated file
;=> (with-open [rdr (clojure.java.io/reader file)]
      (doall (for [[x y] (map #(re-seq #"\w+" %) (line-seq rdr))]
         (Point. x y))))
(#user.Point{:x "1", :y "2"} #user.Point{:x "3", :y "4"} #user.Point{:x "5", :y "6"})