7

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?

Shoe
  • 74,840
  • 36
  • 166
  • 272

2 Answers2

10

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'
leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
2

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
glguy
  • 1,090
  • 7
  • 8