Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meant by destructuring in Clojure?

Tags:

clojure

I'm a Java and learning clojure.

What is exactly destructuring in clojure?

I can see this blog saying:

The simplest example of destructuring is assigning the values of a vector.

user=> (def point [5 7])
#'user/point

user=> (let [[x y] point]
         (println "x:" x "y:" y))
x: 5 y: 7

what he meant by assigning the values of a vector? Whats the real use of it?

Thanks in advance

like image 211
sriram Avatar asked Jun 29 '14 15:06

sriram


2 Answers

point is a variable that contains a vector of values. [x y] is a vector of variable names.

When you assign point to [x y], destructuring means that the variables each get assigned the corresponding element in the value.

This is just a simpler way of writing:

(let [x (nth point 0) y (nth point 1)]
    (println "x:" x "y:" y))

See Clojure let binding forms for another way to use destructuring.

like image 172
Barmar Avatar answered Sep 25 '22 06:09

Barmar


It means making a picture of the structure of some data with symbols

((fn [[d [s [_ _]]]] 
  (apply str (concat (take 2 (name d)) (butlast (name s)) (drop 7 (name d))) ))     
   '(describing (structure (of data))))

=> "destructuring"

((fn [[d e _ _ _ _ _ i n g _ _ _ _ _ s t r u c t u r e & etc]] 
  [d e s t r u c t u r i n g]) "describing the structure of data")

=> [\d \e \s \t \r \u \c \t \u \r \i \n \g]

Paste those ^ examples into a REPL & play around with them to see how it works.

like image 31
Hendekagon Avatar answered Sep 22 '22 06:09

Hendekagon