Clojure Distilled
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
Clojure Distilled
Clojure Distilled The difficulty in learning Clojure does not stem from its syntax, which happens to be extremely simple, but from having to learn new methods for solving problems. As such, we’ll focus on understanding the core concepts and how they can be combined to solve problems the functional way.
学习 Clojure 的困难并不在于其语法(语法实际上非常简单),而在于必须学习解决问题的新方法。因此,我们将专注于理解核心概念,以及如何将它们结合起来以函数式的方式解决问题。
All the mainstream languages belong to the same family. Once you learn one of these languages there is very little effort involved in learning another. Generally, all you have to do is learn some syntax sugar and the useful functions in the standard library to become productive. There might be a new concept here and there, but most of your existing skills are easily transferable.
所有主流语言都属于同一个家族。一旦你学会了其中一种语言,学习另一种语言几乎不需要费什么力气。通常,你只需要学习一些语法糖和标准库中的有用函数即可上手。虽然偶尔会出现一些新概念,但你现有的大部分技能都可以轻松迁移。
This is not the case with Clojure. Being a Lisp dialect, it comes from a different family of languages and requires learning new concepts in order to use effectively. There is no reason to be discouraged if the code appears hard to read at first. I assure you that the syntax is not inherently difficult to understand, and that with a bit of practice you might find it to be quite the opposite.
Clojure 的情况并非如此。作为 Lisp 的一种方言,它来自一个不同的语言家族,需要学习新的概念才能有效使用。如果代码起初看起来难以阅读,不必气馁。我向你保证,其语法本身并不难理解,只要稍加练习,你可能会发现事实恰恰相反。
The goal of this guide is to provide an overview of the core concepts necessary to become productive with Clojure. Let’s start by examining some of the key advantages of the functional style and why you would want to learn a functional language in the first place.
本指南旨在概述使用 Clojure 进行高效开发所需的核心概念。让我们先来看看函数式风格的一些关键优势,以及你为什么要学习一门函数式语言。
Immutable Clojure is a functional language. This makes it extremely well positioned for writing large applications. As the application grows it’s imperative to be able to reason about its constituent parts in isolation. Conversely, there is a lot of value in building code out of components that are testable and reusable by nature. Let’s take a look at why the functional approach is such a good fit here.
不可变性(Immutable)。Clojure 是一门函数式语言。这使得它非常适合编写大型应用程序。随着应用程序的增长,能够独立地推导其组成部分变得至关重要。反过来说,用本质上可测试和可重用的组件构建代码具有很大的价值。让我们来看看为什么函数式方法在这里如此契合。
Functional languages are ideal for writing large applications because they eschew global state and favor immutability as the default. Having immutable shared state allows us to safely reason about parts of the application in isolation. At first glance, the idea of using immutable data structures sounds unnecessarily restrictive. However, as we’ll soon see, many of the benefits associated with the functional style stem directly from it.
函数式语言是编写大型应用程序的理想选择,因为它们避免使用全局状态,并默认倾向于不可变性。拥有不可变的共享状态使我们能够安全地独立推导应用程序的各个部分。乍一看,使用不可变数据结构的想法似乎过于限制。然而,正如我们很快会看到的,函数式风格的许多好处都直接源于此。
Mutable data can either be passed around by value or by reference. The safe approach would be to pass the data by value as it guarantees that any changes to the data will remain in the local scope. Unfortunately, this approach is extremely inefficient, so most languages pass data by reference instead. Passing data by reference is fast, but it makes the code difficult to reason about.
可变数据可以通过值传递或引用传递。安全的方法是按值传递数据,因为它保证对数据的任何更改都将保留在局部范围内。不幸的是,这种方法效率极低,因此大多数语言改用引用传递数据。按引用传递数据很快,但它使代码难以推导。
In order to safely work with the data you have to know all the places where it might be referenced. The complexity grows with the size of the application. The more code has access to a piece of data the more proverbial balls you end up having to juggle in your head.
为了安全地处理数据,你必须知道所有可能引用它的地方。复杂性随着应用程序规模的扩大而增加。访问某段数据的代码越多,你脑子里需要处理的“杂事”就越多。
Immutable data structures provide us with an ingenious alternative to the above dilemma. Every time a change is made to the data structure a revision is created. We now have the same guarantees offered by naive copying of the data, but we only pay the price proportional to the size of the change.
不可变数据结构为上述困境提供了一种巧妙的替代方案。每次对数据结构进行更改时,都会创建一个修订版本。我们现在拥有了简单复制数据所提供的相同保证,但我们只需付出与更改规模成比例的代价。
Just like garbage collection frees us from having to manually track data allocation and deallocation, immutable data structures free us from having to manage data references by hand. From the user perspective we simply “copy” the data any time we make a change. The language will take care of figuring out what parts of it can be cleaned up when they’re no longer used.
就像垃圾回收机制使我们无需手动跟踪数据的分配和释放一样,不可变数据结构使我们无需手动管理数据引用。从用户的角度来看,我们只是在每次更改时“复制”数据。语言本身会负责处理当数据不再使用时,哪些部分可以被清理。
Having such data structures facilitates writing pure functions. A pure function is simply a function without side effects. These functions do not rely on any state outside their inputs and they do not modify any external state when they run. Given the same parameters, the function will always produce the same result, regardless of the global state of the application.
拥有这样的数据结构有助于编写纯函数。纯函数就是没有副作用的函数。这些函数不依赖于输入之外的任何状态,并且在运行时不会修改任何外部状态。给定相同的参数,无论应用程序的全局状态如何,函数总是产生相同的结果。
Such functions can be safely reasoned about in isolation because we can guarantee that they’re only able to modify their local scope. They provide us with self-contained components that can be composed to create complex behaviors. This type of code is referred to as being referentially transparent.
这样的函数可以被安全地独立推导,因为我们可以保证它们只能修改其局部范围。它们为我们提供了自包含的组件,可以组合起来创建复杂的行为。这种类型的代码被称为引用透明。
Reusable Object-oriented languages use classes for composition. The data in each class is tightly coupled to the logic associated with it. Each class represents a specific domain and the methods written in it are not easily reusable outside that domain. When we wish to reuse the existing code we often have to resort to patterns such as adapters and wrappers.
可重用性(Reusable)。面向对象语言使用类进行组合。每个类中的数据与其相关的逻辑紧密耦合。每个类代表一个特定的领域,其中编写的方法在领域之外不容易重用。当我们希望重用现有代码时,通常不得不求助于适配器和包装器等模式。
The focus, in such a language, is primarily on modeling the state using classes. The data is seen as being incidental to the whole process. Functional programming brings data to the forefront and it encourages us to think about our problems in terms of data transformations. In a functional language, the logic and the data are kept separate.
在这种语言中,重点主要在于使用类来建模状态。数据被视为整个过程的附带品。函数式编程将数据置于首位,并鼓励我们从数据转换的角度来思考问题。在函数式语言中,逻辑和数据是分开的。
Clojure provides a small set of common data structures such as lists, vectors, maps, and sets. All the functions in the language operate on the same data structures allowing us to combine them without any additional ceremony. With this approach the function becomes the core reusable component.
Clojure 提供了一小套通用的数据结构,如列表、向量、映射和集合。语言中的所有函数都对相同的数据结构进行操作,使我们能够无需任何额外步骤即可组合它们。通过这种方法,函数成为了核心的可重用组件。
Each function represents a certain transformation that we wish to apply to our data. When we need to solve a problem we simply have to break it up into a sequence of transformations and map those to the appropriate functions. The functions capture how the tasks are accomplished, while their composition states what is being accomplished.
每个函数代表我们希望应用于数据的某种转换。当我们解决问题时,只需将其分解为一系列转换,并将它们映射到相应的函数即可。函数捕获了任务是如何完成的,而它们的组合则说明了正在完成什么。
Code that separates what is being done from how it is done is referred to as being declarative. Let’s take iteration as an example. With the imperative style we would write a loop and put the logic that’s invoked during each step inside it. By contrast, the functional approach is to use an iterator function and pass the logic that we want to execute during the iteration as a parameter. An iterator function can be written once and it encapsulates all the logic required for
将“做什么”与“怎么做”分开的代码被称为声明式代码。以迭代为例。在命令式风格中,我们会编写一个循环,并将每一步调用的逻辑放在循环内。相比之下,函数式方法是使用迭代器函数,并将我们希望在迭代期间执行的逻辑作为参数传递。迭代器函数可以编写一次,它封装了所需的所有逻辑。