ClojureのDestructuring(1)

ウェブ技術 デジタルトランスフォーメーション技術 人工知能技術 自然言語処理技術 セマンティックウェブ技術 深層学習技術 オンライン学習&強化学習技術 チャットボットと質疑応答技術 ユーザーインターフェース技術 知識情報処理技術 推論技術  Clojure プログラミング

Clojureを使う上で重要なデータのDestrucurtingについてまとめる。サンプルコードは「Destructuring in Clojure」を参照した。まずベクトルデータからのデータの分割は以下となる。

(def my-line [[5 10] [10 20]]) 
(let [p1 (first my-line) 
    p2 (second my-line) 
      x1 (first p1) 
      y1 (second p1) 
      x2 (first p2) 
      y2 (second p2)] 
 (println "Line from (" x1 "," y1 ") to (" x2 ", " y2 ")")) 
;= "Line from ( 5 , 10 ) to ( 10 , 20 )"

これをlet文を使ったDesctructuringで表すと以下となる。

;= Using the same vector as above 
(let [[p1 p2] my-line 
    [x1 y1] p1 
      [x2 y2] p2] 
 (println "Line from (" x1 "," y1 ") to (" x2 ", " y2 ")")) 
;= "Line from ( 5 , 10 ) to ( 10 , 20 )"

ベクトルデータ以外のDestructuringは以下となる。

(def my-vector [1 2 3]) 
(def my-list '(1 2 3)) 
(def my-string "abc") 

;= It should come as no surprise that this will print out 1 2 3 
(let [[x y z] my-vector] 
   (println x y z)) 
;= 1 2 3 

;= We can also use a similar technique to destructure a list 
(let [[x y z] my-list] 
   (println x y z)) 
;= 1 2 3 

;= For strings, the elements are destructured by character. 
(let [[x y z] my-string] 
  (println x y z) 
  (map type [x y z])) 
;= a b c 
;= (java.lang.Character java.lang.Character java.lang.Character)

Destructuringする対象が大きいか小さい時には以下となる。

(def small-list '(1 2 3)) 
(let [[a b c d e f g] small-list] 
  (println a b c d e f g)) 
;= 1 2 3 nil nil nil nil

(def large-list '(1 2 3 4 5 6 7 8 9 10)) 
(let [[a b c] large-list] 
  (println a b c)) 
;= 1 2 3

小さい時は、残りはnilになり、大きい時は切り捨てられる。また値の指定以下のように出来る。

(def names ["Michael" "Amber" "Aaron" "Nick" "Earl" "Joe"])

(let [[item1 item2 item3 item4 item5 item6] names] 
  (println item1) 
  (println item2 item3 item4 item5 item6)) 
;= Michael 
;= Amber Aaron Nick Earl Joe

(let [[item1 & remaining] names] 
  (println item1) 
  (apply println remaining)) 
;= Michael 
;= Amber Aaron Nick Earl Joe

(let [[item1 _ item3 _ item5 _] names] 
  (println "Odd names:" item1 item3 item5)) 
;= Odd names: Michael Aaron Earl

(let [[item1 :as all] names] 
  (println "The first name from" all "is" item1)) 
;= The first name from [Michael Amber Aaron Nick Earl Joe] is Michael

(def word "Clojure") 
(let [[x & remaining :as all] word] 
  (apply prn [x remaining all])) 
;= \C (\l \o \j \u \r \e) "Clojure"

また任意のネストしたデータにも適用できる。

(def my-line [[5 10] [10 20]])

(let [[[x1 y1][x2 y2]] my-line] 
  (println "Line from (" x1 "," y1 ") to (" x2 ", " y2 ")")) 
;= "Line from ( 5 , 10 ) to ( 10 , 20 )"

(let [[[a b :as group1] [c d :as group2]] my-line] 
  (println a b group1) (println c d group2)) 
;= 5 10 [5 10] ;= 10 20 [10 20]

次回もDestructuringについて述べる。

コメント

  1. […] きしていくような変数の場合はletを使用することとなる。(上書き可能な変数の利用は基本的には”Clojureのdestructuring“で述べているようにローカル変数として扱うことが基本となる) […]

  2. […] Destructuring(1) ローカル変数のハンドリング […]

タイトルとURLをコピーしました