Menu
  • HOME
  • TAGS

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

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...

Haskell do clause with multiple monad types

haskell,monads

A do block is for a specific type of monad, you can't just change the type in the middle. You can either transform the action or you can nest it inside the do. Most times transformations will be ready for you. You can, for instance have a nested do that...

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

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...

Is a collection with flatMap a monad?

scala,monads

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...

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

haskell,web-crawler,monads

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...

Monads in Haskell and Purity

haskell,io,monads

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...

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

haskell,monads,do-notation

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 <-...

Randomness in a nested pure function

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...

A monad of tuples (monad, state)?

haskell,io,monads,state-monad

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...

Basic Haskell IO Monad FilePath join

haskell,monads

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 ...

Taking monadic functions out of a monad

haskell,types,monads

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 ->...

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

f#,monads

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>...

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

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....

Haskell type signatures and Monads

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 ->...

Composing optional Aeson parsers

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...

Are there contravariant monads?

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...

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

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...

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

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...

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

haskell,monads

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 Function composition of two binary functions?

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 ->...

In Haskell, are there aliases for (liftM . liftM), (liftM . liftM . liftM), etc?

haskell,monads,lifting

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...

How do I map and concatenate FilePaths?

haskell,monads,io-monad

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...

Combine monads into tuples operator scalaz

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)) ...

How to combine a readProcess monad with where in Haskell?

haskell,monads

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...

How to define Applicative in this case?

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...

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

c++,monads

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...

Access element of an Array and return a monad?

scala,monads

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....

Types in MaybeT computation

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...

Why do we need monads?

haskell,monads

Why do we need monads? We want to program only using functions. ("functional programming (FP)" after all). Then, we have a first big problem. This is a program: f(x) = 2 * x g(x,y) = x / y How can we say what is to be executed first? How can...

Creating a monad for incrementally storing results type not matching

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...

Idiomatic way of filtering Failure(t) instances in Scala

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 } ...

Why does this list contain more than one distinct value?

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...

Can we understanding the error monad in terms of the Maybe monad or the Continuation monad?

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 -...

Why are instances matched only by their heads?

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...

Abstraction for monadic recursion with “unless”

haskell,monads

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...

Error handling with MonadPlus

haskell,monads

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...

What the heck is “-<”, anyway?

haskell,monads

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...

Maybe monad in JavaScript

javascript,monads

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...

LZW routine in Haskell using Monads

haskell,monads,lzw

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...

RxJava- No access to Observable's subscribers?

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...

Refactoring “staircasing” with case of `Maybe` values in `IO` code

haskell,monads,maybe,io-monad

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

How to “wrap” monadic return value

haskell,monads

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...

Is there any scala library that treat tuples as monads

scala,tuples,monads

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...

Pause Monad - What should the monadic type look like?

f#,monads

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...

Making continuation monad wrapper instance of Monad class

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...

Maybe Monad and >>=

haskell,monads,maybe

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...

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

haskell,monads,ghc,ghci

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...

Lifting from Either to IO

haskell,monads

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 ->...

Scala: Implementing map and withFilter in a simple custom type

scala,for-loop,monads

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]) {...

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

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...

Must I implement Applicative and Functor to implement a Monad

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...

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

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)...

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

haskell,monads,io-monad

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...

Trouble understanding error handling with monads

haskell,monads

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...

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

clojure,monads,let

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...

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

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...

How to use all with a monadic function?

list,haskell,monads

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...

What is indexed monad?

haskell,monads

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...

How can I create a non-evaluated mapping in Haskell?

haskell,monads

mapM is pretty much sequence . map, which means that it will be evaluated and made into an action. You want to simply map putStrLn - that will create a list of type [IO ()] without carrying out the desired action. When you want it to be printed, simply sequence...

Type troubles with custom typeclass

haskell,types,monads

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...

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

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...

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

haskell,monads

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...

Haskell getting IO list elements

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...

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

scala,functional-programming,monads

For List[A], flatMap expects a function from A => GenTraversableOnce[B]. The problem with using List.apply in that particular syntax is that apply allows repeated parameters A*, which is syntactic sugar for Seq[A]. So List.apply is really a Seq[A] => List[A], which is not the same as A => List[A]. And...

Haskell - Exposing IO actions in API

api,haskell,monads

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...

What is the purpose of the state monad?

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...

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

haskell,monads

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...

Why are some typeclasses prefixed with “Monad”?

haskell,monads

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...

Haskell `forever` type signature

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'...

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

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 ...

MonadBaseControl: how to lift simpleHTTP from Happstack?

haskell,monads,monad-transformers

I don't think you can lift this in general for any MonadBaseControl IO m. There are some ms for which we can. In General UnWebT m is isomorphic to WebT m which has a MonadTransControl instance. You can convert to and from WebT with mkWebT :: UnWebT m a ->...

Scalaz - runnable monad

scala,monads,scalaz

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...

Growing a list in haskell

haskell,monads

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...

HashMaps vs Reactive Programming

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...

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

haskell,io,monads,yesod

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...

Haskell State monad with tuples as state

haskell,state,monads

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....

How to get Reader and ReaderT to work together

haskell,monads

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...

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

parsing,haskell,types,monads

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...

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

haskell,monads

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...

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

monads,state-monad

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...

What is the type of return 5 in Haskell when no context is given?

haskell,monads

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

Try monad in Java 8

java-8,monads

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

How to use bind with nested monads?

haskell,monads

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...

Writing Parser for JSON String

parsing,haskell,monads

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...

Haskell - Mixed stateful computations

haskell,monads,state-monad

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...

What is the use of monads in OCaml?

ocaml,monads

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...

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

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....

Misunderstanding the List monad

haskell,monads

Try f 0 = [[]] Looks like f x generates of bitwise combinations of length x, so f 0 must contain the sequence of length 0, which is the empty list....

Why does this function not fail immediately?

haskell,monads

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...

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

haskell,monads

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...

What are the attributes that make 'types-first' programming in Scala have less code and less bugs?

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...