现实世界haskell说:
我们将使用newtype隐藏解析器类型的详细信息 声明
我不知道如何使用newtype隐藏任何内容。谁能详细说明?我们试图隐藏什么,我们该怎么做。
data ParseState = ParseState {
string :: L.ByteString
, offset :: Int64 -- imported from Data.Int
} deriving (Show)
newtype Parse a = Parse {
runParse :: ParseState -> Either String (a, ParseState)
}
答案 0 :(得分:12)
我们的想法是结合模块+新类型,以防止人们看到我们如何实现事物的内部。
-- 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
的内部而不受惩罚!
这是特别好的,因为在运行时,newtype
被删除,所以几乎没有做这样的事情的开销
答案 1 :(得分:6)
您通过不导出内容隐藏详细信息。所以有两个比较。一个是出口而非出口:
-- hidden: nothing you can do with "Parse a" values -- though
-- you can name their type
module Foo (Parse) where
newtype Parse a = Parse { superSecret :: a }
-- not hidden: outsiders can observe that a "Parse a" contains
-- exactly an "a", so they can do anything with a "Parse a" that
-- they can do with an "a"
module Foo (Parse(..)) where
newtype Parse a = Parse { superSecret :: a }
另一个更微妙,是RWH可能试图强调的那个,那是type
与newtype
:
-- hidden, as before
module Foo (Parse) where
newtype Parse a = Parse { superSecret :: a }
-- not hidden: it is readily observable that "Parse a" is identical
-- to "a", and moreover it can't be fixed because there's nothing
-- to hide
module Foo (Parse) where
type Parse a = a