FAQ Database Discussion Community


Is there any scala library that treat tuples as monads

scala,tuples,monads
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 <-...

A monad of tuples (monad, state)?

haskell,io,monads,state-monad
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...

Must I implement Applicative and Functor to implement a Monad

haskell,monads,functor,applicative,fam-proposal
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...

How does the state monad work? (without code explanation)

monads,state-monad
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...

Monads in Haskell and Purity

haskell,io,monads
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....

How to use all with a monadic function?

list,haskell,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...

Access element of an Array and return a monad?

scala,monads
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? ...

Haskell do clause with multiple monad types

haskell,monads
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:...

What is the use of monads in OCaml?

ocaml,monads
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?

Lifting from Either to IO

haskell,monads
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....

Are there contravariant monads?

haskell,monads,category-theory
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...

Why does this function not fail immediately?

haskell,monads
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...

How to use bind with nested monads?

haskell,monads
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...

Can functional reactive programming (FRP) be expressed using monads?

haskell,functional-programming,monads,reactive-programming
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...

RxJava- No access to Observable's subscribers?

java,monads,reactive-programming,rx-java
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...

Haskell's filterM with filterM (\x -> [True, False]) [1, 2, 3]

haskell,monads
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 <-...

How to properly use monadic expressions in Haskell without getting parse errors?

haskell,monads
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...

How to get Reader and ReaderT to work together

haskell,monads
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...

What is wrong with my Haskell definition of the bind operator in this example?

haskell,monads,ghc,ghci
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...

How to correctly error out in JSON parsing with Data.Aeson

parsing,haskell,monads,applicative,aeson
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?

haskell,monads
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...

Haskell getContents wait for EOF

haskell,io,monads
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...

What the heck is “-<”, anyway?

haskell,monads
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...

Why are some typeclasses prefixed with “Monad”?

haskell,monads
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...

Why does this list contain more than one distinct value?

haskell,random,monads,state-monad
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,...

VTY-UI needs IO. Can I make this happen?

haskell,monads,monad-transformers
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:...

How can I get the value of a Monad without System.IO.Unsafe? [duplicate]

haskell,web-crawler,monads
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...

How to combine multiple monad effects into the same do block?

haskell,monads,monad-transformers
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....

Types in MaybeT computation

haskell,monads,monad-transformers,maybe
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...

Why does GHCI get “stuck” in an error state after an error?

haskell,monads,io-monad
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...

Growing a list in haskell

haskell,monads
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...

In Yesod/Haskell, how do I use data from IO with the variable interpolation functionality?

haskell,io,monads,yesod
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>...

LZW routine in Haskell using Monads

haskell,monads,lzw
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 =...

Haskell Function composition of two binary functions?

haskell,monads,function-composition
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...

Creating a monad for incrementally storing results type not matching

haskell,monads,real-world-haskell
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 =...

Why are instances matched only by their heads?

haskell,monads,typeclass,functor,applicative
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...

Haskell type signatures and Monads

haskell,vector,monads,type-signature
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...

Deriving a base monad using a monad transformer and the identity monad

haskell,monads
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...

how to transform a IO [FilePath] into a [FilePath]? [duplicate]

haskell,monads
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...

How do I program monadicaly in Java8 while getting comparable performance?

java,performance,java-8,monads,either
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...

Taking monadic functions out of a monad

haskell,types,monads
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...

Why does scala.util.Success.flatMap (Try.flatMap) use try-catch again after applying its argument?

scala,exception-handling,monads
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...

Is it true that order of execution inside a do block doesn't depend on the statement order?

haskell,monads,do-notation
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...

Writing Parser for JSON String

parsing,haskell,monads
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,...

Maybe monad in JavaScript

javascript,monads
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...

How do I get the value OUT of my maybe<> monad?

c++,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...

HashMaps vs Reactive Programming

java,monads,reactive-programming,rx-java
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...

Why can't I stack two readers ontop of eachother?

haskell,monads,monad-transformers
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...

What's the difference between Monad.Reader and the (->) monads?

haskell,monads
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...

Randomness in a nested pure function

haskell,functional-programming,monads,purely-functional
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...

How do I map and concatenate FilePaths?

haskell,monads,io-monad
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",...

Haskell State monad with tuples as state

haskell,state,monads
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):...

Composing optional Aeson parsers

haskell,monads,composition,parsec,aeson
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...

`forever`: How to forward information to next iteration?

loops,haskell,monads
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 _ <-...

Why am I getting a type error in this sequence of parsers (lecture 8 by Erik Meijer)?

parsing,haskell,types,monads
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...

Haskell `forever` type signature

haskell,types,monads,type-signature
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, are there aliases for (liftM . liftM), (liftM . liftM . liftM), etc?

haskell,monads,lifting
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...

What is the purpose of the state monad?

functional-programming,monads,state-monad
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...

No instance for MyClass arising from a use of `throwError'

haskell,types,monads,monad-transformers
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 <...

How to pass jQuery function as another function's argument?

javascript,jquery,function,monads
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...

How to combine a readProcess monad with where in Haskell?

haskell,monads
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...

In scala, why doesn't list.flatMap(List) work?

scala,functional-programming,monads
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!...

Maybe Monad and >>=

haskell,monads,maybe
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...

How to “wrap” monadic return value

haskell,monads
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...

Why do we need monads?

haskell,monads
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?

building Either (or Result) on top of Choice in F#

f#,monads
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...

What is the type of the variable in do-notation here in Haskell?

haskell,functional-programming,monads,do-notation
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...

Haskell/XMonad: wrapper around a Monad that also keeps track of data

haskell,data,wrapper,monads,xmonad
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: {-#...

Could this do-monad be replaced by a let block?

clojure,monads,let
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...