cro*_*eea 4 constructor haskell 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]
Run Code Online (Sandbox Code Playgroud)
我四处寻找指定newtype的构造函数的方法.我意识到只能有一个,但我不明白为什么我可以指定它是什么.
例如,我可能只想将参数的前三个元素带到PolyRing值构造函数中.
我尝试where在newtype声明的末尾添加一个子句,但是没有编译.
我也尝试过:
(PolyRing xs) = PolyRing [2, 3, 5, 7]
Run Code Online (Sandbox Code Playgroud)
作为一个玩具的例子.我认为应该做的是忽略值构造函数的参数并始终具有值[2,3,5,7].代码编译,但我的"自定义"构造函数没有效果.
是否可以为newtype指定构造函数?
我认为你正在寻找的是一个智能构造函数.
PolyRing的基本大写构造函数不能超载.但你能做的就是:
polyRing :: (Num a, IntegerAsType n) => [a] -> PolyRing a n
polyRing = PolyRing . take 3
Run Code Online (Sandbox Code Playgroud)
或者,甚至更好:
polyRing :: (Num a, IntegerAsType n) => [a] -> Maybe (PolyRing a n)
polyRing (a:b:c:_) = Just $ PolyRing [a, b, c]
polyRing _ = Nothing
Run Code Online (Sandbox Code Playgroud)
为了防止有人PolyRing直接使用构造函数,文件顶部的模块导出声明可能如下所示:
module PolyRing (
PolyRing (), -- Export the PolyRing type but not constructor
polyRing -- Your smart constructor
) where
Run Code Online (Sandbox Code Playgroud)
在OO中,封装的单位是类,但在Haskell中,它是模块.