I've got the following piece of code that implements a monad. I'm trying to use it to simplify the setting of fields with more complex logic later on.
data Rec = Rec {
alpha :: Int,
beta :: Double,
} deriving (Show)
defaultRec = Rec 0 0 0
data Record r = Record { runRecord :: Rec -> (Rec, r) }
instance Monad Record where
return r = Record $ \s -> (s, r)
a >>= b = Record $ \s -> let (q, r) = runRecord a s in runRecord (b r) q
createRecord f = fst $ runRecord f defaultRec
changeAlpha x = Record $ \s -> (s { alpha = x }, ())
I would use the code like this:
myRecord = createRecord (changeAlpha 9)
This code works, but I'd like to use Template Haskell to simplify the changeAlpha function. It would be great to have something like this:
changeBeta x = $(makeChange beta) x
Now, I've gone as far as this:
changeBeta x = Record $ $([| \z -> \s -> (s { beta = z }, ()) |]) x
But as soon as I change it to this:
changeBeta f x = Record $ $([| \z -> \s -> (s { f = z }, ()) |]) x
I get this:
TestTH.hs:21:49: `f' is not a (visible) constructor field name
No variations work. Is this possible?