Is there any scala library that enriches basic scala tuples with monad syntax. Something similar to the Writer monad but adjusted for usage with tuples. What I look for: val pair = (2, "as") pair >>= (a => point(a+1)) should equal to (3, "as"). As well as for (p <-...

I am trying to write a Haskell "number-guessing" game program, using Monads, but I am stucked: I tried the simple state monad: data SM a = SMN (S -> (a, S)) instance Monad SM where SMN c1 >>= fc2 = SMN (\s0 -> let (r, s1) = c1 s0 in...

I'm trying to implement a Monad instance. As a simpler example, assume the following: data Maybee a = Notheeng | Juust a instance Monad Maybee where return x = Juust x Notheeng >>= f = Notheeng Juust x >>= f = f x fail _ = Notheeng This should be...

For the last number of months I've been taking some spare time here and there to read up on Monads. I haven't worked with a functional language since my University days. So I don't really remember Haskell, and certainly have no idea about Scalaz. It was a trying time learning...

My question is whether monads in haskell actually maintain hakell's purity, and if so how. Frequently I have read about how side effects are impure but that side effects are needed for useful programs (e.g. i/o). In the next sentence it is stated that haskell's solution to this is monads....

I have found myself in a situation where I want to use all with a monadic function. In my mind this didn't really turn out too pretty: f :: Monad m => a -> m Bool g :: Monad m => [a] -> m Int g xs = do cnd...

If I access an index outside the bounds of an Array, I get an ArrayIndexOutOfBoundsException, eg: val a = new Array[String](3) a(4) java.lang.ArrayIndexOutOfBoundsException: 4 Is there a method to return a monad instead (eg: Option)? And why doesn't the default collections apply method for Array support this? ...

I'm using a graphic library in Haskell called ThreePennyUI. In this library the main function returns a UI monad object. This causes me much headache as when I attempt to unpack IO values into local variables I receive errors complaining of different monad types. Here's an example of my problem:...

This might be a stupid question, but since OCaml is not pure and has side effects built-in, what is the use of monads in OCaml?

I would like to convert from Either monad into IO without any clues from Either. Is there more elegant way to do it? I have written this function, but I would like to use something from a library or Prelude: liftEither :: forall t (m :: * -> *) a....

Functors can be covariant and contravariant. Can this covariant/contravariant duality also be applied to monads? Something like: class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b class ContraMonad m where return :: a -> m a contrabind...

I have the following piece of code. main gets the stdin text and sequences it through g, after which f prints it's output and returns an appropriate ExitCode which is commited using exitWith. My question is why does this program, when run with the sample input, not terminate immediately after...

I have two functions, one that tries to get a token from a webservice and may fail, and one that tries to use this token to get the username and may fail. getToken :: IO Maybe Token getUsername :: Token -> IO Maybe String I would like to take the...

I've been reading up on Functional Reactive Programming, and though I have not used monads extensively in any language, I can't help but see them everywhere in the FRP design. This question's answers have some fantastic descriptions of what functional reactive programming is, and I won't attempt to replicate that...

I learned it is undesirable to use Subjects in reactive programming although I found them highly convenient. But I understand they can be abused. So I tried to create an infinite Observable<ImmutableMap<Integer,ActionProfile> that needs to publish a new ImmutableMapevery time refresh() is called. I also have a forKey() method that...

I just cannot understand the magic that Haskell does with this filterM use case. The source code for this function is listed below: filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a] filterM _ [] = return [] filterM p (x:xs) = do flg <-...

I'm running GHC version 7.8.3 on Windows 7. Ok, this is not about fancy code snippets. I'm just trying not be a noob here and actually compile something in a way that vaguely resembles the structure of side-effect languages. I have the following code: main = do { let x...

I'm using the ReaderT Monad transformer to propagate my configuration data from my main function through several functions performing IO. The ultimate function that will need the data doesn't perform any IO. I have this working solution : import Control.Monad.Reader type Configuration = String funNoIO :: Reader Configuration String funNoIO...

I'm following a monad transformers tutorial here. At this point in the tutorial, it asks me to try to implement the Monad instance for the EitherIO data type, defined as: data EitherIO e a = EitherIO { runEitherIO :: IO (Either e a) } So I tried: instance Functor (EitherIO...

My type and correponding FromJSON implementation as listed below. The nonEmpty turns a List into a Maybe NonEmpty and I'm trying to correctly deal with the case where the List is indeed empty and I have to abort the parsing. This parsing is actually done inside of parseJsonBody, which means...

What is indexed monad and the motivation for this monad? I have read that it helps to keep track of the side effects. But the type signature and documentation doesn't lead me to anywhere. What would be an example of how it can help to keep track of side effects...

I want to wait until user input terminates with EOF and then output it all whole. Isn't that what getContents supposed to do? The following code outputs each time user hits enter, what am I doing wrong? import System.IO main = do hSetBuffering stdin NoBuffering contents <- getContents putStrLn contents...

The other day I came across an operator, -<, appearing in the context of binding a value to a variable in a monad; specifically, it looks like this passes a value to a function which is then assigned (and possibly evaluated?) to a variable existing in the scope of a...

Reading through some code I sometimes come across typeclasses that are prefixed with Monad, examples of these are MonadState, MonadIO, MonadReader, etc. What exactly is the purpose of these? Taking MonadState as an example, I know that State allows stateless state StateT allows the use of other monads, like IO...

I have code that looks like: import qualified Data.Vector as V import System.Random import Control.Monad.State.Lazy nextWeightedRandom :: State (StdGen, V.Vector Int) Int nextWeightedRandom = do (g, fs) <- get let (i, g') = randomR (0, V.length fs - 1) g put (g', fs) return (fs V.! i) weightedRandomList :: (StdGen,...

I'm trying to build a UI with the VTY-UI library. I'm also using a custom monad (a few monads stacked on top of eachother). For regular IO functions, this is not a problem. I can just lift them into my monad. However, the VTY-UI function onActivate has this type signature:...

This question already has an answer here: How to get normal value from IO action in Haskell 2 answers I just started learning Haskell and got my first project working today. Its a small program that uses Network.HTTP.Conduit and Graphics.Rendering.Chart (haskell-chart) to plot the amount of google search results...

I have a function that calls functions of type IO and functions of type Either String a. I would like to combine the effects in the do notation, so that I can unpack IO when necessary and at the same time abort the computation at the first Left I encounter....

Working in an IO computation I ended up with a staircase of case mbValue of …s and figured out that I should use the Maybe monad to simplify the code. Since it's within an IO computation and I need to get IO values, I used the MaybeT monad transformer so...

First of all, my apologies for the non-descriptive title. Since I have no idea what's actually going on I can't really make it any more specific. Now for my question. I have implemented the following snippet for problem 23 of the 99 Haskell problems, which should randomly select n items...

I'm learning Haskell by writing an OSC musical sequencer to use it with SuperCollider. But because I'd like to make fairly complex stuff with it, it will work like a programming language where you can declare variables and define functions so you can write music in an algorithmic way. The...

How do I take values from an IO monad and interpolate into a yesod widget? For example, I want to interpolate the contents of a file into hamlet: (readFile "test.txt") >>= \x -> toWidget $ [hamlet| <p> text: #{x} |] or equivalently: contents <- (readFile "test.txt") toWidget $ [hamlet| <h2>...

I'm trying to implement LZW compression in Haskell using Monads, here is my code so far with test cases: {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} import Control.Monad.State import Control.Monad.Writer import Data.Char (chr, ord) import Data.List (isPrefixOf, maximumBy) import Data.Function import Test.QuickCheck type Dictionary =...

I'm working my way through 20 Intermediate Haskell exercises and I got stuck on exercise 13: -- Exercise 13 -- Relative Difficulty: 6 apple :: (Misty m) => m a -> m (a -> b) -> m b apple = error "todo" where the Misty Typeclass is essentially the Monad...

I'm trying to get a better understanding of monads by trying to create one. The idea is to create a monad that just stores all results. However, I just can't get the type to match up. main :: IO () main = do let v1 = return (1,1) v2 =...

I'll start by introducing a concrete problem (StackOverflow guys like that). Say you define a simple type data T a = T a This type is a Functor, Applicative and a Monad. Ignoring automatic deriving, to get those instances you have to write each one of them, even though Monad...

I made a function in haskell that is supposed to take a list along with the size of the list; and it is supposed to create a Data.Vector.Mutable.MVector with the given size, fill the vector with the contents of the list and return this vector. TL;DR I want to know...

I read (for example here and here) that all of the base monads (Mabye, Error, ...) are derived from their corresponding monad transformers (MaybeT, ErrorT, ...) using the identity monad Identity. An example would be: type Maybe a = MaybeT Identity a But that of course doesn't result in a...

This question already has an answer here: How to flatten IO [[String]]? 2 answers I would like to look in my current directory and only print .zip files. My strategy (shown below) is to get the FilePaths as an IO [FilePath]. I thought I could lift the IO so...

Is monadic programming in Java 8 slower? Below is my test (a right-biased Either is used that creates new instances for each computation). The imperative version is 1000 times faster. How do I program monadicaly in Java8 while getting comparable performance? Main.java public class Main { public static void main(String...

Haskell has the function join, which "runs" a monadic action which is inside a monad: join :: Monad m => m (m a) -> m a join m = m >>= \f -> f We can write a similar function for monadic functions with one argument: join1 :: Monad m...

Below is the definition of flatMap taken from scala.util.Success. final case class Success[+T](value: T) extends Try[T] { def flatMap[U](f: T => Try[U]): Try[U] = try f(value) catch { case NonFatal(e) => Failure(e) } } Here the f function takes a value of type T and and does a possibly faulty...

I was reading https://wiki.haskell.org/Do_notation_considered_harmful and was surprised to read the following lines Newcomers might think that the order of statements determines the order of execution. ... The order of statements is also not the criterion for the evaluation order. The wiki post gave some examples that demonstrate this property. While...

As part of trying to write a JSON Parser, I'm working on parsing a JSON String value. Given the following definition from Prof. Brent Yorgey's Haskell course: -- A parser for a value of type a is a function which takes a String -- represnting the input to be parsed,...

In the examples for monads.maybe on npm we have: function find(collection, predicate) { for (var i = 0; i < collection.length; ++i) { var item = collection[i] if (predicate(item)) return Maybe.Just(item) } return Maybe.Nothing() } Can someone explain what Maybe.Just(item); and Maybe.Nothing() are actually doing? Put another way; are monads...

For educational reasons, I'm trying to implement a maybe monad in C++14. My (perhaps overly simplistic) understanding of monads is that they let you define a computation as a series of composable function calls. The wikipedia article on monads calls them "programmable semicolons" because they let you define what happens...

I am starting to embrace reactive programming a bit more, and I'm trying to apply it to my typical business problems. One pattern I often design with is database-driven classes. I have some defined unit class like ActionProfile whose instances are managed by an ActionProfileManager, which creates the instances off...

I get errors like this: Let's say I have a monadStack ReaderT A (ReaderT B m), whenever I use ask or asks, I get an error like this: Types.hs:21:10: Couldn't match type ‘A’ with ‘B’ arising from a functional dependency between: constraint ‘MonadReader B m’ arising from the instance declaration...

I learned that Monad.Reader is actually an encapsulation of a function, namely: newtype Reader r a = Reader { runReader :: r -> a } Which is made an instance of Monad, instance Monad (Reader r) where return a = Reader $ \_ -> a m >>= k = Reader...

I want to provide a function that replaces each occurrence of # in a string with a different random number. In a non-pure language, it's trivial. However, how should it be designed in a pure language? I don't want to use unsafePerformIO, as it rather looks like a hack and...

I'm still figuring out Haskell, especially the IO monad. I have a list of directory paths, e.g., ["/some/path", "/another/path", "/yet/another/path", "/still/more"] and I want to map this list into a list of fully-qualified contents of each of these paths (without . and ..), like this: ["/some/path/file.1", "/some/path/somedir", "/some/path/file.2", "/another/path/file.a", "/another/path/a/directory",...

My apologies if my question is stupid (I'm still quite new to monads), but I couldn't find the answer to it so far. I want to store pairs as the state in the State monad. However, if I try this on a simple example of (Int, Int) I get (ghci):...

Here is a part of JSON object which represents the user: { "image": { "url": "http://example.com" } } I need to parse it into a User type: data User = User { imgUrl :: Maybe Text } The naive solution: parseJSON (Object o) = User <$> getImgUrl o where getImgUrl...

There is a thread waiting for new input in a queue to safe it to the file system. It also creates backup copies. The sscce looks like this: import Control.Concurrent import Control.Concurrent.STM import Control.Monad import Data.Time.Clock.POSIX main :: IO () main = do contentQueue <- atomically $ newTQueue _ <-...

I'm in the process of watching the Functional Programming Fundamentals lecture series by Erik Meijer (with slides by Graham Hutton). In lecture 8 (on functional parsers), after defining the Parser a type, introducing a few parsing primitives (including item and return, which I named return'), Erik gives a simple example...

In Haskell why is type-signature of forever forever :: Monad m => m a -> m b Specifically why isn't it just :: Monad m => m a -> m a? Surely the type of monad we are acting upon doesn't change half way through forever? A function such as:...

In Haskell, is there any alias for (liftM . liftM), (liftM . liftM . liftM) etc? So that I don't have to be so verbose, e.g.: (liftM . liftM) (+ 1) [Just 1, Just 2] = [Just 2, Just 3] (liftM2 . liftM2) (+) [Just 1] [Just 2] = [Just...

I am a JavaScript developer on a journey to up my skills in functional programming. I recently ran into a wall when it comes to managing state. When searching for a solution I stumbeled over the state monad in various articles and videos but I have a really hard time...

I have a problem with typing. I started to study Monad transformers with this article. Then I little changed them example. Now, my code is: data PwdError = PwdError String type PwdErrorMonad = ErrorT PwdError IO isValid :: String -> ErrorT String PwdErrorMonad Bool isValid s | length s <...

I want to create function which takes one function as a parameter (another function) and returns function taking arguments which will be apply to the first one. It's monadic idea like this: function creator(fun) { return function (arg) { fun(arg); }; } $(function () { var printer = creator(alert); printer("foo...

Below script is intended as an extension of a published and working Pandoc Haskell filter script. What has been added is a call to the shell command curl. #!/usr/bin/env runhaskell -- svgtex.hs import Text.Pandoc.JSON import System.Process curl latex = readProcess "curl" ["-d", "type=tex&q=" ++ latex, "http://localhost:16000"] "" main = toJSONFilter...

This works well val l = List(1,2,3) l.flatMap(x => List(x)) But this doesn't work: l.flatMap(List) And this doesn't work either: l.flatmap(List.apply _) Does anyone have ideas about this? Thanks!...

The type signature for >>= is the following: (>>=) :: Monad m => m a -> (a -> m b) -> m b And the following makes sense to me (it is also one of the monad laws): (>>=) (Just 1) (id . return) == Just 1 Yet the Prelude...

I have the following code: data APNSIdentifier = NoIdentifier | Identifier Word32 deriving (Show, Eq) newtype APNSItem = Item Put createNotificationIdentifierItem :: APNSIdentifier -> APNSItem <--- here createNotificationIdentifierItem (Identifier identifier) = do putWord8 3 putWord16be 4 putWord32be identifier How can I "wrap" the Put monad with an APNSItem? Do I...

In my humble opinion the answers to the famous question "What is a monad?", especially the most voted ones, try to explain what is a monad without clearly explaining why monads are really necessary. Can they be explained as the solution to a problem?

I built a monad for success/failure based on information in Scott Wlaschin's blog with extra help from this stack overflow posting. I ended up with a type type Result<'a> = | Success of 'a | Error of string I now realize that this is equivalent of Choice in F#, and...

The codes below looks quite clear: do x <- Just 3 y <- Just "!" Just (show x ++ y) Here the type of x is Num and y is String. (<- here is used to take actual value out of the Monad) However, this snippet looks not so clear...

This is a followup to Ben's previous answer. I had asked for type checking for cases in which X t actions "require cleanup" (ungrabbing of buttons and/or keyboard after it has been completed). His response was a monadic wrapper NeedsCleanup, for which my current implementation goes something like this: {-#...

The author here provides the following example usage of a do-monad to combine test generators: (require '[clojure.test.check.generators :as gen]) (require '[clojure.algo.monads :as m]) (m/defmonad gen-m [m-bind gen/bind m-result gen/return]) (def vector-and-elem (m/domonad gen-m [n (gen/choose 1 10) v (gen/vector gen/int n) e (gen/element v)] [v, e])) (gen/sample vector-and-elem) ([[0 -1...