[英]How do you use TypeApplications in Haskell?
With -XTypeApplications
in GHC 8.0, you can specify types explicitly with @
preceding function arguments. 使用GHC 8.0中的
-XTypeApplications
,可以使用@
preceding函数参数显式指定类型。 What types does it exactly specify, especially when several @
are introduced? 它准确指定了哪些类型,特别是当引入了几个
@
时?
If you look at the type of a function 如果你看一个函数的类型
elem :: (Foldable t, Eq a) => a -> t a -> Bool
we see it has two polymorphic variables, t
and a
. 我们看到它有两个多态变量,
t
和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
. 似乎在上下文中引入的变量 - 类型类约束在哪里 - 影响顺序,因此第一个
@
指定t
,第二个指定a
。 In functions without context variables 在没有上下文变量的函数中
const :: a -> b -> a
the order is more obvious, the a
is first and b
is second. 顺序更明显,
a
是第一个, b
是第二个。 As Cactus mentioned in a comment above, you can also use explicit foralls to specify the order yourself. 正如Cactus在上面的评论中提到的,您也可以使用显式的foralls来自己指定顺序。
myConst :: forall b a. a -> b -> a
Now the first type application will specify the b
and the second the a
. 现在第一个类型的应用程序将指定
b
,第二个应用程序将指定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']
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从列表元素中推断出Char
,因此@Char
可以省略@Char
。
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. 如果GHC能够推断的多态参数恰好是第一个你可以利用
-XPartialTypeSignatures
,它允许你在类型签名中使用_
包括类型应用程序签名,告诉GHC只是推断[部分]类型,以减少冗长。
f @_ @[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.