monads

How to convert this map/flatMap into a for comprehension in Scala?

蓝咒 提交于 2019-11-30 04:49:07
How to convert this map/flatMap into a for comprehension, and please explain how it works, thanks. def compute2(maybeFoo: Option[Foo]): Option[Int] = maybeFoo.flatMap { foo => foo.bar.flatMap { bar => bar.baz.map { baz => baz.compute } } } Your code can be translated into this: def compute2(maybeFoo: Option[Foo]): Option[Int] = for { foo <- maybeFoo bar <- foo.bar baz <- bar.baz } yield baz.compute Quotes from Programming in Scala, Second Edition : Generally, a for expression is of the form: for ( seq ) yield expr Here, seq is a sequence of generators, definitions, and filters, with semi

Must mplus always be associative? Haskell wiki vs. Oleg Kiselyov

≡放荡痞女 提交于 2019-11-30 04:41:53
The Haskell wikibook asserts that Instances of MonadPlus are required to fulfill several rules, just as instances of Monad are required to fulfill the three monad laws. ... The most essential are that mzero and mplus form a monoid. A consequence of which is that mplus must be associative. The Haskell wiki agrees. However, Oleg, in one of his many backtracking search implementations , writes that -- Generally speaking, mplus is not associative. It better not be, -- since associative and non-commutative mplus makes the search -- strategy incomplete. Is it kosher to define a non-associative mplus

Difference between Haskell's Lazy and Strict monads (or transformers)

久未见 提交于 2019-11-30 04:40:48
When browsing Hackage, most of the monads have a Lazy and a Strict version. What is the difference exactly? Can you highlight it with some examples for the common monads (State, Reader, Writer)? I don't know of a separation into lazy and strict for the reader monad, the reason for the State(T) and Writer(T) separation doesn't apply there. The difference between the lazy and strict Writer and State monads resp. their monad transformers is the implementation of the monadic bind (>>=) , fmap etc. In the strict versions, the implementation pattern-matches on the pair ( (result, state) , resp.

Why can Haskell exceptions only be caught inside the IO monad?

安稳与你 提交于 2019-11-30 04:29:01
Can anybody explain why exceptions may be thrown outside the IO monad, but may only be caught inside it? One of the reasons is the denotational semantics of Haskell . One of the neat properties of (pure) Haskell functions is their monotonicity -- more defined argument yields more defined value. This property is very important e.g. to reason about recursive functions (read the article to understand why). Denotation of exception by definition is the bottom, _|_ , the least element in poset corresponding to the given type. Thus, to satisfy monotonicity requirement, the following inequality needs

What advantages does scala.util.Try have over try..catch?

允我心安 提交于 2019-11-30 04:26:26
问题 Searching online for the answer gives two prominent posts (Codacy's and Daniel Westheide's), and both give the same answer as Scala's official documentation for Try: An important property of Try shown in the above example is its ability to pipeline, or chain, operations, catching exceptions along the way. The example referenced above is: import scala.io.StdIn import scala.util.{Try, Success, Failure} def divide: Try[Int] = { val dividend = Try(StdIn.readLine("Enter an Int that you'd like to

What's the point of using monads in an interpreter?

╄→尐↘猪︶ㄣ 提交于 2019-11-30 03:57:14
I recently discovered this little scala example called Simple interpreter using monads : object simpleInterpreter { case class M[A](value: A) { def bind[B](k: A => M[B]): M[B] = k(value) def map[B](f: A => B): M[B] = bind(x => unitM(f(x))) def flatMap[B](f: A => M[B]): M[B] = bind(f) } def unitM[A](a: A): M[A] = M(a) def showM(m: M[Value]): String = m.value.toString(); type Name = String trait Term; case class Var(x: Name) extends Term case class Con(n: int) extends Term case class Add(l: Term, r: Term) extends Term case class Lam(x: Name, body: Term) extends Term case class App(fun: Term, arg

Why does application of `sequence` on List of Lists lead to computation of its Cartesian Product?

試著忘記壹切 提交于 2019-11-30 02:55:06
My question is about the sequence function in Prelude , the signature of which is as follows: sequence :: Monad m => [m a] -> m [a] I understand how this function works for List of Maybe s. For example, applying sequence on [Just 3, Just 9] gives Just [3, 9] . I noticed that applying sequence on List of List s gives its Cartesian Product. Can someone please help me understand how/why this happens? Peter Wortmann This works because using lists as monads in Haskell makes them model indeterminism. Consider: sequence [[1,2],[3,4]] By definition this is the same as: do x <- [1,2] y <- [3,4] return

Is access to the internal structure of a monad required for a monad transformer?

坚强是说给别人听的谎言 提交于 2019-11-30 02:53:11
问题 Is it necessary to have access to the internal structure of a monad to write the monad transformer? For example: I'd like to have GetT - transformer for Get monad from Data.Binary.Get, but this module doesn't expose internals of Get monad. Does it mean that the only way for me is to add GetT directly to Data.Binary.Get module? 回答1: In general, yes. See in this example how the the inner monad (here the list monad) can “undo” the effect of an “earlier” action of the outer monad: > execWriterT

State Monad, sequences of random numbers and monadic code

孤者浪人 提交于 2019-11-30 01:55:19
I'm trying to grasp the State Monad and with this purpose I wanted to write a monadic code that would generate a sequence of random numbers using a Linear Congruential Generator (probably not good, but my intention is just to learn the State Monad, not build a good RNG library). The generator is just this (I want to generate a sequence of Bool s for simplicity): type Seed = Int random :: Seed -> (Bool, Seed) random seed = let (a, c, m) = (1664525, 1013904223, 2^32) -- some params for the LCG seed' = (a*seed + c) `mod` m in (even seed', seed') -- return True/False if seed' is even/odd Don't

MonadPlus definition for Haskell IO

纵然是瞬间 提交于 2019-11-30 01:37:40
问题 I was just writing a quick bit of code, and I wanted to use the guard function in the IO Monad. However, there is no definition of MonadPlus for IO which means that we cannot use guard in IO land. I have seen an example of using the MabyeT transformer to use guard in the Maybe Monad and then lifting all of the IO actions but I do not really want to do that if I do not have to. Some example of what I want might be: handleFlags :: [Flag] -> IO () handleFlags flags = do when (Help `elem` flags)