Haskell синоним типа

A type synonym is a new name for an existing type.
Values of different synonyms of the same type are entirely compatible.
In Haskell you can define a type synonym using type:

type MyChar = Char

In C you define a type synonym using typedef.

В функциональном языке программирования Haskell синонимом типа называется определение, записанное при помощи ключевого слова type. Такое определение формирует краткое (или мнемоническое) наименование некоторого типа, которое используется исключительно в качестве сокращения и является полностью тождественным самому типу. При определении синонимов типов можно использовать полиморфизм.

Основное назначение синонимов — создание единственного места, где определяется некоторый сложный тип данных, не связанный с конструированием объектов в памяти. Это единственное место (собственно, определение синонима) используется для того, чтобы в нужный момент заменить определение типа в одном месте, чтобы оно автоматически поменялось во всём исходном коде, где только используется.

Примеры:

type IntList = [Int]

type Field a = [[a]]

type Function a b = a -> b

Синонимы типов могут использоваться везде, где могут использоваться сами типы, за исключением одного места — определения экземпляров классов.

This corresponds to existential quantification. In pseudo-Haskell,

type NumberList = exists a . Num a => [a]

I say «pseudo» because GHC doesn’t allow introducing existential quantifiers on the fly — you need to create a separate datatype for that.

Now, most of the type you’d use NumberList to the left of the arrow, where «exists» effectively changes its meaning to «forall».

That is, instead of writing

isIncreasing :: NumberList -> Bool

which is the same as

isIncreasing :: (exists a . Num a => [a]) -> Bool

you can write

isIncreasing :: forall a . Num a => [a] -> Bool

or simply

isIncreasing :: Num a => [a] -> Bool

Of course, having a type synonym seems like less code, but it has disadvantages as well.
These disadvantages, by the way, are typical for object-oriented programming, which is based on the existential approach.

For example, you want to concatenate two lists. Ordinarily you would write

(++) :: forall a . [a] -> [a] -> [a]

(where again forall is unnecessary and added for clarity). Since a is the same across the entire signature, that ensures that you are concatenating lists of the same type.

How do we concatenate two numeric lists? A signature

(++) :: NumberList -> NumberList -> NumberList

wouldn’t work, since one list may contain Ints and the other may contain Doubles. And the resulting NumberList has to contain values of a single type.

Or, say, you want to find the sum of the list elements.

Usually you write

sum :: Num a => [a] -> a

Notice that the result type is the same as the type of list elements. Alas, we cannot do the same for NumberList!

sum :: NumberList -> ???

What is the result type? We could apply existential quantification there as well.

sum :: NumberList -> (exists a . Num a => a)

But now the connection between the original list type and the sum type is lost — at least for Haskell’s type system. If you then decide to write a function like

multiplySum :: Integer -> [Integer] -> Integer
multiplySum x ys = x * sum ys

then you’ll get a type error, because sum ys may be of any type, not necessarily of type Integer.

It would work if you pushed everything to extreme and made every type existentially-quantified — but then you’d end up essentially with another object-oriented-like language with all their problems.

(That said, there are some good use cases for existential quantification, of course.)

Синонимы типов

Ранее мы упоминали, что типы [Char] и String являются эквивалентами и могут взаимно заменяться. Это осуществляется с помощью синонимов типов. Синоним типа сам по себе ничего не делает – он просто даёт другое имя существующему типу, облегчая понимание нашего кода и документации. Вот так стандартная библиотека определяет тип String как синоним для [Char]:

type String = [Char]

Ключевое слово type может ввести в заблуждение, потому что на самом деле мы не создаём ничего нового (создаём мы с помощью ключевого слова data), а просто определяем синоним для уже существующего типа.

Если мы создадим функцию, которая преобразует строку в верхний регистр, и назовём её toUpperString, то можем дать ей сигнатуру типа toUpperString :: [Char] –> [Char] или toUpperString :: String –> String. Обе сигнатуры обозначают одно и то же, но вторая легче читается.

I’m trying to understand what the following type synonym from Yesod is doing.

type HtmlUrlI18n msg url = Translate msg -> Render url -> Html

I could not find an example in learn you some haskell or the haskell wikibook of a type synonym with -> present. Any links or explanations are much appreciated. Thanks.

asked Jul 8, 2012 at 18:48

David's user avatar

5

Its just a synonym for a (long to write down) function type. For example, the following should be valid Haskell

--Example of a function type synonym
type StrFn = String -> String

foo :: StrFn
foo s = s ++ "!"

--Example of a function type synonym with type parameters
type Fn a = a -> a

bar :: Fn String
bar s = s ++ "?"

answered Jul 9, 2012 at 12:58

hugomg's user avatar

hugomghugomg

67.8k24 gold badges160 silver badges246 bronze badges

2

Понравилась статья? Поделить с друзьями:
  • Hard worker синонимы
  • Hard skills синоним
  • Happy синонимы на английском
  • Happy синонимы и антонимы
  • Happiness синонимы на английском