Search Results

Search found 79 results on 4 pages for 'monad'.

Page 1/4 | 1 2 3 4  | Next Page >

  • Critique of the IO monad being viewed as a state monad operating on the world

    - by Petr Pudlák
    The IO monad in Haskell is often explained as a state monad where the state is the world. So a value of type IO a monad is viewed as something like worldState -> (a, worldState). Some time ago I read an article (or a blog/mailing list post) that criticized this view and gave several reasons why it's not correct. But I cannot remember neither the article nor the reasons. Anybody knows? Edit: The article seems lost, so let's start gathering various arguments here. I'm starting a bounty to make things more interesting.

    Read the article

  • Type error while trying to implement the (>>=) function in order to create a custom monad transforme

    - by CharlieP
    Hello, I'm trying to create a monad transformer for a future project, but unfortunately, my implementation of the Monad typeclasse's (=) function doesn't work. First of all, here is the underlying monad's implementation : newtype Runtime a = R { unR :: State EInfo a } deriving (Monad) Here, the implementation of the Monad typeclasse is done automatically by GHC (using the GeneralizedNewtypeDeriving language pragma). The monad transformer is defined as so : newtype RuntimeT m a = RuntimeT { runRuntimeT :: m (Runtime a) } The problem comes from the way I instanciate the (=) function of the Monad typeclasse : instance (Monad m) => Monad (RuntimeT m) where return a = RuntimeT $ (return . return) a x >>= f = runRuntimeT x >>= id >>= f The way I see it, the first >>= runs in the underlying m monad. Thus, runRuntimeT x >>= returns a value of type Runtime a (right ?). Then, the following code, id >>=, should return a value of type a. This value is the passed on to the function f of type f :: (Monad m) => a -> RuntimeT m b. And here comes the type problem : the f function's type doesn't match the type required by the (=) function. Jow can I make this coherent ? I can see why this doesn't work, but I can't manage to turn it into something functionnal. Thank you for you help, and do not hesitate to correct any flaws in my message, Charlie P.

    Read the article

  • Non-trivial functions that operate on any monad

    - by Strilanc
    I'm looking for examples of interesting methods that take an arbitrary monad and do something useful with it. Monads are extremely general, so methods that operate on monads are widely applicable. On the other hand, methods I know of that can apply to any monad tend to be... really, really trivial. Barely worth extracting into a function. Here's a really boring example: joinTwice. It just flattens an m m m t into an m t: join n = n >>= id joinTwice n = (join . join) n main = print (joinTwice [[[1],[2, 3]], [[4]]]) -- prints [1,2,3,4] The only non-trivial method for monads that I know of is bindFold (see my answer below). Are there more?

    Read the article

  • How I understood monads, part 1/2: sleepless and self-loathing in Seattle

    - by Bertrand Le Roy
    For some time now, I had been noticing some interest for monads, mostly in the form of unintelligible (to me) blog posts and comments saying “oh, yeah, that’s a monad” about random stuff as if it were absolutely obvious and if I didn’t know what they were talking about, I was probably an uneducated idiot, ignorant about the simplest and most fundamental concepts of functional programming. Fair enough, I am pretty much exactly that. Being the kind of guy who can spend eight years in college just to understand a few interesting concepts about the universe, I had to check it out and try to understand monads so that I too can say “oh, yeah, that’s a monad”. Man, was I hit hard in the face with the limitations of my own abstract thinking abilities. All the articles I could find about the subject seemed to be vaguely understandable at first but very quickly overloaded the very few concept slots I have available in my brain. They also seemed to be consistently using arcane notation that I was entirely unfamiliar with. It finally all clicked together one Friday afternoon during the team’s beer symposium when Louis was patient enough to break it down for me in a language I could understand (C#). I don’t know if being intoxicated helped. Feel free to read this with or without a drink in hand. So here it is in a nutshell: a monad allows you to manipulate stuff in interesting ways. Oh, OK, you might say. Yeah. Exactly. Let’s start with a trivial case: public static class Trivial { public static TResult Execute<T, TResult>( this T argument, Func<T, TResult> operation) { return operation(argument); } } This is not a monad. I removed most concepts here to start with something very simple. There is only one concept here: the idea of executing an operation on an object. This is of course trivial and it would actually be simpler to just apply that operation directly on the object. But please bear with me, this is our first baby step. Here’s how you use that thing: "some string" .Execute(s => s + " processed by trivial proto-monad.") .Execute(s => s + " And it's chainable!"); What we’re doing here is analogous to having an assembly chain in a factory: you can feed it raw material (the string here) and a number of machines that each implement a step in the manufacturing process and you can start building stuff. The Trivial class here represents the empty assembly chain, the conveyor belt if you will, but it doesn’t care what kind of raw material gets in, what gets out or what each machine is doing. It is pure process. A real monad will need a couple of additional concepts. Let’s say the conveyor belt needs the material to be processed to be contained in standardized boxes, just so that it can safely and efficiently be transported from machine to machine or so that tracking information can be attached to it. Each machine knows how to treat raw material or partly processed material, but it doesn’t know how to treat the boxes so the conveyor belt will have to extract the material from the box before feeding it into each machine, and it will have to box it back afterwards. This conveyor belt with boxes is essentially what a monad is. It has one method to box stuff, one to extract stuff from its box and one to feed stuff into a machine. So let’s reformulate the previous example but this time with the boxes, which will do nothing for the moment except containing stuff. public class Identity<T> { public Identity(T value) { Value = value; } public T Value { get; private set;} public static Identity<T> Unit(T value) { return new Identity<T>(value); } public static Identity<U> Bind<U>( Identity<T> argument, Func<T, Identity<U>> operation) { return operation(argument.Value); } } Now this is a true to the definition Monad, including the weird naming of the methods. It is the simplest monad, called the identity monad and of course it does nothing useful. Here’s how you use it: Identity<string>.Bind( Identity<string>.Unit("some string"), s => Identity<string>.Unit( s + " was processed by identity monad.")).Value That of course is seriously ugly. Note that the operation is responsible for re-boxing its result. That is a part of strict monads that I don’t quite get and I’ll take the liberty to lift that strange constraint in the next examples. To make this more readable and easier to use, let’s build a few extension methods: public static class IdentityExtensions { public static Identity<T> ToIdentity<T>(this T value) { return new Identity<T>(value); } public static Identity<U> Bind<T, U>( this Identity<T> argument, Func<T, U> operation) { return operation(argument.Value).ToIdentity(); } } With those, we can rewrite our code as follows: "some string".ToIdentity() .Bind(s => s + " was processed by monad extensions.") .Bind(s => s + " And it's chainable...") .Value; This is considerably simpler but still retains the qualities of a monad. But it is still pointless. Let’s look at a more useful example, the state monad, which is basically a monad where the boxes have a label. It’s useful to perform operations on arbitrary objects that have been enriched with an attached state object. public class Stateful<TValue, TState> { public Stateful(TValue value, TState state) { Value = value; State = state; } public TValue Value { get; private set; } public TState State { get; set; } } public static class StateExtensions { public static Stateful<TValue, TState> ToStateful<TValue, TState>( this TValue value, TState state) { return new Stateful<TValue, TState>(value, state); } public static Stateful<TResult, TState> Execute<TValue, TState, TResult>( this Stateful<TValue, TState> argument, Func<TValue, TResult> operation) { return operation(argument.Value) .ToStateful(argument.State); } } You can get a stateful version of any object by calling the ToStateful extension method, passing the state object in. You can then execute ordinary operations on the values while retaining the state: var statefulInt = 3.ToStateful("This is the state"); var processedStatefulInt = statefulInt .Execute(i => ++i) .Execute(i => i * 10) .Execute(i => i + 2); Console.WriteLine("Value: {0}; state: {1}", processedStatefulInt.Value, processedStatefulInt.State); This monad differs from the identity by enriching the boxes. There is another way to give value to the monad, which is to enrich the processing. An example of that is the writer monad, which can be typically used to log the operations that are being performed by the monad. Of course, the richest monads enrich both the boxes and the processing. That’s all for today. I hope with this you won’t have to go through the same process that I did to understand monads and that you haven’t gone into concept overload like I did. Next time, we’ll examine some examples that you already know but we will shine the monadic light, hopefully illuminating them in a whole new way. Realizing that this pattern is actually in many places but mostly unnoticed is what will enable the truly casual “oh, yes, that’s a monad” comments. Here’s the code for this article: http://weblogs.asp.net/blogs/bleroy/Samples/Monads.zip The Wikipedia article on monads: http://en.wikipedia.org/wiki/Monads_in_functional_programming This article was invaluable for me in understanding how to express the canonical monads in C# (interesting Linq stuff in there): http://blogs.msdn.com/b/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx

    Read the article

  • How Does The Maybe Monad Relate To The Option Type?

    - by Onorio Catenacci
    I was doing a presentation on F# and was discussing the Option type when someone in the audience asked me if the Option type is F#'s implementation of the maybe monad. I know that's not the case but I did want to ask how the two concepts are related. I mean it seems to me that an option type might be the result of the operation of a maybe monad but I'm not even sure of that. Would someone elucidate the relationship between the maybe monad and the option type in those functional languages which support it?

    Read the article

  • mtl, transformers, monads-fd, monadLib, and the paradox of choice

    - by yairchu
    Hackage has several packages for monad transformers: mtl: Monad transformer library transformers: Concrete functor and monad transformers monads-fd: Monad classes, using functional dependencies monads-tf: Monad classes, using type families monadLib: A collection of monad transformers. mtl-tf: Monad transformer library using type families mmtl: Modular Monad transformer library mtlx: Monad transformer library with type indexes, providing 'free' copies. compose-trans: Composable monad transformers (and maybe I missed some) Which one shall we use? mtl is the one in the Haskell Platform, but I keep hearing on reddit that it's uncool. But what's bad about choice anyway, isn't it just a good thing? Well, I saw how for example the authors of data-accessor had to make all these to cater to just the popular choices: data-accessor-monadLib library: Accessor functions for monadLib's monads data-accessor-monads-fd library: Use Accessor to access state in monads-fd State monad class data-accessor-monads-tf library: Use Accessor to access state in monads-tf State monad type family data-accessor-mtl library: Use Accessor to access state in mtl State monad class data-accessor-transformers library: Use Accessor to access state in transformers State monad I imagine that if this goes on and for example several competing Arrow packages evolve, we might see something like: spoonklink-arrows-transformers, spoonklink-arrows-monadLib, spoonklink-tfArrows-transformers, spoonklink-tfArrows-monadLib, ... And then I worry that if spoonklink gets forked, Hackage will run out of disk space. :) Questions: Why are there so many monad transformer packages? Why is mtl [considered] uncool? What are the key differences? Most of these seemingly competing packages were written by Andy Gill and are maintained by Ross Paterson. Does this mean that these packages are not competing but rather work together in some way? And do Andy and Ross consider any of their own packages as obsolete? Which one should me and you use?

    Read the article

  • Haskell maps returning a monad

    - by sabauma
    The lookup function in Data.Map and Data.IntMap currently return values wrapped in Maybe with the type signature lookup :: Ord k => k -> Map k a -> Maybe a It used to have the more general type of lookup :: (Monad m, Ord k) => k -> Map k a -> m a I realize the former likely reduces the need of extra type specification, but the latter would make it much more general and allow lookup to be used in list comprehensions. Is there any way to mimic this behavior with the newer version, or would I have to use an older version of the library?

    Read the article

  • Appropriate uses of Monad `fail` vs. MonadPlus `mzero`

    - by jberryman
    This is a question that has come up several times for me in the design code, especially libraries. There seems to be some interest in it so I thought it might make a good community wiki. The fail method in Monad is considered by some to be a wart; a somewhat arbitrary addition to the class that does not come from the original category theory. But of course in the current state of things, many Monad types have logical and useful fail instances. The MonadPlus class is a sub-class of Monad that provides an mzero method which logically encapsulates the idea of failure in a monad. So a library designer who wants to write some monadic code that does some sort of failure handling can choose to make his code use the fail method in Monad or restrict his code to the MonadPlus class, just so that he can feel good about using mzero, even though he doesn't care about the monoidal combining mplus operation at all. Some discussions on this subject are in this wiki page about proposals to reform the MonadPlus class. So I guess I have one specific question: What monad instances, if any, have a natural fail method, but cannot be instances of MonadPlus because they have no logical implementation for mplus? But I'm mostly interested in a discussion about this subject. Thanks! EDIT: One final thought occured to me. I recently learned (even though it's right there in the docs for fail) that monadic "do" notation is desugared in such a way that pattern match failures, as in (x:xs) <- return [] call the monad's fail. It seems like the language designers must have been strongly influenced by the prospect of some automatic failure handling built in to haskell's syntax in their inclusion of fail in Monad.

    Read the article

  • Has anyone ever encountered a Monad Transformer in the wild?

    - by martingw
    In my area of business - back office IT for a financial institution - it is very common for a software component to carry a global configuration around, to log it's progress, to have some kind of error handling / computation short circuit... Things that can be modelled nicely by Reader-, Writer-, Maybe-monads and the like in Haskell and composed together with monad transformers. But there seem to some drawbacks: The concept behind monad transformers is quite tricky and hard to understand, monad transformers lead to very complex type signatures, and they inflict some performance penalty. So I'm wondering: Are monad transformers best practice when dealing with those common tasks mentioned above?

    Read the article

  • clojure.algo.monad strange m-plus behaviour with parser-m - why is second m-plus evaluated?

    - by Mark Fisher
    I'm getting unexpected behaviour in some monads I'm writing. I've created a parser-m monad with (def parser-m (state-t maybe-m)) which is pretty much the example given everywhere (here, here and here) I'm using m-plus to act a kind of fall-through query mechanism, in my case, it first reads values from a cache (database), if that returns nil, the next method is to read from "live" (a REST call). However, the second value in the m-plus list is always called, even though its value is disgarded (if the cache hit was good) and the final return is that of the first monadic function. Here's a cutdown version of the issue i'm seeing, and some solutions I found, but I don't know why. My questions are: Is this expected behaviour or a bug in m-plus? i.e. will the 2nd method in a m-plus list always be evaluated if the first item returns a value? Minor in comparison to the above, but if i remove the call _ (fetch-state) from checker, when i evaluate that method, it prints out the messages for the functions the m-plus is calling (when i don't think it should). Is this also a bug? Here's a cut-down version of the code in question highlighting the problem. It simply checks key/value pairs passed in are same as the initial state values, and updates the state to mark what it actually ran. (ns monods.monad-test (:require [clojure.algo.monads :refer :all])) (def parser-m (state-t maybe-m)) (defn check-k-v [k v] (println "calling with k,v:" k v) (domonad parser-m [kv (fetch-val k) _ (do (println "k v kv (= kv v)" k v kv (= kv v)) (m-result 0)) :when (= kv v) _ (do (println "passed") (m-result 0)) _ (update-val :ran #(conj % (str "[" k " = " v "]"))) ] [k v])) (defn filler [] (println "filler called") (domonad parser-m [_ (fetch-state) _ (do (println "filling") (m-result 0)) :when nil] nil)) (def checker (domonad parser-m [_ (fetch-state) result (m-plus ;; (filler) ;; intitially commented out deliberately (check-k-v :a 1) (check-k-v :b 2) (check-k-v :c 3))] result)) (checker {:a 1 :b 2 :c 3 :ran []}) When I run this as is, the output is: > (checker {:a 1 :b 2 :c 3 :ran []}) calling with k,v: :a 1 calling with k,v: :b 2 calling with k,v: :c 3 k v kv (= kv v) :a 1 1 true passed k v kv (= kv v) :b 2 2 true passed [[:a 1] {:a 1, :b 2, :c 3, :ran ["[:a = 1]"]}] I don't expect the line k v kv (= kv v) :b 2 2 true to show at all. The first function to m-plus (as seen in the final output) is what is returned from it. Now, I've found if I pass a filler into m-plus that does nothing (i.e. uncomment the (filler) line) then the output is correct, the :b value isn't evaluated. If I don't have the filler method, and make the first method test fail (i.e. change it to (check-k-v :a 2) then again everything is good, I don't get a call to check :c, only a and b are tested. From my understanding of what the state-t maybe-m transformation is giving me, then the m-plus function should look like: (defn m-plus [left right] (fn [state] (if-let [result (left state)] result (right state)))) which would mean that right isn't called unless left returns nil/false. I'd be interested to know if my understanding is correct or not, and why I have to put the filler method in to stop the extra evaluation (whose effects I don't want to happen). Apologies for the long winded post!

    Read the article

  • Why this Either-monad code does not type check?

    - by pf_miles
    instance Monad (Either a) where return = Left fail = Right Left x >>= f = f x Right x >>= _ = Right x this code frag in 'baby.hs' caused the horrible compilation error: Prelude> :l baby [1 of 1] Compiling Main ( baby.hs, interpreted ) baby.hs:2:18: Couldn't match expected type `a1' against inferred type `a' `a1' is a rigid type variable bound by the type signature for `return' at <no location info> `a' is a rigid type variable bound by the instance declaration at baby.hs:1:23 In the expression: Left In the definition of `return': return = Left In the instance declaration for `Monad (Either a)' baby.hs:3:16: Couldn't match expected type `[Char]' against inferred type `a1' `a1' is a rigid type variable bound by the type signature for `fail' at <no location info> Expected type: String Inferred type: a1 In the expression: Right In the definition of `fail': fail = Right baby.hs:4:26: Couldn't match expected type `a1' against inferred type `a' `a1' is a rigid type variable bound by the type signature for `>>=' at <no location info> `a' is a rigid type variable bound by the instance declaration at baby.hs:1:23 In the first argument of `f', namely `x' In the expression: f x In the definition of `>>=': Left x >>= f = f x baby.hs:5:31: Couldn't match expected type `b' against inferred type `a' `b' is a rigid type variable bound by the type signature for `>>=' at <no location info> `a' is a rigid type variable bound by the instance declaration at baby.hs:1:23 In the first argument of `Right', namely `x' In the expression: Right x In the definition of `>>=': Right x >>= _ = Right x Failed, modules loaded: none. why this happen? and how could I make this code compile ? thanks for any help~

    Read the article

  • Null Safe dereferencing in Java like ?. in Groovy using Maybe monad

    - by Sathish
    I'm working on a codebase ported from Objective C to Java. There are several usages of method chaining without nullchecks dog.collar().tag().name() I was looking for something similar to safe-dereferencing operator ?. in Groovy instead of having nullchecks dog.collar?.tag?.name This led to Maybe monad to have the notion of Nothing instead of Null. But all the implementations of Nothing i came across throw exception when value is accessed which still doesn't solve the chaining problem. I made Nothing return a mock, which behaves like NullObject pattern. But it solves the chaining problem. Is there anything wrong with this implementation of Nothing? [http://github.com/sathish316/jsafederef/blob/master/src/s2k/util/safederef/Nothing.java] As far as i can see 1. It feels odd to use mocking library in code 2. It doesn't stop at the first null. 3. How do i distinguish between null result because of null reference or name actually being null? How is it distinguished in Groovy code?

    Read the article

  • Turtle Graphics as a Haskell Monad

    - by iliis
    I'm trying to implement turtle graphis in Haskell. The goal is to be able to write a function like this: draw_something = do fordward 100 right 90 forward 100 ... and then have it produce a list of points (maybe with additional properties): > draw_something (0,0) 0 -- start at (0,0) facing east (0 degrees) [(0,0), (0,100), (-100,100), ...] I have all this working in a 'normal' way, but I fail to implement it as a Haskell Monad and use the do-notation. The basic code: data State a = State (a, a) a -- (x,y), angle deriving (Show, Eq) initstate :: State Float initstate = State (0.0,0.0) 0.0 -- constrain angles to 0 to 2*pi fmod :: Float -> Float fmod a | a >= 2*pi = fmod (a-2*pi) | a < 0 = fmod (a+2*pi) | otherwise = a forward :: Float -> State Float -> [State Float] forward d (State (x,y) angle) = [State (x + d * (sin angle), y + d * (cos angle)) angle] right :: Float -> State Float -> [State Float] right d (State pos angle) = [State pos (fmod (angle+d))] bind :: [State a] -> (State a -> [State a]) -> [State a] bind xs f = xs ++ (f (head $ reverse xs)) ret :: State a -> [State a] ret x = [x] With this I can now write > [initstate] `bind` (forward 100) `bind` (right (pi/2)) `bind` (forward 100) [State (0.0,0.0) 0.0,State (0.0,100.0) 0.0,State (0.0,100.0) 1.5707964,State (100.0,99.99999) 1.5707964] And get the expected result. However I fail to implement this as an instance of Monad. instance Monad [State] where ... results in `State' is not applied to enough type arguments Expected kind `*', but `State' has kind `* -> *' In the instance declaration for `Monad [State]' And if I wrap the list in a new object data StateList a = StateList [State a] instance Monad StateList where return x = StateList [x] I get Couldn't match type `a' with `State a' `a' is a rigid type variable bound by the type signature for return :: a -> StateList a at logo.hs:38:9 In the expression: x In the first argument of `StateList', namely `[x]' In the expression: StateList [x] I tried various other versions but I never got it to run as I'd like to. What am I doing wrong? What do I understand incorrectly?

    Read the article

  • Continuation monad "interface"

    - by sdcvvc
    The state monad "interface" class MonadState s m where get :: m s put :: s -> m () (+ return and bind) allows to construct any possible computation with State monad without using State constructor. For example, State $ \s -> (s+1, s-1) can be written as do s <- get put (s-1) return (s+1) Similarily, I never have to use Reader constructor, because I can create that computation using ask, return and (>>=). Precisely: Reader f == ask >>= return . f. Is it the same true for continuations - is it possible to write all instances of Cont r a using callCC (the only function in MonadCont), return and bind, and never type something like Cont (\c -> ...)?

    Read the article

  • Is do-notation specific to "base:GHC.Base.Monad"?

    - by yairchu
    The idea that the standard Monad class is flawed and that it should actually extend Functor or Pointed is floating around. I'm not necessarily claiming that it is the right thing to do, but suppose that one was trying to do it: import Prelude hiding (Monad(..)) class Functor m => Monad m where return :: a -> m a join :: m (m a) -> m a join = (>>= id) (>>=) :: m a -> (a -> m b) -> m b a >>= t = join (fmap t a) (>>) :: m a -> m b -> m b a >> b = a >>= const b So far so good, but then when trying to use do-notation: whileM :: Monad m => m Bool -> m () whileM iteration = do done <- iteration if done then return () else whileM iteration The compiler complains: Could not deduce (base:GHC.Base.Monad m) from the context (Monad m) Question: Does do-notation work only for base:GHC.Base.Monad? Is there a way to make it work with an alternative Monad class? Extra context: What I really want to do is replace base:Control.Arrow.Arrow with a "generalized" Arrow class: {-# LANGUAGE TypeFamilies #-} class Category a => Arrow a where type Pair a :: * -> * -> * arr :: (b -> c) -> a b c first :: a b c -> a (Pair a b d) (Pair a c d) second :: a b c -> a (Pair a d b) (Pair a d c) (***) :: a b c -> a b' c' -> a (Pair a b b') (Pair a c c') (&&&) :: a b c -> a b c' -> a b (Pair a c c') And then use the Arrow's proc-notation with my Arrow class, but that fails like in the example above of do-notation and Monad. I'll use mostly Either as my pair type constructor and not the (,) type constructor as with the current Arrow class. This might allow to make the code of my toy RTS game (cabal install DefendTheKind) much prettier.

    Read the article

  • State Monad, why not a tuple?

    - by thr
    I've just wrapped my head around monads (at least I'd like to think I have) and more specifically the state monad, which some people that are way smarter then me figured out, so I'm probably way of with this question. Anyway, the state monad is usually implemented with a M<'a as something like this (F#): type State<'a, 'state> = State of ('state -> 'a * 'state) Now my question: Is there any reason why you couldn't use a tuple here? Other then the possible ambiguity between MonadA<'a, 'b> and MonadB<'a, 'b> which would both become the equivalent ('a * 'b) tuple. Edit: Added example for clarity type StateMonad() = member m.Return a = (fun s -> a, s) member m.Bind(x, f) = (fun s -> let a, s_ = x s in f a s_) let state = new StateMonad() let getState = (fun s -> s, s) let setState s = (fun _ -> (), s) let execute m s = m s |> fst

    Read the article

  • Monad in plain English?

    - by fig-gnuton
    In terms that an OOP programmer would understand (without any functional programming background), what is a monad? What problem does it solve and what are the most common places it's used?

    Read the article

  • What is a monad?

    - by kronoz
    Having briefly looked at Haskell recently I wondered whether anybody could give a brief, succinct, practical explanation as to what a monad essentially is? I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail, so could somebody here help me?

    Read the article

  • How to redirect within a monad in Yesod?

    - by Squazic
    I'm currently using the fb package to write a Yesod app that takes data from Facebook. In my Handler, I've managed to get the first step of the authentication to work, but I need to redirect to the url that getUserAccessTokenStep1 returns, which I've defined as fbRedirUrl. I'm having trouble with all the monad wrapping and type checking to make sure I can redirect to this url. getAccessTokenR :: Handler RepHtml getAccessTokenR = do withManager $ \manager -> do FB.runFacebookT creds manager $ do fbRedirUrl <- FB.getUserAccessTokenStep1 redirUrl [] liftIO $ print fbRedirUrl

    Read the article

  • How can I make a Maybe-Transformer MaybeT into an instance of MonadWriter?

    - by martingw
    I am trying to build a MaybeT-Transformer Monad, based on the example in the Real World Haskell, Chapter Monad Transformers: data MaybeT m a = MaybeT { runMT :: m (Maybe a) } instance (Monad m) => Monad (MaybeT m) where m >>= f = MaybeT $ do a <- runMT m case a of Just x -> runMT (f x) Nothing -> return Nothing return a = MaybeT $ return (Just a) instance MonadTrans MaybeT where lift m = MaybeT $ do a <- m return (Just a) This works fine, but now I want to make MaybeT an instance of MonadWriter: instance (MonadWriter w m) => MonadWriter w (MaybeT m) where tell = lift . tell listen m = MaybeT $ do unwrapped <- listen (runMT m) return (Just unwrapped) The tell is ok, but I can't get the listen function right. The best I could come up with after 1 1/2 days of constructor origami is the one you see above: unwrapped is supposed to be a tuple of (Maybe a, w), and that I want to wrap up in a Maybe-Type and put the whole thing in an empty MonadWriter. But the compiler complains with: Occurs check: cannot construct the infinite type: a = Maybe a When generalising the type(s) for `listen' In the instance declaration for `MonadWriter w (MaybeT m)' What am I missing?

    Read the article

  • What exactly is a Monad?

    - by WeNeedAnswers
    Can someone please explain to me what a Monad is. I think I grasp Monoids and I grasp that they basically control the input of state into a system. I just look at the text in Haskell and glaze over. A simple example in python would be great. My current understanding is that a Monoid is a procedural piece of code that needs to be read from top to bottom in sequence with the output being the input for the function. I think that I may even got that wrong, but hey I am here to learn.

    Read the article

  • trouble with state monad composition

    - by user1308560
    I was trying out the example given at http://www.haskell.org/haskellwiki/State_Monad#Complete_and_Concrete_Example_1 How this makes the solution composible is beyond my understanding. Here is what I tried but I get compile errors as follows: Couldn't match expected type `GameValue -> StateT GameState Data.Functor.Identity.Identity b0' with actual type `State GameState GameValue' In the second argument of `(>>=)', namely `g2' In the expression: g1 >>= g2 In an equation for `g3': g3 = g1 >>= g2 Failed, modules loaded: none. Here is the code: See the end lines module StateGame where import Control.Monad.State type GameValue = Int type GameState = (Bool, Int) -- suppose I want to play one game after the other g1 = playGame "abcaaacbbcabbab" g2 = playGame "abcaaacbbcabb" g3 = g1 >>= g2 m2 = print $ evalState g3 startState playGame :: String -> State GameState GameValue playGame [] = do (_, score) <- get return score playGame (x:xs) = do (on, score) <- get case x of 'a' | on -> put (on, score + 1) 'b' | on -> put (on, score - 1) 'c' -> put (not on, score) _ -> put (on, score) playGame xs startState = (False, 0) main str = print $ evalState (playGame str) startState

    Read the article

  • Futures/Monads vs Events

    - by c69
    So, the question is quite simple: in an application framework, when performance impact can be ignored (10-20 events per second at max), what is more maintainable and flexible to use as a preferred medium for communication between modules - Events or Futures/Promices/Monads ? Its often being said, that Events (pub/sub, mediator) allow loose-coupling and thus - more maintainable app... My experience deny this: once you have more that 20+ events - debugging becomes hard, and so is refactoring - because it is very hard to see: who, when and why uses what. Promices (i'm coding in javascript) are much uglier and dumber, than Events. But: you can clearly see connections between function calls, so application logic becomes more straight-forward. What i'm afraid. though, is that Promices will bring more hard-coupling with them... p.s: the answer does not have to be based on JS, experience from other functional languages is much welcome.

    Read the article

1 2 3 4  | Next Page >