List Haskell:类型类和实例
我在类型类和从中创建实例方面遇到了一些可能很简单的问题。 我试图为Haskell列表中的一些函数和Set函数创建一个typeclass,比如“size”、“null”和“filter”。 我已经通过以下方式获得了“大小”和“空值”:List Haskell:类型类和实例,list,haskell,set,instance,typeclass,List,Haskell,Set,Instance,Typeclass,我在类型类和从中创建实例方面遇到了一些可能很简单的问题。 我试图为Haskell列表中的一些函数和Set函数创建一个typeclass,比如“size”、“null”和“filter”。 我已经通过以下方式获得了“大小”和“空值”: module Main where import qualified Data.List as DL import qualified Data.Set as DS class Interface a where null' :: [a
module Main where
import qualified Data.List as DL
import qualified Data.Set as DS
class Interface a where
null' :: [a] -> Bool
size' :: a -> Int
instance Interface [a] where
null' xs = DL.null xs
size' xs = DL.length xs
instance Interface (DS.Set a) where
null' x = DS.null x
size' x = DS.size x
这个函数在我测试的时候就可以工作
过滤函数
class Interface a where
null' :: [a] -> Bool
size' :: a -> Int
filter' :: (a-> Bool) -> a -> a
instance Interface [a] where
null' xs = DL.null xs
size' xs = DL.length xs
filter' f xs = DL.filter f xs
我现在遇到的问题如下:
ue4.hs:17:30:
Couldn't match type ‘a’ with ‘[a]’
‘a’ is a rigid type variable bound by
the instance declaration at ue4.hs:14:10
Expected type: a -> Bool
Actual type: [a] -> Bool
Relevant bindings include
xs :: [a] (bound at ue4.hs:17:15)
f :: [a] -> Bool (bound at ue4.hs:17:13)
filter' :: ([a] -> Bool) -> [a] -> [a] (bound at ue4.hs:17:5)
In the first argument of ‘filter’, namely ‘f’
In the expression: filter f xs
据我所知,问题出在函数内部。它需要获取一个正常值,以便遍历映射并使用所有值对函数求值,然后将它们放入结果列表中,该列表将由过滤器返回。但是实例声明中的[a]将所有内容都读取为列表,而它不应该这样做
如果我把
filter' :: (a-> Bool) -> [a] -> [a]
在类中,我想我让列表过滤器工作了,但是我在设置过滤器时遇到了问题,Typeclass的感觉丢失了
有人知道如何处理或修复这个问题吗?我必须接受什么样的类定义
通过使用,我已经得到了“大小”和“空值”
真的吗?在我看来这是个错误。null'
的定义非常不可靠。对于列表,您有:
null' :: [[a]] -> Bool
null' :: [Set a] -> Bool
对于集
,您有:
null' :: [[a]] -> Bool
null' :: [Set a] -> Bool
我肯定那不是你想要的
也许这样更合适:
module Main where
import qualified Data.List as DL
import qualified Data.Set as DS
class Interface a where
null' :: a x -> Bool
size' :: a x -> Int
filter' :: (x -> Bool) -> a x -> a x
instance Interface [] where
null' = DL.null
size' = DL.length
filter' = DL.filter
instance Interface DS.Set where
null' = DS.null
size' = DS.size
filter' = DS.filter
请注意,我已将您的接口更改为应用于更高类型的类型,因此,
[]
本身不是类的实例,[]
本身是类的实例。这可能不是您想要的,但它确实允许您实现映射
(但遗憾的是,Set
).谢谢!我理解对了吗?当我编写一个带有参数a的类时,在函数的定义中,我写“a x”,这意味着,例如在我的列表实例中,我将“a x”解释为列表?如果我使用Set接口,“a x”将被解释为一个集合?因此在过滤函数中,solo“x“只是指任何类型,对于Int列表,例如Int?提前感谢,我仍在尝试获取这些概念:)。这正是我想要的,我想我没有正确理解接口中参数的用法。类型[x]
只是编写类型[]x
的另一种方式,因此当您有[Int]
并尝试对a x
进行模式匹配时,首先将其写为[]Int
,然后得到a=[]
和x=Int
。很少有其他编程语言能让您拥有更高级的类型,比如[]
和Set
。在大多数其他语言中,[Int]
将是一种类型,但更高级的类型构造函数[]
将不是一种类型。好的,我得到了:)。命令式语言很难理解。非常感谢@rehne93:这与命令式语言与函数式语言无关:它只是关于更高级类型的存在。你可以把HKT放在命令式语言中。