newtype如何帮助隐藏任何东西? [英] How does newtype help hiding anything?
问题描述
真实世界haskell说:
Real world haskell says:
我们将使用newtype
声明隐藏解析器类型的细节
we will hide the details of our parser type using a newtype declaration
我不明白我们如何使用newtype隐藏任何东西。任何人都可以详述吗?
I don't get how we can hide anything using the newtype. Can anyone elaborate? What are we trying to hide and how do we do it.
data ParseState = ParseState {
string :: L.ByteString
, offset :: Int64 -- imported from Data.Int
} deriving (Show)
newtype Parse a = Parse {
runParse :: ParseState -> Either String (a, ParseState)
}
推荐答案
这个想法是将modules + newtypes结合起来,以防止人们看到我们如何实现内部事物。
The idea is to combine modules + newtypes to keep people from seeing the internals of how we implement things.
-- module A
module A (A, toA) where -- Notice we limit our exports
newtype A = A {unA :: Int}
toA :: Int -> A
toA = -- Do clever validation
-- module B
import A
foo :: A
foo = toA 1 -- Must use toA and can't see internals of A
这可以防止模式匹配和任意构造 A
。这让我们的 A
模块对 A
做一些假设,并且改变 A
逍遥法外!
This prevents from pattern matching and arbitrarily constructing A
. This let's our A
module make certain assumptions about A
and also change the internals of A
with impunity!
这非常好,因为在运行时, newtype
几乎没有像这样做的开销
This is particularly nice because at runtime the newtype
s are erased so there's almost no overhead from doing something like this
这篇关于newtype如何帮助隐藏任何东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!