我有一种类型
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]。代码会编译,但我的“自定义”构造函数没有任何作用。
可以为newtype指定构造函数吗?
发布于 2011-09-03 06:26:07
我想你要找的是一个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中,封装的单位是模块。
https://stackoverflow.com/questions/7289627
复制相似问题