I have defined a monadic counter in Haskell , which I am trying to translate into Scala, so far not depressing. The problem in a nutshell is the implementation of the counter as a state monad, which reads the constant increment of the counter from the environment and records the history of the counter (its sequence of values).
My friend improved my solution and came up with this simple solution:
newtype Counter = Counter Int deriving (Eq)
instance Show Counter where
show (Counter i) = show i
incWith :: MonadState Counter m => Int -> m ()
incWith n = let incCounter n' (Counter i) = Counter $ i + n'
in modify (incCounter n)
inc :: (MonadReader Int m, MonadState Counter m, MonadWriter [Counter] m) => m ()
inc = ask >>= incWith >> get >>= tell . (:[])
compute :: (MonadReader Int m, MonadState Counter m, MonadWriter [Counter] m) => m ()
compute =
local (const 3) $ do
inc
inc
inc
local (const 5) $ do
inc
inc
I tried without success to encode this in Scala + (Cats | ScalaZ). The latest stable version of Cats has no method liftfor WriterT. And with ReaderWriterStatein ScalazI could not understand after a couple of hours how to use the method local. And this is just the beginning ...
Haskell ? ( , ).
:
, , Haskell Scala + FP (Cats, Scalaz). Haskell - , Scala IntelliJ, GitHub StackOverflow . , , .