This works, but I don't know if it makes sense from a FP point of view. auto unwrap = [](auto const &f) { return f; }; int main( int argc, char* argv[] ) { auto plus_2 = [] ( auto arg ) { return arg + 2; }; auto minus_2...

scala,functional-programming,monads,scalaz

Given that each Monad is an Applicative you can also use (monadA |@| monadB).tupled E.g. scala> val b: List[(Int, Int)] = (List(1, 2, 3) |@| List(4, 6)).tupled b: List[(Int, Int)] = List((1,4), (1,6), (2,4), (2,6), (3,4), (3,6)) ...

scala,exception-handling,monads,scala-2.11

If you want to get all exceptions you could use collect like this: someList.collect{ case Failure(t) => t } // List[Throwable] If you want to get all success results you could use flatMap or collect: someList.flatMap{ _.toOption } // List[String] someList.collect{ case Success(s) => s } ...

You can not extract anything from IO, but you can adapt the other functions to work on IO values listCompressedImages folder = filter (match (compile ".zip")) `fmap` getDirectoryContents folder The above fmap applies a pure function (as filter ...) to some IO value. Note that the resulting type will still...

The monad is IO. This is a minor quirk of the behaviour of GHCi. It tries to unify the type of your input with IO a; if it succeeds, it runs that IO action and tries to show the result. If you give it something other than an IO action,...

scala,concurrency,monads,applicative

Well has soon has you have PairJob, you have what you need for applicative. With any generic type G, (here, that would be Job) if you have pairing: def pair[A,B](ga: G[A], gb: G[B]): G[(A,B)] (which for Job, is just PairJob(ga, gb)) and also map, then you can easily implement apply...

haskell,vector,monads,type-signature

You're almost there. You're expected type signature is correct except the resulting MVector needs to be in the monad m: vecFromList :: PrimMonad m => [t] -> Int -> m (MV.MVector (PrimState m) t) The fillV function should have type fillV :: [(Int, t)] -> MV.MVector (PrimState m) t ->...

Yep, Scalaz provides monad instances for tuples (up to Tuple8): import scalaz.std.anyVal._, scalaz.std.tuple._, scalaz.syntax.monad._ scala> type IntTuple[A] = (Int, A) defined type alias IntTuple scala> pair >>= (a => (a+1).point[IntTuple]) res0: (Int, String) = (2,as1) scala> for (p <- pair) yield (p + 1) res1: (Int, String) = (2,as1) (Note...

Adding an item to a list You can make a new list that contains one more item than an existing list with the : constructor. ("key", "value") : existing Where existing is a list you've already made Keeping track of changing state You can keep track of changing state between...

The "major" concern is easier to answer: no, it doesn't, because that's not what it means. A monad is not required to have any particular "value" or none, only to compose with functions in particular ways. For the "minor" one, you're right to be concerned about the types. Properly, a...

You can use MaybeT and the MonadPlus instance to use msum: f :: MaybeT IO Int f = msum [readInt, readInt, readInt] ...

scala,types,monads,category-theory

I would say that less bugs are expected because you give the complier as much information as possible and therefore it can find issues already during compilation. Otherwise they would occur at runtime. Regarding less code I am not sure, but maybe the idea is that Scalaz does a lot...

haskell,monads,monad-transformers,maybe

In short: Replace lift by the MaybeT constructor. Note that newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) } and lift :: (MonadTrans t, Monad m) => m a -> t m a Your use of lift in x <- lift lol is at the type...

Converting code from Haskell to F# is a bit tricky, because Haskell is lazy and so whenever you see any value, say 'a in Haskell, you could interpret it as unit -> 'a (or more precisely, as Lazy<'a>) - so everything is delayed implicitly. But let's just compare the two...

The type of get is get :: State s s So if s = (Int, Int) then you want get :: State (Int, Int) (Int, Int) That's all. get returns the entire tuple....

I think the answer to your question is to use the flip function, e.g. createTempFile filename = fmap (flip joinDrive filename) getTemporaryDirectory You could also use a section: createTempFile filename = fmap (`joinDrive` filename) getTemporaryDirectory ...

In the context of test.check the answer is no, this do-monad can't be replaced by a let block. But you can use the gen/bind and gen/return manually like this: (def vector-and-elem (gen/bind (gen/choose 1 10) (fn [n] (gen/bind (gen/vector gen/int n) (fn [v] (gen/bind (gen/elements v) (fn [e] (gen/return [v...

scala,clojure,monads,continuations,maybe

