神刀安全网

Destructuring in Clojure – Part 1

Introduction

Basically, destructuring allows you to create local bindings in a very succint (and elegant) syntax.

In this article, we will demonstrate the basics of destructuring in clojure, usingKLIPSE.

Destructuring a vector

The simplest example is destructuring the first n values of a vector:

A more advanced example is splitting a vector into a head and a tail :

It’s also worth noting that you can bind the entire vector to a local using the :as directive.

Destructuring a map

Simple destructuring on a map is as easy as choosing a local name and providing the key.

As the example shows, the values of :x and :y are bound to locals with the names the-x and the-y .

Usually, you want to create locals with the same name as the keys of the map.

In this case, the syntax becomes even simpler, using the :keys directive:

As with vectors, you can bind the entire map to a local using the :as directive.

Here is how to combine :keys and :as .

In the next article, we will show more advanced usages og destructuring in clojure.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Destructuring in Clojure – Part 1

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