2011-09-02 121 views
4

我有一个类型定义构造函数NEWTYPE

class IntegerAsType a where 
    value :: a -> Integer 

data T5 
instance IntegerAsType T5 where value _ = 5 

newtype (Num a, IntegerAsType n) => PolyRing a n = PolyRing [a] 

我环顾四周,换一种方式来指定NEWTYPE的构造。我意识到只能有一个,但我不明白为什么我可以指定它是什么。

例如,我可能只想将参数的前三个元素带到PolyRing值构造函数中。

我试着在newtype声明的结尾处使用where子句添加,但没有编译。

我也尝试:

(PolyRing xs) = PolyRing [2, 3, 5, 7] 

作为玩具的例子。我认为这应该做的是忽略值构造函数的参数,并始终具有值[2,3,5,7]。代码编译,但我的“自定义”构造函数没有效果。

是否可以指定新类型的构造函数?

+0

我不明白这个问题。当你执行'newtype PolyRing a n = PolyRing [a]'时,你指定了构造函数。如果你想调用构造函数,可以使用'newtype PolyRing a n = SomethingElse [a]'。 – sepp2k

+0

我不想重命名它,我想在施工过程中做某些事情。确切地说, – crockeea

回答

7

我认为你要找的是Smart constructor

PolyRing的基本大写的构造函数不能被重载。但你可以做到这一点:

polyRing :: (Num a, IntegerAsType n) => [a] -> PolyRing a n 
polyRing = PolyRing . take 3 

,或者甚至更好:

polyRing :: (Num a, IntegerAsType n) => [a] -> Maybe (PolyRing a n) 
polyRing (a:b:c:_) = Just $ PolyRing [a, b, c] 
polyRing _   = Nothing 

为了防止有人直接使用PolyRing构造,在该文件可能看起来像的顶端的模块出口报关这个:

module PolyRing (
PolyRing(), -- Export the PolyRing type but not constructor 
polyRing  -- Your smart constructor 
) where 

在OO中,封装单元是类,但在Haskell中,它是模块。

+0

。谢谢! – crockeea