Why is the new type usually used instead of the state monad type

Almost all examples I've seen in State

Monad have been wrapped inside newtype

.

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import Control.Monad.State
import Control.Applicative

data Bazzar 
  = Bazzar {
    valueOne :: Int      
  , valueTwo :: Int      
  }

newtype BazState a = BazState { unBazify :: State Bazzar a } 
  deriving (Functor, Applicative, Monad, MonadState Bazzar)

      

Is there any reason why I shouldn't just create a type alias?

type BazState a = State Bazzar a

      

I understand that the goal newtype

is to distinguish between two different uses for the same type of data structure, for example overriding class classes for existing types, or if you want to distinguish the use of that type from normal behavior. Or implement additional classes to use this class

If you are not doing any of the above, is newtype

it just unnecessary recourse in this case?

+3


source to share


1 answer


In addition to being able to define instances for the newtype, you can use it as a "private constructor" API for your library. This way, you export a single type without any constructors, along with functions that act as primitives and combinators so that users of your library cannot create invalid values ​​for your type. This also means that if you're careful enough, you can change the underlying structure without breaking the external API. A great example of this is Neil Mitchell, who said in a recent post about modifying the Shake build system to use the monadContinuation

: / p>



The cool thing about Haskell is that I was able to completely replace the base Shake monad Action

from StateT/IO

, to ReaderT/IO

, to ReaderT/ContT/IO

without breaking any Shake users. Haskell allows me to create efficient and flexible abstractions.

+3


source







All Articles