Search code examples
haskellinvariantshaskell-lenslenses

Export only getter or setter from a module


Is there a way for me to only export specific getters xor setters from a module with a lens?

For example, let's assume a data structure that has an invariant of being always >= 0, being modified only by incrementing it and being created only with an initial value of 0:

module Something
    ( Counter
    -- export only `count` getter
    , make
    , increment
    ) where

data Counter = Counter { _count :: Int } deriving (Eq)
makeLenses ''Positive

make :: Counter
make = Counter 0

increment :: Counter -> Counter
increment c = c ^. count %~ (+1)

how would I be able to only export the count getter?


Solution

  • A lens isn't, in fact, "a getter and a setter", it just happens to be isomorphic to such a pair. So you can't just export one of them, rather you have to define something new and export that. Fortunately, this is extremely simple:

    data Counter = Counter { _count' :: Int } deriving (Eq)
    makeLenses ''Counter
    
    count :: Getter Counter Int
    count = count'