haskell类属性检查

时间:2011-03-17 13:46:59

标签: class haskell properties

我想要一个检查类实例属性的函数:

class ListWithAtLeastOneElement a where
   list :: [a]
   check :: Bool
   check = (length list) >= 1

但在GHC中编译时出现此错误: “类方法'检查'没有提到ListWithAtLeastOneElement类的类型变量a当检查类方法时:check :: Bool在'ListWithAtLeastOneElement'的类声明中”

有没有更好的方法来做我想要的,或者在GHC中编译它的方法?

3 个答案:

答案 0 :(得分:3)

你似乎认为Haskell中的一个类就像一个OO语言的类。事实并非如此。您应该使用数据类型或新类型或键入同义词。

newtype NonemptyList a = List1 [a]

fromList :: [a] -> Maybe (NonemptyList a)
fromList []       = Nothing
fromList xs@(_:_) = Just $ List1 xs

check :: NonemptyList a -> Bool
check (List1 xs) = length xs >= 1

答案 1 :(得分:2)

正如jmg所说,这不是有效的Haskell所以它很好GHC没有编译它!如果您已经习惯了Java,那么您应该考虑Haskell的类型类,如Java接口。如果这没有用,那么也许你应该阅读LYAH's chapter on classes

对于你的问题,你似乎想要一个永远不会为null的类似列表的数据类型。您不需要测试这样的属性,您可以通过使用数据静态地确保它 永远不会为空的类型:

-- Notice this data type can never have zero 'a' values!
data NonEmptyList a = NEL a (NonEmptyList a) | Singleton a

-- We can define basic operators for this, just like list has
-- You can't pattern match with them, but there are work-arounds for that if you want to ask
(.:) = NEL  -- concatenate non-empty lists

nelHead :: NonEmptyList a -> a 
nelHead (NEL a _) = a
nelHead (Singleton a) = a

nelTail :: NonEmptyList a -> Maybe (NonEmptyList a)
nelTail (NEL _ b) = Just b
nelTail _ = Nothing

nelTake :: Int -> NonEmptyList a -> NonEmptyList a
nelTake 1 (NEL a _) = Singleton a
nelTake 1 (Singleton a) = Singleton a
nelTake n (NEL a rest) = a .: nelTake (n-1) rest

nelDrop :: Int -> NonEmptyList a -> NonEmptyList a
nelDrop _ (Singleton _) = error "Perhaps I should have used the 'maybe' type"
nelDrop 1 (NEL a r) = r
nelDrop n (NEL a r) = nelDrop (n-1) r

依此类推。值得注意的是nelTakenelDrop是部分的,但nelHead是完全有趣的,因为这与常规列表相反。

答案 2 :(得分:1)

你需要检查一个功能

检查:: [a] - >布尔

也就是说,对于非空列表而不是类,数据类型更好,Haskell中的类与面向对象语言中的类没有相同的用途。