Search code examples
pointershaskelltypesghc

How would I make GHC.Ptr an instance of Monad?


This is what I have so far:

instance Monad Ptr where
    return = pure
    (>>=) (Ptr t) f = f t 

The error being thrown is:

    • Couldn't match a lifted type with an unlifted type
      When matching types
        a :: *
        GHC.Prim.Addr# :: TYPE 'GHC.Types.AddrRep
    • In the first argument of ‘f’, namely ‘t’
      In the expression: f t
      In an equation for ‘>>=’: (>>=) (Ptr t) f = f t
    • Relevant bindings include
        f :: a -> Ptr b (bound at RegionalMemory.hs:16:19)
        (>>=) :: Ptr a -> (a -> Ptr b) -> Ptr b
          (bound at RegionalMemory.hs:16:5)
   |
16 |     (>>=) (Ptr t) f = f t
   |                         ^

I do not quite understand this error. What am I doing wrong here?


Solution

  • t is not of type a, but an Addr#ess, so you don't. Indeed, the Ptr data type is defined as [Haskell-src]:

    data Ptr a = Ptr Addr#
      deriving ( Eq  -- ^ @since base-2.01
               , Ord -- ^ @since base-2.01
               )
    

    The a does not tell what the type of the value wrapped in the data constructor is, it tells what kind of thing the address refers to.

    So we can not make this work, we don't get the "result" of the address to pass as parameter.