I am writing a framework where the main function asks the user for a function like a -> [b] .
However, since this function can be quite complex, its implementation may look something like this:
fn a = extractPartOfAAndConvert a ++ extractAnotherPartofAAndConvert a
That's why I thought using Reader might be a nice idiomatic idea to deal with this. However, at the same time, I understand that some people may not want to use a monad.
During the experiments, I developed this solution:
class Iso ab where isoFrom :: a -> b isoTo :: b -> a instance Iso aa where isoFrom = id isoTo = id instance Iso (a -> b) (Reader ab) where isoFrom f = reader f isoTo m = runReader m
This, in turn, allows me to:
testCallback :: MyState -> Callback -> MyState testCallback myState cb = cb myState -- The important signature testCallbackGeneric :: Iso Callback a => MyState -> a -> MyState testCallbackGeneric myState cb = (isoTo cb) myState callbackFunction :: Callback callbackFunction s = s + 10 callbackMonad :: Reader MyState MyState callbackMonad = do x <- ask return $ x - 10 ----------- let myStateA = testCallback myState callbackFunction -- let myStateB = testCallback myState callbackMonad -- won't work, obviously let myStateC = testCallbackGeneric myState callbackFunction let myStateD = testCallbackGeneric myState callbackMonad
However, I really feel like I'm reinventing the wheel.
Is there a way to express Reader equivalence in order to easily write such general functions without resorting to creating my own type class?
haskell
Bartek banachewicz
source share