Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
Shoe Avatar asked Dec 14 '14 23:12

Shoe


2 Answers

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'
like image 70
leftaroundabout Avatar answered Sep 27 '22 21:09

leftaroundabout


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
like image 33
glguy Avatar answered Sep 27 '22 20:09

glguy