"In terms of" is a loose phrase. The Result monad you've shown is more general than the Maybe monad; indeed I'd say that Maybe is a special case of Result. And in turn continuation is more general still, and Result can be seen as a special case of continuation -...

Something like this using the either function from Data.Either: liftEither :: Monad m => (t -> m a) -> Either String t -> m a liftEither f xs = either fail f xs Or even simpler: liftEither :: Monad m => (t -> m a) -> Either String t ->...

What it says is that the order of statements doesn't influence the evaluation criteria. As @chi points out in IO monad effects are sequenced in order but their evaluation order is still not known. An example of a monad which will make the concept clear: test = do x <-...

java,monads,reactive-programming,rx-java

Cold Observables generally interact with a single Subscriber at a time and even if you subscribe more to them, they run independently and don't really need to know about each other. Subjects, on the other hand, have to track their subscribers as they multicast events they themselves receive. A quick...

I have defined a function useToken showing your use case: type Token = String getToken :: IO (Maybe Token) getToken = undefined getUsername :: Token -> IO (Maybe String) getUsername = undefined useToken :: IO (Maybe String) useToken = do token <- getToken case token of Just x -> getUsername...

class,haskell,instance,monads,continuations

You can't make Foo into a Monad. First, let's point out that Foo a is an elaborate way of writing (a -> a) -> a. runFoo :: Foo a -> ((a -> a) -> a) runFoo = runCont . unFoo foo :: ((a -> a) -> a) -> Foo a...

When working with monad transformers, to convert from some monad m to a transformer t m, you have to use the lift function: lift :: (MonadTrans t, Monad m) => m a -> t m a This is actually the defining method of the MonadTrans typeclass, so the implementation is...

You can do something like this with a fair amount of ugliness if you really desire. {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} import Control.Monad (join, liftM) class Joinable m z | z -> m where joins :: m z ->...

Not a "correct" solution, but scalaz's Comonad has copoint, which can be (ab)used to achieve this; Comonad instances already exist for a lot of standard scalaz monads, and you can cheat and define one for e.g. Task (this may make theorists angry; be sure to limit the scope of any...

