Изучай Haskell ради Добра! Типы и классы типов | Participants
|
- Statistics
- Participants
- Translate into Russian
- Translation result
- Translation complete.
If you do not want to register an account, you can sign in with OpenID.
Learn you a Haskell for Great Good:chapter - Types and Typeclasses | ||
Types and Typeclasses | ||
Believe the type | ||
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 является статически типизированным языком. Тип каждого выражения известен во время компиляции, что ведет к безопасному коду. Если вы напишете программу, которая попытается поделить булевский тип на число, то она даже не скомпилируется. | |
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 имеет свой тип, так что компилятор может сделать довольно много выводов о вашей программе перед ее компиляцией. | |
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 может вывести это сам, так что нам не надо явно указывать типы наших функций и выражений. | |
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. | |
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" – это строка, и так далее. | — категории вещей.. как-то странно звучит... багаж? =) Я понимаю, что в оригинале так... фиг знает — 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», которая, если за ней следует любое правильное выражение, выдаст нам тип последнего. Давайте попробуем. | |
ghci> :t 'a' | ||
'a' :: Char | ||
ghci> :t True | ||
True :: Bool | ||
ghci> :t "HELLO!" | ||
"HELLO!" :: [Char] | ||
ghci> :t (True, 'a') | ||
(True, 'a') :: (Bool, Char) | ||
ghci> :t 4 == 5 | ||
4 == 5 :: Bool | ||
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. Выглядит логично. Ну а как на счет этого? | |
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. |
License: Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License

— интересно, что лучше "имеет вывод типов" или "умеет выводить типы"? — Dmitry-Leushin
— возможно распознавание типов? — scriper
— нет, именно вывод — asinitsyn
— да, "вывод типов" - общепринятое понятие — Dmitry-Leushin