定义newtype的构造函数

时间:2011-09-02 22:02:06

标签: haskell constructor newtype

1 个答案:

答案 0 :(得分: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中,它是模块。

相关问题