您如何在Haskell中使用TypeApplications? [英] How do you use TypeApplications in Haskell?
问题描述
使用GHC 8.0中的-XTypeApplications
,可以使用@
前面的函数参数显式指定类型.它确切指定了什么类型,特别是在引入几个@
时?
With -XTypeApplications
in GHC 8.0, you can specify types explicitly with @
preceding function arguments. What types does it exactly specify, especially when several @
are introduced?
推荐答案
如果您查看函数的类型
elem :: (Foldable t, Eq a) => a -> t a -> Bool
我们看到它有两个多态变量,t
和a
.这些变量是应用程序指定的@
类型.似乎上下文中引入的变量(类型类约束所在的位置)会影响顺序,因此第一个@
指定t
,第二个a
指定.在没有上下文变量的函数中
we see it has two polymorphic variables, t
and a
. These variables are what the @
type applications specify. It seems that variables introduced in the context — where typeclass constraints go — affect order, and hence the first @
specifies the t
, and the second the a
. In functions without context variables
const :: a -> b -> a
顺序更明显,a
是第一位,b
是第二位.正如仙人掌在上面的评论中提到的,您还可以使用显式的forall自己指定订单.
the order is more obvious, the a
is first and b
is second. As Cactus mentioned in a comment above, you can also use explicit foralls to specify the order yourself.
myConst :: forall b a. a -> b -> a
现在,第一种类型的应用程序将指定b
,第二种类型的应用程序将指定a
.
Now the first type application will specify the b
and the second the a
.
您可能会遇到需要指定类型的问题,尤其是在使用重载字符串或列表的情况下
You may run into this problem of needing to specify types particularly if you're using overloaded strings or lists
elem c "abc...xyz" -- What string type is this?
elem c ['a' .. 'z'] -- What list constructor is this?
因此,我们使用显式类型的应用程序
therefore we use explicit type applications
elem @[] @Char c ['a' .. 'z']
在这种情况下,我们仅必须指定@[]
,并说这是[]
列表类型构造函数",因为GHC从列表元素中推断出Char
,所以@Char
可以在这里省略.
in this case we only have to specify the @[]
and say "this is a []
list type constructor" because GHC infers Char
from the list elements, so @Char
can be omitted here.
如果多态参数GHC能够推断碰巧首先出现,则可以利用-XPartialTypeSignatures
,它允许您在类型签名(包括类型应用程序签名)中使用_
,告诉GHC只是推断出[一部分]类型,使事情变得不太冗长.
If a polymorphic argument GHC is able to infer happens to come first you can leverage -XPartialTypeSignatures
which allows you to use _
in type signatures including type application signatures, telling GHC to just infer that [part of the] type, to make things less verbose.
f @_ @[]
这篇关于您如何在Haskell中使用TypeApplications?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!