[英]Haskell-(Type declaration) what is “a”?
This is perhaps a very basic question, but, nevertheless, it does not seem to have been covered on SO. 这可能是一个非常基本的问题,但是,它似乎没有涵盖在SO上。
I recently took up Haskell and up until now type declarations consisted of mostly the following: 我最近接受了Haskell,直到现在,类型声明主要包括以下内容:
Int
Bool
Float
etc, etc
Now I am getting into lists and I am seeing type declarations that use a
, such as in the following function that iterates through an associative list: 现在我进入列表,我看到使用a
类型声明,例如在以下函数中迭代关联列表:
contains :: Int -> [(Int,a)] -> [a]
contains x list = [values | (key,values)<-list, x==key]
Can someone provide an explanation as to what this a
is, and how it works? 有人可以提供一个解释,这是什么a
是,它是如何工作的? From observation it seems to represent every type. 从观察来看,它似乎代表了每一种类型。 Does this mean I can input any list of any type as parameter? 这是否意味着我可以输入任何类型的任何列表作为参数?
Yes, you're right, it represents "any type" - the restriction being that all a
s in a given type signature must resolve to the same type. 是的,你说得对,它代表“任何类型” -的限制是所有的a
在给定类型签名s必须解析为同一类型。 So you can input a list of any type, but when you use contains
to look up a value in the list, the value you look up must be the same type as the elements of the list - which makes sense of course. 因此,您可以输入任何类型的列表,但是当您使用contains
来查找列表中的值时,您查找的值必须与列表中的元素类型相同 - 这当然是有道理的。
In Haskell, uppercase types are concrete types ( Int
, Bool
) or type constructors ( Maybe
, Either
) while lowercase types are type variables . 在Haskell中,大写类型是具体类型( Int
, Bool
)或类型构造函数( Maybe
, Either
),而小写类型是类型变量 。 A function is implicitly generic in all the type variables it uses, so this: 函数在它使用的所有类型变量中都是隐式通用的,所以这样:
contains :: Int -> [(Int, a)] -> [a]
Is shorthand for this*: 这是*的简写:
contains :: forall a. Int -> [(Int, a)] -> [a]
In C++, forall
is spelled template
: 在C ++中, forall
是拼写template
:
template<typename a>
list<a> contains(int, list<pair<int, a>>);
In Java and C#, it's spelled with angle brackets: 在Java和C#中,它用尖括号拼写:
list<a> contains<a>(int, list<pair<int, a>>);
Of course, in these languages, generic type variables are often called T
, U
, V
, while in Haskell they're often called a
, b
, c
. 当然,在这些语言中,泛型类型变量通常称为T
, U
, V
,而在Haskell中,它们通常称为a
, b
, c
。 It's just a difference of convention. 这只是传统的差异。
* This syntax is enabled by the -XExplicitForAll
flag in GHC, as well as other extensions. *此语法由GHC中的-XExplicitForAll
标志以及其他扩展启用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.