Haskell 如何调用不带实例参数的函数?
假设您有一个类:Haskell 如何调用不带实例参数的函数?,haskell,Haskell,假设您有一个类: class AClass a where func:: Int instance AClass SomeTree where func = 0 instance AClass Double where func = 1 如何调用函数func?neutral::Int,应该可以,因为信息都是从输入类型和输出类型收集的。没有不带参数的函数func这里只是一个Int。像任何其他Int一样使用它。更大的问题是,您不能将func定义为在某种程度上不涉及a的类型。@TVS
class AClass a where
func:: Int
instance AClass SomeTree where
func = 0
instance AClass Double where
func = 1
如何调用函数func?
neutral::Int
,应该可以,因为信息都是从输入类型和输出类型收集的。没有不带参数的函数func
这里只是一个Int
。像任何其他Int
一样使用它。更大的问题是,您不能将func
定义为在某种程度上不涉及a
的类型。@TVSuchty:然后您可以使用TypeApplications
:func@Double
。您可以将{-\LANGUAGE TypeApplications}
添加到您的文件中,它启用了一个新的@
符号来提供类型参数。然后,您可以编写func@SomeTree
,这将产生0,或者func@Double
,这将产生1。请看,您能否提供一个更详细的示例,说明您正在尝试执行的操作?条形类型约束有何神奇之处?谢谢你的回答<代码>∀ a.正是您在函数中隐含的内容,如sum::Num a=>[a]->a
,它实际上是sum::∀ A.数值a=>[a]->a
。区别在于显式∀
(也称为forall
)将a
引入作用域,使其可以在函数体中使用,如这里的func@a
。
{-# LANGUAGE AllowAmbiguousTypes, TypeApplications #-}
class AClass a where
func :: Int
instance AClass SomeTree where
func = 0
instance AClass Double where
func = 1
foo :: Int
foo = func @SomeTree + func @Double
{-# LANGUAGE ScopedTypeVariables, UnicodeSyntax #-}
bar :: ∀ a . AClass a => a -> Int
bar _ = func @a