I have defined a monadic counter in Haskell which I'm trying to translate to Scala, failing miserably so far. The problem in a nutshell is about implementing a counter as a state monad, which reads the counter increment constant from the environment, and logs the history of the counter (its sequence of values).
A friend of mine improved upon 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've tried without success to code this into Scala + (Cats | ScalaZ). The latest stable version of Cats lacks a lift
method for WriterT
. And with ReaderWriterState
in Scalaz
I could not figure out in a couple of hours how to use the local
method. And that's only the begining ...
How this Haskell solution could be translated in a simple and elegant way? (to the extent allowed by the language).
Side note:
I'm still trying to figure out why I need to spend so much time to translate simple solutions from Haskell to Scala + FP libraries (Cats, Scalaz). In Haskell finding the instances and available functions of each type-class is a breeze, in Scala using IntelliJ, GitHub and StackOverflow this takes me days. So I'm wondering what am I doing wrong, and how could I improve this situation.
local
above for instance), which means that you cannot use it directly but through one of the multiple instances of this private class. I don't think you can do this from the Scala doc alone. – Damian Nadales