denisshevchenko/ohaskell.guide

View on GitHub
chapters/08-choose-n-patterns.md

Summary

Maintainability
Test Coverage

Line length
Open

Эта глава откроет нам другие способы выбора, а также познакомит нас с образцами. Уверяю, вы влюбитесь в них!

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Сравнение с образцом, называемое ещё «сопоставлением с образцом» используется в Haskell чрезвычайно широко. В русскоязычной литературе перевод словосочетания «pattern matching» не особо закрепился, вместо этого так и говорят «паттерн матчинг». Я поступлю так же.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

В последующих главах мы встретимся и с другими видами паттерн матчинга, ведь он используется не только для выбора.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

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

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Убрав слово `if`, мы и с нашими виртуальными «ИЛИ» можем расстаться. В этом случае останется лишь это:

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Важно отметить, что сравнение аргумента с образцами происходит последовательно, сверху вниз. Поэтому если мы напишем так:

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

наша функция будет всегда возвращать первое выражение, строку `I don't know such a standard...`, и это вполне ожидаемо: первая же проверка гарантированно даст нам `True`, ведь с образцом `_` совпадает всё что угодно. Таким образом, общий образец следует располагать в самом конце, чтобы мы попали на него лишь после того, как не сработали все остальные образцы.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

где `EXPRESSION` — анализируемое выражение, последовательно сравниваемое с образцами `PATTERN1..n`. Если ни одно не сработало — как обычно, упираемся в универсальный образец `_` и выдаём `COMMON_EXPR`.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Помните: расширение, включённое с помощью прагмы `LANGUAGE`, действует лишь в рамках текущего модуля. И если я прописал его только в модуле `app/Main.hs`, то на модуль `src/Lib.hs` механизм `MultiWayIf` не распространяется.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Не пренебрегайте `otherwise`! Если вы его не укажете и при этом примените функцию `analyzeGold` к значению, отличному от проверяемых:

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

А сейчас стоп. Вы ведь попробовали скомпилировать этот код, не так ли? А почему вы не ругаетесь? Ведь такой код не скомпилируется, так как не хватает одной маленькой, но важной детали. Вот как должен выглядеть модуль `Main`:

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Мы просто перечислили определения функции `analyzeGold` одно за другим. На первый взгляд, возможность множества определений одной и той же функции удивляет, но если вспомнить, что применение функции суть выражение, тогда ничего удивительного. Вот как это читается:

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Стандарт [Haskell 2010](https://www.haskell.org/onlinereport/haskell2010/) — это официальный стержень языка. Однако компилятор GHC, давно уж ставший компилятором по умолчанию при разработке на Haskell, обладает рядом особых возможностей. По умолчанию многие из этих возможностей выключены, а прагма `LANGUAGE` как раз для того и предназначена, чтобы их включать/активизировать. В данном случае мы включили расширение `MultiWayIf`. Именно это расширение позволяет нам использовать множественный `if`. Такого рода расширений существует очень много, и мы будем часто их использовать.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

где `COND1..n` — выражения, дающие ложь или истину, а `EXPR1..n` — соответствующие им результирующие выражения. Особая функция `otherwise` соответствует общему случаю, когда ни одно из логических выражений не дало `True`, и в этой ситуации результатом условной конструкции послужит выражение `COMMON_EXPR`.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

То есть перед нами уже не одно определение функции, а цепочка определений, потому нам и не нужно ключевое слово `if`. Но и эту цепочку определений можно упростить.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

С формальной точки зрения, это — универсальный образец, сравнение с которым всегда истинно (ещё говорят, что с ним матчится (англ. match) всё что угодно). А с неформальной — это символ, который можно прочесть как «мне всё равно». Мы как бы говорим: «В данном случае нас не интересует конкретное содержимое аргумента, нам всё равно, мы просто возвращаем строку `I don't know such a standard...`».

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Вот теперь всё в порядке. Но что это за странный комментарий в первой строке модуля? Вроде бы оформлен как многострочный комментарий, но выглядит необычно. Перед нами — указание расширения языка Haskell.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Часто мы хотим выбирать не только из двух возможных вариантов. Вот как это можно сделать:

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Уверен, вы уже стираете плевок с экрана. Вложенная `if-then-else` конструкция не может понравиться никому, ведь она крайне неудобна в обращении. А уж если бы анализируемых проб золота было штук пять или семь, эта лестница стала бы поистине ужасной. К счастью, в Haskell можно написать по-другому:

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Кстати, видите слово `guards` в сообщении об ошибке? Вертикальные черты перед логическими выражениями — это и есть охранники (англ. guard), неусыпно охраняющие наши условия. Потешное название выбрали. Чтобы читать их было легче, воспринимайте их как аналог слова «ИЛИ».

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Устройство почти такое же, но, помимо исчезновения ключевого слова `if`, мы теперь используем знаки равенства вместо стрелок. Именно поэтому исчез знакомый нам знак равенства после имени аргумента `arg`. В действительности он, конечно, никуда не исчез, он лишь перешёл в выражения. А чтобы это легче прочесть, напишем выражения в строчку:

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

Line length
Open

Когда функция `analyzeGold` применяется к конкретному аргументу, этот аргумент последовательно сравнивается с образцом (англ. pattern matching). Образца здесь три: `999`, `750` и `585`. И если раньше мы сравнивали аргумент с этими числовыми значениями явно, посредством функции `==`, теперь это происходит скрыто. Идея сравнения с образцом очень проста: что-то (в данном случае реальный аргумент) сопоставляется с образцом (или образцами) на предмет «подходит/не подходит». Если подходит — то есть сравнение с образцом даёт результат `True` — готово, используем соответствующее выражение. Если же не подходит — переходим к следующему образцу.

MD013 - Line length

Tags: line_length

Aliases: line-length Parameters: linelength, codeblocks, tables (number; default 80, boolean; default true)

This rule is triggered when there are lines that are longer than the configured line length (default: 80 characters). To fix this, split the line up into multiple lines.

This rule has an exception where there is no whitespace beyond the configured line length. This allows you to still include items such as long URLs without being forced to break them in the middle.

You also have the option to exclude this rule for code blocks and tables. To do this, set the code_blocks and/or tables parameters to false.

Code blocks are included in this rule by default since it is often a requirement for document readability, and tentatively compatible with code rules. Still, some languages do not lend themselves to short lines.

There are no issues that match your filters.

Category
Status