我想知道是否有一个可以跟踪应用操作次数的
Applicative
。我尝试按照以下方式实现它:import Control.Applicative
main :: IO ()
main = print $ run 1 $ (,,,) <$> FromInt id <*> FromInt id <*> FromInt id <*> FromInt id
data FromInt a = FromInt (Int -> a)
run :: Int -> FromInt a -> a
run i (FromInt f) = f i
instance Functor FromInt where
fmap g (FromInt f) = FromInt (g . f)
instance Applicative FromInt where
pure a = FromInt (const a)
FromInt f <*> FromInt g = FromInt (\i -> f i (g (i + 1)))
但是,这当然是不行的。如果我们在文件上调用runhaskell,我们会得到以下结果:
(1,2,2,2)
我需要的是:
(1,2,3,4)
我看到有人通过将增量要求推入实际数据来实现此效果(这是yesod-forms实现其表单样式的方式)。这更或多或少使用了State
的变体,它允许人们在不使用特定帮助函数的情况下打破假定的不变性(我认为yesod的一个叫做mhelper
)。我想知道是否可以像我尝试做的那样将增量操作拉入应用实例中。这将使违反这个特定不变量成为不可能。
State
的应用实例运行良好,但我希望有更好的方法。 - Andrew Thaddeus Martin