createNotificationIdentifierItem :: APNSIdentifier -> APNSItem createNotificationIdentifierItem (Identifier identifier) = Item $ do putWord8 3 putWord16be 4 putWord32be identifier or createNotificationIdentifierItem :: APNSIdentifier -> APNSItem createNotificationIdentifierItem (Identifier identifier) = do Item $ putWord8 3 Item $ putWord16be 4 Item $ putWord32be identifier after making APNSItem an instance of Monad (you can...

java,performance,java-8,monads,either

While I don't quite understand your effort – apparently you are using map for side effects and you don't really have any alternative to get the result unboxed from the Either type – I have measured your work on JMH as it is. Your usage of Random was wrong, I...

You can use lift: a.lift(4) // None a.lift(2) // Some(null) Array[T] is a PartialFunction[Int, T] and lift creates a Function[Int, Option[T]] from the index to an option of the element type....

haskell,monads,monad-transformers

The part p' <- return $ errorf p looks wrong. Here, return builds a monadic value in EitherT String IO. Assuming that errorf p = Left something the value which is being built is p' <- EitherT (return (Right (Left something))) where the above return builds an IO action. This...

Instead of trying to keep track of, whether a Computation is pure, before executing it, I took the approach to make it abort if it tries to execute IO but isn't allowed to. (Like danidiaz said, static analysis is hard on Monads.) To avoid executing the IO actions, the Computation...

javascript,jquery,function,monads

el.fun will literally try to access the property fun on el (which doesn't exist). Instead you want to call fun (like you did in the first example) but also set its this value to the jQuery object: fun.call(el, attr, value); Learn more about .call and .apply....

haskell,monads,composition,parsec,aeson

I was pointed to a nice solution To start with, here is how we can do it. parseJSON (Object o) = User . join <$> (traverse (.:? "url") =<< (o .:? "image")) Here, we get Parser (Maybe Object) and pass it to the next monadic action, which works with Maybe...

You can change the type of funNoIO and funIO to be parameterised over the monad type since they aren't used: funNoIO :: Monad m => ReaderT Configuration m String funIO' :: Monad m => ReaderT Configuration m String to fix the compiler error, then you can change main to: main...

There isn't such a thing as that in base, but well done for asking the most entertaining question for me on Stack Overflow for some time. Functors and Applicative functors are closed under composition (which certainly isn't the case in general for monads, thus the need for monad transformers), which...

haskell,monads,monad-transformers

I managed to implement the suggestion mentioned in the comments of the question. I give vty callbacks in IO that sends events down a Chan. Then i have another thread listening for those events and executing the appropriate actions in my own monad....

I will translate from your specification: If the list contains no elements, I want to return an error. f [] = mzero If the list contains exactly 1 element, I want to return that element as a Monad. f [x] = return x If the list contains more than 1...

The getStdRandom function basically looks up a StdGen value in a global variable, runs some function on it, puts the new seed back into the global variable, and returns the result to the caller. If the function in question returns with an error, that error gets put into the global...

My guess is that this is the culprit: instance Monad (EitherIO e) where return = EitherIO . return . Right x >>= f = join $ fmap f x However, join is defined as: join x = x >>= id However, in this way join and >>= get defined in...

haskell,state,monads,monad-transformers,statet

You just have two little mistakes. The first is here: n <- get <* modify (-m+) This gets the value of n before we subtract m. You almost certainly want n <- modify (-m+) >> get instead, or modify (-m+) n <- get if you prefer that spelling. The other...

functional-programming,monads,state-monad

The purpose of the state monad is to hide the passing of state between functions. Let's take an example: The methods A and B need to use some state and mutate it, and B needs to use the state that A mutated. In a functional language with immutable data, this...

haskell,types,monads,monad-transformers

You need to make PwdError an instance of the Error typeclass. The following should be sufficient, though I haven't tried to compile it: instance Error PwdError where strMsg = PwdError ...

Try this: head' :: MonadPlus m => [a] -> m (a,[a]) head' xs = if null xs then mzero then return (head xs, tail xs) mzero is the "nothing" or (indeed) "zero" value, which you can use here to model the absence of a result. It has type m x...

A possible solution (importing System.IO System.Directory System.FilePath Control.Applicative): concat <$> mapM (\pd -> map (pd </>) <$> getDirectoryContents pd) pathDirs -- ^ this is to work under IO (..) -- ^ this is to affect what's under IO [..] -- ^ this returns IO [[FilePath]] There might be some way...

haskell,types,monads,type-signature

The type signature of forever is crafted to suggest that its result runs forever. Specifically, there is no way to write an action of type m b (polymorphic in its return value) that terminates and yields a non-bottom value. An alternative way to suggest the same thing would be forever'...

The list monad [] models non-determinism: a list of values [a] represents a number of different possibilities for the value of a. When you see a statement like flg <- p x in the list monad, flg will take on each value of p x in turn, i.e. True and...

haskell,functional-programming,monads,reactive-programming

Behaviors could be given monad operations. After all Behavior a is semantically Time -> a, which is Reader Time. Also Events which are semantically [(Time, a)] could be given at least Applicative instance which would resemble ZipList structure. Yet, even these are theoretically possible and elegant, in practice they are...

This is a lie: getResultCounter :: String -> Integer The type signature above is promising that the resulting integer only depends on the input string, when this is not the case: Google can add/remove results from one call to the other, affecting the output. Making the type more honest, we...

haskell,monads,typeclass,functor,applicative

There's a lot of questions rolled into one here. But let's take them one at a time. First: why doesn't the compiler look at instance contexts when choosing which instance to use? This is to keep instance search efficient. If you require the compiler to consider only instances whose instance...

haskell,data,wrapper,monads,xmonad

You can use, for example, the Writer monad for that: import Control.Monad.Writer data DirtyThing = Keyboard | Mouse newtype Dirty m a = Dirty { unDirty :: WriterT [DirtyThing] m a } doFoo :: Dirty IO () doFoo = -- doing something dirty cleanup :: Dirty m a -> m a...

haskell,monads,monad-transformers,scotty

The behaviour you are seeing is definitely the expected one: note the remark on the third argument in the documentation for scottyT: -> (m Response -> IO Response) -- Run monad m into IO, called at each action. What you could do is store the state external to the StateT...

As ever, the terminology people use is not entirely consistent. There's a variety of inspired-by-monads-but-strictly-speaking-isn't-quite notions. The term "indexed monad" is one of a number (including "monadish" and "parameterised monad" (Atkey's name for them)) of terms used to characterize one such notion. (Another such notion, if you're interested, is Katsumata's...

scala,exception-handling,monads

If I understand your question correctly, you are wondering why you need the (potentially) double try/catch, well f could throw an exception before returning the Try: scala> import scala.util.Try import scala.util.Try scala> val someTry = Try(1) someTry: scala.util.Try[Int] = Success(1) scala> someTry.flatMap(theInt => { | throw new Exception("") | Try(2)...

It's hard to argue conclusively in either direction because "pure" is not particularly well-defined. Certainly, something makes Haskell fundamentally different from other languages, and it's deeply related to managing side-effects and the IO type¹, but it's not clear exactly what that something is. Given a concrete definition to refer to...

Monads have nothing to do with purity, except that a pure language without Monads would be almost entirely useless. In layman's terms, a Monad is just a set of rules that describe how a sequence of steps can be executed. Having a Monad abstraction gives you the ability to define...

You need also an active pattern: type Result<'a> = Choice<'a,string> let Success x :Result<'a> = Choice1Of2 x let Error x :Result<'a> = Choice2Of2 x let (|Success|Error|) = function Choice1Of2 x -> Success x | Choice2Of2 x -> Error x Then for Either: type Either<'a,'b> = Choice<'b,'a> let Right x :Either<'a,'b>...

main = do let x = [0..10] print x works for me and so does main = do { let x = [0..10] in print x } I think you're trying to mix some different syntax options up....

haskell,monads,category-theory

Well, of course, it's possible to define it, but I doubt it would be of any use. There is a popular saying that "monad is just a monoid in a category of endofunctors". What it means is, first of all, that we have a category of endofunctors (meaning, (covariant) functors...

haskell,random,monads,state-monad

Since you call put in nextWeightedRandom, the state gets updated on each iteration. So each time you call randomR ... g, it is using the generator output by the previous iteration. In fact, the question itself, "isn't evalState getting run over a bunch different copies of the same generator" is...

As two commenters suggested, you need -XScopedTypeVariables. The following code compiles for me: {-# LANGUAGE ScopedTypeVariables #-} module Foo where import Control.Monad data Elem = Number Int | Truth Bool deriving Eq instance Show Elem where show (Number i) = show i show (Truth b) = show b class Stack...

The line let l1:l2:ls = lines str means that to evaluate even just l1, the whole pattern l1:l2:ls needs to match, which means that a check needs to be done that str actually contains at least two lines. With lazy input, that causes the behavior you see. You can fix...

I think that the monad instance under discussion does preserve State structure and that the tuple is throwing you for a loop when it should not. If we take a step back and ask what signature should bind have in order to match up with our monad expectations, we get...

State, StateT and other types like them come from transformers, while the MonadState typeclass and other typeclasses like it come from mtl. Notice that the former are types, while the latter are typeclasses. The types from transformers are instances of Monad and MonadTrans. You can work directly with them, but...

Maybe is used to represent an operation that might fail. In the case of this function, you return Just(the element) if an element fulfills the predicate, else, you return Nothing to show that it had "failed" (in this case, none of the elements fulfill the predicate). It's preferred to just...

TL;DR They are the same. Some history lessons State, Writer and Reader were inspired by Mark P. Jones' Functional Programming with Overloading and Higher-Order Polymorphism, where he defined Reader as follows: A Reader monad is used to allow a computation to access the values held in some enclosing environment (represented...

The problem is that the do notation in your definition of p is not using the monad you want it to use. I could be wrong, but it looks like p is using a version of the Reader monad. If you use this definition you'll see that x and y...

haskell,monads,real-world-haskell

Your code is very similar to the Writer [a] monad, and I don't think there is a simpler way of fixing it than closing the gap in all but naming. Specifically: Since a monad must allow an arbitrary result type, the type of the effect part cannot depend on the...

haskell,monads,functor,applicative,fam-proposal

With GHC 7.10 and above, you must implement Functor and Applicative. The class definitions for Monad mandate the superclass instances: class Functor f => Applicative f where ... class Applicative m => Monad m where ... Note that once you have a Monad instance, the Functor and Applicative instances can...

You don't need to write any instances. You're simply using append and munch in a wrong way. append has type MonadState Dictionary m => String -> String -> m (). If f and s are strings, then append f s yields a state-modifying action that eventually returns a (). put...

haskell,monads,function-composition

Let's start step by step. Misty typeclass is given: class Misty m where banana :: (a -> m b) -> m a -> m b unicorn :: a -> m a Also furry' is already solved in an earlier problem in those exercises: furry' :: Misty m => (a ->...

haskell,monads,monad-transformers

The MonadReader class is defined using the FunctionalDependencies extension, which allows declarations like class Monad m => MonadReader r m | m -> r where ... This means that for any monad m, the r is uniquely determined by it. Therefore, you can't have a single monad m that determines...

haskell,functional-programming,monads,do-notation

Well, you've stumbled upon a kind of weird monad. The monad in question is the Monad ((->) r). Now, what does that mean? Well, it's the monad of functions of the form r -> *. I.e., of functions that take the same type of input. You asked what the type...

java,monads,reactive-programming,rx-java

Using BehaviorSubject is the right thing to do here if you don't care about earlier values. Note most post discouraging Subjects were written in the early days of Rx.NET and is mostly quoted over and over again without much thought. I attribute this to the possibility that such authors didn't...

haskell,functional-programming,monads

Problem to make the last monadic: addStuff = (*2) >>= \a -> (+10) >>= \b -> return (a + b) ...

You want to cleanly combine a stateful action having side effects, a delay, and an independent stopping condition. The iterative monad transformer from the free package can be useful in these cases. This monad transformer lets you describe a (possibly nonending) computation as a series of discrete steps. And what's...

Yes, that is the same kind of arrow. There is sugar syntax for arrows just like there is sugar syntax for monads. You can't use Google to search for -<, but you can use Hoogle. See: GHC Language Features, Arrow tutorial. Arrow syntax is indeed poorly documented. The reason that...

list,haskell,io,element,monads

Your main problem here is you simply don't know how to manipulate monads, so here are a few pointers: Monads have a few functions to allow them to be manipulated. These stem from the basic ones defined in the monad typeclass, return and >>= (aka 'bind'). return allows a monad...

The problem lies here: svgtex x = x The complier complains that Couldn't match expected type `IO Inline' with actual type `Inline' because x is an Inline, while svgtex must return an IO Inline. To inject the x into the IO monad, we can simply use the return function svgtex...

haskell,functional-programming,monads,purely-functional

You would, in fact, use a variant of the state monad to pass the random generator around behind the scenes. The Rand type in Control.Monad.Random helps with this. The API is a bit confusing, but more because it's polymorphic over the type of random generator you use than because it...

The type of id is c -> c (using a different letter so not to conflict with a and b that occur in the type of >>=). We can unify c -> c with a -> Maybe b if we pick c = a = Maybe b. So this means...

notEndOfString is matching and consuming any characters in the text including " until the end, so it acts greedily to consume all characters and never hands off to the char '"' parser. You need to match any characters inside of the quotes that aren't a quote, which means you need...

Different approaches are being used here. Sometimes, the base monad Foo is defined in terms of its transformer as FooT Identity. For example, State from transformer package, as Daniel Wagner points out. Other times, the base monad Foo is defined independently. In these cases, it usually happens that Foo and...

f#,monads,computation-expression

Whether or not an implementation of Zero is needed is determined by how the if statement is translated into function calls from the monadic syntax. If both branches of an if are syntactically computation expressions then the translation does not involve Zero. In the case that one of the branches...

How about Control.Monad.Loops.iterateM_? This is slightly neater as it avoids explict recursion. iterateM_ :: Monad m => (a -> m a) -> a -> m b saveThreadFunc :: TQueue String -> Int -> IO () saveThreadFunc queue = iterateM_ $ \lastBackupTime -> do newLine <- atomically $ readTQueue queue now...

parsing,haskell,monads,applicative,aeson

Essentially, you need a Parser [a] -> Parser NE.NonEmpty transformer, which is relatively easy: -- toNonEmptyP :: Parser [a] -> Parser NE.NonEmtpy toNonEmptyP p = fmap NE.nonEmpty p >>= maybe mzero return We map NE.nonEmpty on our regular list parser, which gives us Parser (Maybe NE.NonEmpty). We then inspect the...

Since you're hitting a database, no. A huge part of Haskell is specifying to someone using your API that they're performing an IO action. Since IO actions can fail, return different results for the same input, or fire the missiles, we always tell the user when this happens. What would...

In this case you can just pass the map call on to the wrapped collection fields. For withFilter you can call the filter method on fields, but I think that's not entirely in line with the semantics that withFilter is supposed to have. case class Grid[E](private val fields: IndexedSeq[E]) {...

The type of (>>=) is: Monad m => m a -> (a -> m b) -> m b Since you are writing an instance for SM, the type of bind in your instance is therefore SM a -> (a -> SM b) -> SM b Notice that both a and...

The "better-java-monads" project on GitHub has a Try monad for Java 8 here.

If you import Control.Applicative and Data.Bool (if using base >= 4.7), then you could write it as g xs = bool 0 42 <$> and <$> mapM f xs -- Or equivalently -- g xs = bool 0 42 . and <$> mapM f xs -- g = fmap (bool...