Обзор синтаксиса языка Haskell | Participants
|
- Statistics
- Participants
- Translate into Russian
- Translation result
- 94% translated in draft. Almost done, let's finish it!
If you do not want to register an account, you can sign in with OpenID.
Tour of the Haskell Syntax | ||
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), вам необходимо просмотреть много глав. | |
In the informal syntax rules I use a "..."-notation and subscripts. For example | В неформальных правилах синтаксиса я использую обозначение "..." и индексы. Например: | |
name pattern1 pattern2 ... patternn = expression (n>=0) | name pattern1 pattern2 ... patternn = expression (n>=0) | |
This means that there can be zero or more parameters. Valid instantiations are: | Это значит, что у name может быть 0 или более параметров. Примеры допустимого использования этой синтаксической конструкции: | — instantiations непереводимо имхо — sunray |
pi = 3.14159265 | ||
nextChar c = chr (ord c + 1) | ||
simple x y z = x * (y + z) | ||
Types are printed in italic. | ||
Lines printed in bold are not valid Haskell, but show what the language construct looks like in general. | Строки, выделенные жирным шрифтом, не являются корретными выражениями на языке Haskell, но показывают примерный вид конструкций языка. | |
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 из-за того, что хорошо с ними знаком. | |
# Functions | ||
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: | Простое определение функции состоит из имени функции, за которым следуют ноль или более параметров, знак "равно" и выражение. Например: | |
simple x y z = x * (y + z) | ||
In general the parameters can be arbitrary patterns: | В общем случае параметры могут быть произвольными шаблонами (patterns). | |
name pattern1 pattern2 ... patternn = expression (n>=0) | name pattern1 pattern2 ... patternn = expression (n>=0) | |
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) и сопоставление с шаблоном для описания различных вариантов поведения функции в зависимости от значений ее параметров. | Comment was deleted |
You can also bind a pattern to an expression. | Также можно сопоставлять с шаблоном произвольное выражение. | |
# Pattern bindings | ||
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: | Вместо простого связывания выражения с переменной вы можете сопоставить его с образцом. Разумно выбрать образец, сопоставление с которым всегда успешно: | |
(xs, ys) = unzip listOfPairs | ||
(x:y:z:rest) = [1..] | ||
In general, |

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