Ran*_*ala 2 haskell module abstract-data-type
假设我有一个包含类型的模块:
module My where
data L a = Nil | Cons a (L a)
Run Code Online (Sandbox Code Playgroud)
模块导出具体的定义My以允许模式匹配等.是否有可能是另一个模块,比如Client以
抽象My的方式导入,L a即L a类型检查器禁止模式匹配值?
是; 你只需要使用导入列表:
module Client where
import My (L)
ok :: L Int
ok = undefined
bad :: L Int
bad = Cons 3 Nil
bad2 :: L Int -> Int
bad2 (Cons i _) = i
bad2 Nil = 0
Run Code Online (Sandbox Code Playgroud)
如果您尝试编译它,您将收到以下四个错误:
Client.hs:8:10: Not in scope: data constructor `Cons'
Client.hs:8:17: Not in scope: data constructor `Nil'
Client.hs:11:10: Not in scope: data constructor `Cons'
Client.hs:12:9: Not in scope: data constructor `Nil'
Run Code Online (Sandbox Code Playgroud)
如果您确实想要导入构造函数,则应指定L(..)或L(Cons)导入Cons但不导入Nil.
对于其他一些可以使用该import语句的方法,请查看HaskellWiki上的文章import(尽管文章没有提到导入数据类型及其构造函数).