How does newtype help hide something?

The real world of haskell says:

we will hide the details of our parser using the new type

I don’t understand how we can hide something using a new type. Can anyone clarify? What we are trying to hide and how 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) } 
+6
source share
2 answers

The idea is to combine + newtypes modules so people don’t see the insides 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 

This prevents pattern matching and arbitrary construction of A This allows our module A to make certain assumptions about A , as well as to change the internal elements of A with impunity!

This is especially good because at runtime newtype erases, so there is almost no overhead to doing something like this

+12
source

You hide details without exporting things. So there are two comparisons. One is exported and not exported:

 -- 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 } 

The other is thinner, and one RWH is probably trying to highlight, and this is type vs. 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 nothing -- to hide module Foo (Parse) where type Parse a = a 
+6
source

Source: https://habr.com/ru/post/957719/


All Articles