本文介绍了为什么ghci可以查看非导出的类型和构造函数?我该如何解决它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Haskell的新手。这里有一些简单的代码:

  module Src 
( - 'Answer'类型不会被导出
Shape(Circle), - 即'Rectangle'数据构造函数未导出
Point(..),
area,
nudge
)其中

data答案=是|不显示(显示)

数据点=点浮点数浮点数(显示)

数据形状=圆点浮点数|矩形Point Point
派生(显示)

区域:: Shape - > Float
area(Circle _ r)= pi * r ^ 2
area(Rectangle(Point x1 y1)(Point x2 y2))=(abs $ x2 - x1)*(abs $ y2 - y1 )

nudge :: Shape-> Float-> Float-> Shape
nudge(Rectangle(Point x1 y1)(Point x2 y2))dx dy = Rectangle
(点(x1 + dx)(y1 + dy))(点(x2 + dx)(y2 + dy))
nudge(Circle(Point xy)r)dx dy = Circle(Point(x + dx )(y + dy))r

我隐藏了 Answer 类型和 Rectangle 构造函数。但是当我加载 Src.hs 文件时,ghci仍然会看到它们:

  ghci> :l src 
[1的1]编译源(src.hs,解释)
好​​了,模块加载:Src。
ghci>让a =是
ghci> a

ghci> :t a
a ::回答
ghci>让r = Rectangle(Point 0 0)(Point 100 100)
ghci> r
Rectangle(Point 0.0 0.0)(Point 100.0 100.0)
ghci> :t r
r :: Shape
ghci>

为什么发生这种情况,我该如何解决它?



如果你希望代码的行为就像从另一个文件导入一样,你可以使用 import 而不是:l 。那么它只会允许访问支持的定义。


I am a novice in Haskell. Here's some simple code:

module Src
(   -- The 'Answer' type isn't exported
    Shape(Circle), -- i.e 'Rectangle' data constructor isn't exported
    Point(..),
    area,
    nudge
) where

data Answer = Yes | No deriving (Show)

data Point = Point Float Float deriving (Show)

data Shape = Circle Point Float | Rectangle Point Point
    deriving (Show)

area :: Shape -> Float
area (Circle _ r) = pi * r ^ 2
area (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1)

nudge::Shape->Float->Float->Shape
nudge (Rectangle(Point x1 y1)(Point x2 y2)) dx dy = Rectangle 
    (Point (x1 + dx) (y1 + dy)) (Point (x2 + dx) (y2 + dy))
nudge (Circle (Point x y) r) dx dy  = Circle (Point(x + dx) (y + dy)) r

I've hidden the Answer type and the Rectangle constructor. But when I load the Src.hs file, ghci still sees them:

ghci> :l src
[1 of 1] Compiling Src ( src.hs, interpreted )
Ok, modules loaded: Src.
ghci> let a = Yes
ghci> a
Yes
ghci> :t a
a :: Answer
ghci> let r = Rectangle (Point 0 0) (Point 100 100)
ghci> r
Rectangle (Point 0.0 0.0) (Point 100.0 100.0)
ghci> :t r
r :: Shape
ghci>

Why did this happen and how can I fix it?

解决方案

Yes, when you load a file in GHCi like that, you can access anything defined in that file regardless of whether or not it is exported. This way expressions you write into GHCi behave exactly like they would inside the loaded file. So you can use GHCi to quickly test an expression that you mean to use inside the file or to quickly test a function defined in the file even if it is private.

If you want the code to behave as if imported from another file, you can use import instead of :l. Then it will only allow access to expported definitions.

这篇关于为什么ghci可以查看非导出的类型和构造函数?我该如何解决它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 03:54