Обзор синтаксиса языка Haskell

Arjan van IJzendoorn, “Tour of the Haskell Syntax”, public translation into Russian from English More about this translation.

See also 100 similar translations

Translate into another language.

Participants

ka3a4ok1019 points
Softy754 points
ventalf290 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
1 2 3 4 5 6 7 8 9 10 11

Tour of the Haskell Syntax

Обзор синтаксиса языка Haskell

History of edits (Latest: sunray 3 years, 9 months ago) §

This document gives an informal overview of the Haskell syntax. A formal syntax can be found at the Haskell homepage. I've made this document because the book we use for teaching here (Haskell School of Expression, Paul Hudak) introduces language constructs by example and the reader may not get a feel for for the language as a whole. For example, to find out what things may serve as a pattern you would have to look through many chapters.

Этот документ представляет неформальный обзор синтаксиса Haskell. Формальную спецификацию синтаксиса языка можно найти на домашней странице Haskell. Я написал этот документ потому, что книга, которую мы используем для преподавания (Haskell School of Expression, Paul Hudak) знакомит читателя с конструкциями языка на основе примеров, и читатель может не прочувствовать язык в полной мере. Например, для того, чтобы узнать, что может послужить шаблоном (pattern), вам необходимо просмотреть много глав.

History of edits (Latest: dnoskov 8 months ago) §

In the informal syntax rules I use a "..."-notation and subscripts. For example

В неформальных правилах синтаксиса я использую обозначение "..." и индексы. Например:

History of edits (Latest: Dmitry-Leushin 2 years, 7 months ago) §

— Может subscript перевести как подстрочный индекс? А то не по-русски как-то. Gazelle

— Можно просто "индекс". Softy

name pattern1 pattern2 ... patternn = expression (n>=0)

name pattern1 pattern2 ... patternn = expression (n>=0)

History of edits (Latest: sunray 3 years, 9 months ago) §

This means that there can be zero or more parameters. Valid instantiations are:

Это значит, что у name может быть 0 или более параметров. Примеры допустимого использования этой синтаксической конструкции:

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

— instantiations непереводимо имхо sunray

pi = 3.14159265

pi = 3.14159265

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

nextChar c = chr (ord c + 1)

nextChar c = chr (ord c + 1)

History of edits (Latest: sunray 3 years, 9 months ago) §

simple x y z = x * (y + z)

simple x y z = x * (y + z)

History of edits (Latest: sunray 3 years, 9 months ago) §

Types are printed in italic.

Имена типов выделены курсивом.

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

Lines printed in bold are not valid Haskell, but show what the language construct looks like in general.

Строки, выделенные жирным шрифтом, не являются корретными выражениями на языке Haskell, но показывают примерный вид конструкций языка.

History of edits (Latest: _adept_ 3 years, 5 months ago) §

Most examples are Prelude functions which means that if you try to load them the Haskell interpreter or compiler will complain about functions being multiply defined. If you want to try them, you would have to rename them. I chose to use mostly Prelude functions because they are familiar.

Большинство примеров являются функциями из стандартной библиотеки Prelude, а значит при их загрузке в интерпретатор или компилятор Haskell'a будут жалобы на то, что такие функции уже определены. Если вы хотите поэкспериментировать с моими примерами, переименуйте их. Для большинства своих примеров я использовал функции Prelude из-за того, что хорошо с ними знаком.

History of edits (Latest: _adept_ 3 years, 5 months ago) §

# Functions

# Функции

History of edits (Latest: hunlong 3 years, 9 months ago) §

A simple function definition is formed by the name of the functions followed by zero or more parameters, an equals sign and then an expression. Example:

Простое определение функции состоит из имени функции, за которым следуют ноль или более параметров, знак "равно" и выражение. Например:

History of edits (Latest: _adept_ 3 years, 5 months ago) §

simple x y z = x * (y + z)

simple x y z = x * (y + z)

History of edits (Latest: sunray 3 years, 9 months ago) §

In general the parameters can be arbitrary patterns:

В общем случае параметры могут быть произвольными шаблонами (patterns).

History of edits (Latest: _adept_ 3 years, 5 months ago) §

name pattern1 pattern2 ... patternn = expression (n>=0)

name pattern1 pattern2 ... patternn = expression (n>=0)

History of edits (Latest: Gazelle 3 years, 9 months ago) §

Note that there are no parentheses around or commas between the parameters. It is good practice to write a type signature above the definition. In function definitions you can use guards and pattern-matching to make choices.

Заметьте, что параметры не окружаются круглыми скобками и не разделяются запятыми. Хорошим тоном является указание сигнатуры типов функции до ее определения. В определении функций вы можете использовать охранные выражения (guards) и сопоставление с шаблоном для описания различных вариантов поведения функции в зависимости от значений ее параметров.

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

Comment was deleted

You can also bind a pattern to an expression.

Также можно сопоставлять с шаблоном произвольное выражение.

History of edits (Latest: _adept_ 3 years, 5 months ago) §

# Pattern bindings

# Сопоставление с образцом

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

Instead of simply binding an expression to a variable you can bind a pattern to it. It is wise to choose patterns that always succeed in this case:

Вместо простого связывания выражения с переменной вы можете сопоставить его с образцом. Разумно выбрать образец, сопоставление с которым всегда успешно:

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

(xs, ys) = unzip listOfPairs

(xs, ys) = unzip listOfPairs

History of edits (Latest: sunray 3 years, 9 months ago) §

(x:y:z:rest) = [1..]

(x:y:z:rest) = [1..]

History of edits (Latest: sunray 3 years, 9 months ago) §

In general,

В целом,

History of edits (Latest: Softy 3 years, 9 months ago) §
Pages: ← previous Ctrl next next untranslated
1 2 3 4 5 6 7 8 9 10 11