Application that enhances the environment at haskell

I am wondering if there is Applicativeone that can track how many application operations have occurred. I tried to implement it as follows:

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)))

But this, of course, does not work. If we call runhaskell in the file, we get the following:

(1,2,2,2)

And I want this:

(1,2,3,4)

, , ( , yesod- ). - State, , ( , mhelper). , , . .

+4
1

(,) a Applicative, a Monoid. (,) (Sum Int) , Data.Functor.Compose, , "", , .

, , 1:

module Main where

import Data.Monoid
import Control.Applicative
import Data.Functor.Compose

type CountedIO a = Compose ((,) (Sum Int)) IO a

-- lift from IO
step :: IO a -> CountedIO a
step cmd = Compose (Sum 1, cmd)

countSteps :: CountedIO a -> Int
countSteps = getSum . fst . getCompose

exec :: CountedIO a -> IO a
exec =  snd . getCompose

program :: CountedIO () 
program = step (putStrLn "aaa") *>  step (putStrLn "bbb") *> step (putStrLn "ccc")

main :: IO ()
main = do
    putStrLn $ "Number of steps: " ++ show (countSteps program)
    exec program 

, , step.

(, pure, 0 .)

+10

All Articles