我有以下实现 monad 的代码。我正在尝试使用它来简化稍后具有更复杂逻辑的字段设置。
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 }, ())
我会使用这样的代码:
myRecord = createRecord (changeAlpha 9)
此代码有效,但我想使用 Template Haskell 来简化 changeAlpha 函数。有这样的东西会很棒:
changeBeta x = $(makeChange beta) x
现在,我已经做到了:
changeBeta x = Record $ $([| \z -> \s -> (s { beta = z }, ()) |]) x
但是,一旦我将其更改为:
changeBeta f x = Record $ $([| \z -> \s -> (s { f = z }, ()) |]) x
我明白了:
TestTH.hs:21:49: `f' is not a (visible) constructor field name
没有变化工作。这可能吗?