Export only getter or setter from a module

534 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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'
0
On

If you want to only generate Getter and Fold optics (as appropriate) you can use the new generateUpdateableOptics setting

{-# LANGUAGE TemplateHaskell #-}
import Control.Lens

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

let rules = set generateUpdateableOptics False lensRules in
  makeLensesWith rules ''Counter

-- Generates:
-- count :: Getter Counter Int