Destructuring Examples


#1

Originally published at: https://purelyfunctional.tv/destructuring/destructuring-examples/
We go over some cases where destructuring is very useful. We also look at why we shouldn’t use it all the time.


#2

In the loop example:

(loop [[f & rst] (seq 1 2 3 4)]
    (println f)
    (recur rst))

I understand there is a difference between clojure’s rest and next functions. Will rst always be the correct cdr function from what is being destructured?


#3

Hi @Davin_Tryon,

The destructuring of a sequence will assign nil to the rest argument if there aren’t enough elements. It doesn’t matter what the type of the collection is.

The difference between rest and next is simply that next will return nil when the sequence runs out instead of returning an empty list.

Also, be careful. (seq 1 2 3 4) is incorrect code. I think you mean (list 1 2 3 4).

Rock on!
Eric


#4

Ah, thanks that makes sense. and yes (list 1 2 3 4).

I thought I read somewhere that rest and next behave differently on a lazy collection.

So, are you saying that destructuring into rst is always the same as using next?


#5

Hi @Davin_Tryon,

I thought I read somewhere that rest and next behave differently on a lazy collection.

Yes, they behave differently. rest is slightly lazier. next will evaluate one more item in the lazy sequence. But if you need to know if the sequence is empty, you’ll need to evaluate it anyway.

Answering that precisely will require going into the source code. But I think it’s safe to think of it that way.

Eric