monads

Haskell Monad bind operator confusion

萝らか妹 提交于 2019-12-04 07:51:34
问题 Okay, so I am not a Haskell programmer, but I am absolutely intrigued by a lot of the ideas behind Haskell and am looking into learning it. But I'm stuck at square one: I can't seem to wrap my head around Monads, which seem to be fairly fundamental. I know there are a million questions on SO asking to explain Monads, so I'm going to be a little more specific about what's bugging me: I read this excellent article (an introduction in Javascript), and thought that I understood Monads completely.

How to inject multi dependencies when I use “Reader monad” for dependency injection?

十年热恋 提交于 2019-12-04 07:50:00
问题 I'm trying to use Reader monad for dependency injection, but have problems when the methods requires different dependencies: class PageFetcher { def fetch(url: String) = Reader((dep1: Dep1) => Try { ... }) } class ImageExtractor { def extractImages(html: String) = Reader((deps: (Dep2, Dep3)) => { ... }) } object MyImageFinder { def find(url: String) = Reader((deps: (PageFetcher, ImageExtractor)) => { val (pageFetcher, imageExtractor) = deps for { htmlTry <- pageFetcher.fetch(url) html <-

Implementing Haskell's Maybe Monad in c++11

僤鯓⒐⒋嵵緔 提交于 2019-12-04 07:48:38
问题 I am trying to implement the Maybe monad from Haskell using the lambda functions in C++11 and templates. Here's what I have so far #include<functional> #include<iostream> using namespace std; template<typename T1> struct Maybe { T1 data; bool valid; }; template<typename T1, typename T2> Maybe<T2> operator>>=(Maybe<T1> t, std::function < Maybe<T2> (T1)> &f) { Maybe<T2> return_value; if(t.valid == false) { return_value.valid = false; return return_value; } else { return f(t.data); } } int main(

Help me understand this Scala code: scalaz IO Monad and implicits

谁都会走 提交于 2019-12-04 07:39:10
This is a followup to this question. Here's the code I'm trying to understand (it's from http://apocalisp.wordpress.com/2010/10/17/scalaz-tutorial-enumeration-based-io-with-iteratees/ ): object io { sealed trait IO[A] { def unsafePerformIO: A } object IO { def apply[A](a: => A): IO[A] = new IO[A] { def unsafePerformIO = a } } implicit val IOMonad = new Monad[IO] { def pure[A](a: => A): IO[A] = IO(a) def bind[A,B](a: IO[A], f: A => IO[B]): IO[B] = IO { implicitly[Monad[Function0]].bind(() => a.unsafePerformIO, (x:A) => () => f(x).unsafePerformIO)() } } } This code is used like this (I'm

Pure functional Random number generator - State monad

倾然丶 夕夏残阳落幕 提交于 2019-12-04 06:52:17
The book ' Functional Programming in Scala ' demonstrates an example of pure functional random number generator as below trait RNG { def nextInt: (Int, RNG) } object RNG { def simple(seed: Long): RNG = new RNG { def nextInt = { val seed2 = (seed*0x5DEECE66DL + 0xBL) & ((1L << 48) - 1) ((seed2 >>> 16).asInstanceOf[Int], simple(seed2)) } } } The usage will look like val (randomNumber,nextState) = rng.nextInt I do get the part that it's a pure function as it returns the next state and leaves it on the API client to use it to call nextInt the next time it would need a random number but what I did

Monad instance for pairs

自古美人都是妖i 提交于 2019-12-04 05:28:52
问题 This question shows an instance definition for (,) a b , where a is an instance of Monoid . However, I don't know how to write similar thing for (,) a b , and b is an instance of Monoid ? I can basically do this as long as I can write the definition: instance Monoid b => Monad ((,) ???) where return a = (a,mempty) ~(a,b) >>= f = let (c,b1) in f a in (c,b `mappend` b1) So the question is how to write the ??? part? UPDATE Actually this question is special case of a more generic problem: is it

Combining List, Future and Option in for-comprehension - scalaz

青春壹個敷衍的年華 提交于 2019-12-04 04:21:38
问题 I've got following problem: val sth: Future[Seq[T, S]] = for { x <- whatever: Future[List[T]] y <- x: List[T] z <- f(y): Future[Option[S]] n <- z: Option[S] } yield y: T -> n: S I would want to make this code to work(I guess everyone understands the idea as I've added types). By "to work" I mean, that I would want to stay with the for-comprehension structure and fulfil expected types in the end. I know there are "ugly" ways to do it, but I want to learn how to do it pure :) As I read the

Is there something like Java Stream's “peek” operation in Scala?

混江龙づ霸主 提交于 2019-12-04 04:20:30
In Java you can call peek(x -> println(x)) on a Stream and it will perform the action for each element and return the original stream, unlike foreach which is Unit. Is there something similar in Scala, ideally something which works on all Monady types, allowing you to "pass through" the original Monad while performing a side effect action? (Logging, e.g.) It is of course easily implemented: def tap[A, U](a: A)(action: (A) => U): A = { action(a) a } but I'm hoping for something a bit more elegant or idiomatic. One way to solve this is using implicits: class Tappable[A](a: A) { def tap[U](action

Violation of the left identity law for Future monads in scalaz

孤人 提交于 2019-12-04 04:07:11
Suppose I define an instance of the Monad typeclass for Future : val futureMonad = new Monad[Future] { override def point[A](a: ⇒ A): Future[A] = Future(a) override def bind[A, B](fa: Future[A])(f: A => Future[B]): Future[B] = fa flatMap f } Strictly speaking, this is not a monad, since it violates the law of left identity: futureMonad.point(a) bind f == f(a) If f throws an exception, the result of the expression on the left hand side will be a failed Future , whereas the right hand side will, of course, throw the exception. But what are the practical implications of this violation? In which

Chaining method calls with Either

痴心易碎 提交于 2019-12-04 03:59:41
I'd like to know if it is possible to create some kind of "method call chain", with all methods returning the same Either[Error,Result]. What i'd like to do is: call all the methods successively, and when method returns a Left(Error), then stop the method calls and return the first Left found in the call chain. I've tryied some stuff, with fold, map, projections... but i'm new to Scala and don't find any elegant solution. I've tryed some thing like that: def createUserAndMandatoryCategories(user: User) : Either[Error,User] = { User.create(user).right.map { Logger.info("User created") Category