Изучай Haskell ради Добра! Создание своих собственных типов и классов типов

Miran Lipovača, “Learn You a Haskell for Great Good! Making Our Own Types and Typeclasses”, public translation into Russian from English More about this translation.

See also 132 similar translations

Translate into another language.

Participants

asinitsyn13864 points
malphunction28 points
slayzx18 points
And others...
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next next untranslated

Learn You a Haskell for Great Good! Making Our Own Types and Typeclasses

Изучай Haskell ради Добра! Создание своих собственных типов и классов типов

History of edits (Latest: asinitsyn 2 years, 3 months ago) §

Making Our Own Types and Typeclasses

Создание своих собственных типов и классов типов

History of edits (Latest: asinitsyn 2 years, 3 months ago) §

In the previous chapters, we covered some existing Haskell types and typeclasses. In this chapter, we'll learn how to make our own and how to put them to work!

В предыдущих главах мы изучили некоторые типы и классы типов в Хаскеле. В этой главе мы узнаем как создать и заставить работать свои собственные!

History of edits (Latest: asinitsyn 2 years, 2 months ago) §

Algebraic data types intro

Введение в алгебраические типы данных

History of edits (Latest: asinitsyn 2 years, 3 months ago) §

So far, we've run into a lot of data types. Bool, Int, Char, Maybe, etc. But how do we make our own? Well, one way is to use the data keyword to define a type. Let's see how the Bool type is defined in the standard library.

До сих пор мы сталкивались с многими типами данных. Bool, Int, Char, Maybe и т.д. Но как создать свой собственный тип? Один из способов - использовать ключевое слово data. Давайте посмотрим, как в стандартной библиотеке определен тип Bool.

History of edits (Latest: asinitsyn 2 years, 3 months ago) §

data Bool = False | True

data Bool = False | True

History of edits (Latest: asinitsyn 2 years, 3 months ago) §

data means that we're defining a new data type. The part before the = denotes the type, which is Bool. The parts after the = are value constructors. They specify the different values that this type can have. The | is read as or. So we can read this as: the Bool type can have a value of True or False. Both the type name and the value constructors have to be capital cased.

Ключевое слово data объявляет новый тип данных. Часть до знака равенства обозначает тип, в данном случае Bool. Часть после знака равенства - это конструкторы значений. Они определяют, какие значения может принимать тип. Знак | читается как "или". Объявление можно прочесть так: тип Bool может принимать значения True или False. И имя типа и конструкторы значений должны начинаться с заглавной буквы.

History of edits (Latest: Yasir 10 months, 3 weeks ago) §

In a similar fashion, we can think of the Int type as being defined like this:

Рассуждая таким образом, мы можем думать что тип Int объявлен так:

History of edits (Latest: Yasir 10 months, 3 weeks ago) §

data Int = -2147483648 | -2147483647 | ... | -1 | 0 | 1 | 2 | ... | 2147483647

data Int = -2147483648 | -2147483647 | ... | -1 | 0 | 1 | 2 | ... | 2147483647

History of edits (Latest: asinitsyn 2 years, 3 months ago) §

The first and last value constructors are the minimum and maximum possible values of Int. It's not actually defined like this, the ellipses are here because we omitted a heapload of numbers, so this is just for illustrative purposes.

Первое и последнее значение - минимальное и максимально возможное значение для Int. На самом деле Int объявлен не так, троеточия заменяют огромное количество чисел, так что подобная запись нам нужна только для демонстрации.

History of edits (Latest: asinitsyn 2 years, 3 months ago) §

Now, let's think about how we would represent a shape in Haskell. One way would be to use tuples. A circle could be denoted as (43.1, 55.0, 10.4) where the first and second fields are the coordinates of the circle's center and the third field is the radius. Sounds OK, but those could also represent a 3D vector or anything else. A better solution would be to make our own type to represent a shape. Let's say that a shape can be a circle or a rectangle. Here it is:

Теперь, подумаем как бы мы представили некоторую фигуру в Хаскеле. Один из способов - использовать кортежи. Круг может быть представлен как (43.1, 55.0, 10.4), где первое и второе поле - координаты центра, а третье поле - радиус. Вроде подходит, но такой же кортеж может представлять вектор в трехмерном пространстве или что-нибудь другое. Лучшим решением было бы определить свой собственный тип для фигуры. Скажем, наша фигура может быть кругом или прямоугольником.

History of edits (Latest: asinitsyn 2 years, 3 months ago) §

data Shape = Circle Float Float Float | Rectangle Float Float Float Float

data Shape = Circle Float Float Float | Rectangle Float Float Float Float

History of edits (Latest: asinitsyn 2 years, 3 months ago) §

Now what's this? Think of it like this. The Circle value constructor has three fields, which take floats. So when we write a value constructor, we can optionally add some types after it and those types define the values it will contain. Here, the first two fields are the coordinates of its center, the third one its radius. The Rectangle value constructor has four fields which accept floats. The first two are the coordinates to its upper left corner and the second two are coordinates to its lower right one.

Ну и что это? Размышляйте следующим образом. Конструктор для значения Circle содержит три поля типа Float. Когда мы записываем конструктор значения типа, опционально мы можем добавлять типы после имени конструктора, эти типы определяют какие значения будет содержать тип с этим конструктором. В нашем случае первые два числа - это координаты центра, третье число - радиус. Конструктор для значения Rectangle имеет четыре поля, которые так же являются числами с плавающей точкой. Первые два числа это координаты верхнего левого угла, вторые два числа - координаты нижнего правого угла.

History of edits (Latest: asinitsyn 2 years, 3 months ago) §
Pages: ← previous Ctrl next next untranslated

© Miran Lipovača. License: creative commons attribution noncommercial blah blah blah ... license