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

Miran Lipovača, “Learn you a Haskell for Great Good:chapter - Types and Typeclasses”, public translation into Russian from English More about this translation.

See also 27 similar translations

Translate into another language.

Participants

olegchir1753 points
Dmitry-Leushin1033 points
asinitsyn366 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
1 2 3 4 5 6 7 8

Learn you a Haskell for Great Good:chapter - Types and Typeclasses

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

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

Types and Typeclasses

Типы и классы типов

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

Believe the type

Поверь в типы

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

Previously we mentioned that Haskell has a static type system. The type of every expression is known at compile time, which leads to safer code. If you write a program where you try to divide a boolean type with some number, it won't even compile.

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

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

That's good because it's better to catch such errors at compile time instead of having your program crash. Everything in Haskell has a type, so the compiler can reason quite a lot about your program before compiling it.

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

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

Unlike Java or Pascal, Haskell has type inference. If we write a number, we don't have to tell Haskell it's a number. It can infer that on its own, so we don't have to explicitly write out the types of our functions and expressions to get things done.

В отличие от Java или Pascal, у Haskell есть механизм распознавания типов. Если мы напишем число, то нам не надо говорить языку, что это число. Haskell может вывести это сам, так что нам не надо явно указывать типы наших функций и выражений.

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

— интересно, что лучше "имеет вывод типов" или "умеет выводить типы"? Dmitry-Leushin

— возможно распознавание типов? scriper

— нет, именно вывод asinitsyn

— да, "вывод типов" - общепринятое понятие Dmitry-Leushin

We covered some of the basics of Haskell with only a very superficial glance at types. However, understanding the type system is a very important part of learning Haskell.

Мы изучили некоторые основы Haskell только очень поверхностно упомянув типы. Тем не менее, понимание системы типов является очень важной частью обучения языку Haskell.

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

A type is a kind of label that every expression has. It tells us in which category of things that expression fits. The expression True is a boolean, "hello" is a string, etc.

Тип – это нечто вроде ярлыка, который есть у каждого выражения. Он говорит нам, к какой категории относится данное выражение. Выражение «True» – булево, "hello" – это строка, и так далее.

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

— категории вещей.. как-то странно звучит... багаж? =) Я понимаю, что в оригинале так... фиг знает Dmitry-Leushin

Now we'll use GHCI to examine the types of some expressions. We'll do that by using the :t command which, followed by any valid expression, tells us its type. Let's give it a whirl.

А сейчас воспользуемся GHCi для определения типов нескольких выражений. Мы сделаем это с помощью команды «:t», которая, если за ней следует любое правильное выражение, выдаст нам тип последнего. Давайте попробуем.

History of edits (Latest: YasirArsanukaev 1 year, 2 months ago) §

ghci> :t 'a'

ghci> :t 'a'

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

'a' :: Char

'a' :: Char

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

ghci> :t True

ghci> :t True

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

True :: Bool

True :: Bool

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

ghci> :t "HELLO!"

ghci> :t "HELLO!"

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

"HELLO!" :: [Char]

"HELLO!" :: [Char]

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

ghci> :t (True, 'a')

ghci> :t (True, 'a')

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

(True, 'a') :: (Bool, Char)

(True, 'a') :: (Bool, Char)

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

ghci> :t 4 == 5

ghci> :t 4 == 5

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

4 == 5 :: Bool

4 == 5 :: Bool

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

Here we see that doing :t on an expression prints out the expression followed by :: and its type. :: is read as "has type of". Explicit types are always denoted with the first letter in capital case. 'a', as it would seem, has a type of Char. It's not hard to conclude that it stands for character. True is of a Bool type. That makes sense. But what's this?

Мы видим что делает «:t» с выражениями – печатает сами выражения, за которыми следует «::» и их тип. «::» читается как «имеет тип». У явно указанных типов первый символ всегда в вернем регистре. 'a', как можно увидеть, имеет тип Char. Не сложно сообразить, что это обозначает «character» – символ. True – это тип Bool. Выглядит логично. Ну а как на счет этого?

History of edits (Latest: YasirArsanukaev 1 year, 2 months ago) §

Examining the type of "HELLO!" yields a [Char]. The square brackets denote a list. So we read that as it being a list of characters. Unlike lists, each tuple length has its own type. So the expression of (True, 'a') has a type of (Bool, Char), whereas an expression such as ('a','b','c') would have the type of (Char, Char, Char). 4 == 5 will always return False, so its type is Bool.

Исследуя тип "HELLO!" получим [Char]. Квадратные скобки указывают на список, так мы прочтем это как «список символов». В отличие от списков, каждый кортеж любой длины имеет свой тип. Так выражение (True, 'a') имеет тип (Bool, Char), тогда как выражение ('a','b','c') будет иметь тип (Char, Char, Char). «4==5» всегда вернет False, поэтому его тип – Bool.

History of edits (Latest: Dmitry-Leushin 2 years, 7 months ago) §
Pages: ← previous Ctrl next
1 2 3 4 5 6 7 8

License: Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License