我已经编写了这个简单的模块,其中公开了ADT Point和Shape:
module Lib(Point, Shape) where
data Point = Point Float Float deriving (Show)
data Shape = Circle Point Float | Rectangle Point Point deriving (Show)
Run Code Online (Sandbox Code Playgroud)
然后,我写了一个main定义了一个实例Circle:
module Main where
import Lib
main :: IO ()
main = do
let circle = Circle 0.0 0.0 10.0
print ""
Run Code Online (Sandbox Code Playgroud)
但是,它无法编译错误消息:
Data constructor not in scope:
Circle :: Double -> Double -> Double -> t
|
7 | let circle = Circle 0 0 10
| ^^^^^^
Run Code Online (Sandbox Code Playgroud)
从我看过的书中,我给人的印象是,Haskell编译器会根据ADT定义来推断类型,例如,我应该能够像这样编写main并进行编译:
module Main where
import Lib
main :: IO ()
main = do
let circle = Circle 0 0 10
print ""
Run Code Online (Sandbox Code Playgroud)
但这然后失败,并显示类似消息:
Data constructor not in scope:
Circle :: Integer -> Integer -> Integer -> t
|
7 | let circle = Circle 0 0 10
| ^^^^^^
Run Code Online (Sandbox Code Playgroud)
有谁可以帮我解决这个问题,让我理解为什么它不起作用?
您仅使Lib模块导出类型,而不使相应的数据构造函数导出,可以使用以下命令导出这些类型:
module Lib(Point(..), Shape(..)) where
-- ...Run Code Online (Sandbox Code Playgroud)
或更详细:
module Lib(Point(Point), Shape(Circle, Rectangle)) where
-- ...Run Code Online (Sandbox Code Playgroud)
请注意,由于您Circle使用Point和,因此上述方法仍无法正常工作Float。因此应该是:
let circle = Circle (Point 0 0) 10Run Code Online (Sandbox Code Playgroud)