为了练习,我在一个名为“Queue”的模块中实现了一个队列数据类型。我的数据类型也称为“队列”,它唯一的值构造函数也是如此:
module Queue (Queue, enq, emptyQueue) where
data Queue a = Queue {
inbox :: [a],
outbox :: [a]
} deriving (Eq, Show)
emptyQueue :: Queue a
emptyQueue = Queue [] []
enq :: a -> Queue a -> Queue a
enq x (Queue inb out) = Queue (x:inb) out
-- other function definitions (irrelevant here)...
据我了解,因为我在导出语句中写了Queue
, not Queue(..)
or Queue(Queue)
,所以我不希望我的数据类型的值构造函数被模块导出。这正是我想要的,出于封装目的:用户不应该直接使用值构造函数;只有emptyQueue
, enq
, 和我界面中的其他功能。
但是(对于经验丰富的 Haskeller 来说,我的问题的解决方案可能很明显),如果我在 GHCi 中加载我的模块,我可以直接使用值构造函数。
$ ghci Queue.hs
GHCi, version 7.8.4: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Queue ( Queue.hs, interpreted )
Ok, modules loaded: Queue.
λ> Queue [1] [2]
Queue {inbox = [1], outbox = [2]}
如上所述,这是不希望的。我究竟做错了什么?