为什么我能够使用我的值构造函数,即使我不导出它? [英] Why am I able to use my value constructor even though I don't export it?

查看:147
本文介绍了为什么我能够使用我的值构造函数,即使我不导出它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实践中,我在一个名为Queue的模块中实现了一个队列数据类型。我的数据类型也被称为Queue,就像它的唯一值构造函数一样:
$ b

  module Queue (Queue,enq,emptyQueue)其中

数据Queue a = Queue {
inbox :: [a],
outbox :: [a]
}派生( Eq,Show)

emptyQueue ::队列a
emptyQueue =队列[] []

enq :: a - >队列a - >排队
enq x(Queue inb out)= Queue(x:inb)out

- 其他函数定义(无关)...

就我所知,因为我写了 Queue ,而不是 Queue(..) Queue(Queue),我不希望我的数据类型的值构造函数是由模块导出。这正是我想要的,因为封装的目的:用户不应该能够直接使用值构造函数;只有 emptyQueue enq 和我的界面中的其他功能。



但是(对于我的问题的解决方案对于经验丰富的Haskeller可能是显而易见的),如果我将模块加载到GHCi中,我可以直接使用值构造函数。

  $ ghci Queue.hs 
GHCi,版本7.8.4:http://www.haskell.org/ghc/:?寻求帮助
加载包ghc-prim ...链接...完成。
加载包integer-gmp ...链接...完成。
加载程序包库...链接...完成。
[1的1]编译队列(Queue.hs,解释)
好​​了,模块加载:队列。

λ> Queue [1] [2]
Queue {inbox = [1],outbox = [2]}

如上所述,这是不可取的。我做错了什么?

解决方案

你没有做错什么。只是,为方便起见,ghci忽略了它加载的模块的范围规则。



如果您想查看通常可用的内容,您可以

 :m -Queue 
:m + Queue

您可以稍后使用 $ b

 :m *队列返回一切都可用模式

另见官方文档中提示的范围真的很重要


For practice, I'm implementing a queue data type in a module called "Queue". My data type is also called "Queue", as is its only value constructor:

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)...

As far as I understand, because I wrote Queue, not Queue(..) or Queue(Queue) in the export statement, I don't expect the value constructor of my data type to be exported by the module. This is exactly what I want, for encapsulation purposes: users should not be able to use the value constructor directly; only emptyQueue, enq, and the other functions in my interface.

However (and the solution to my problem may be obvious to seasoned Haskellers), if I load my module in GHCi, I'm able to use the value constructor directly.

$ 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]}

As stated above, this is undesirable. What am I doing wrong?

解决方案

You are doing nothing wrong. It's just that, for convenience, ghci ignores scoping rules on modules it loads.

If you want to see what would normally be available, you can

:m -Queue
:m +Queue

You can later return to the "everything is available" mode with

:m *Queue

See also What's really in scope at the prompt? in the official documentation.

这篇关于为什么我能够使用我的值构造函数,即使我不导出它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