Search Results

Search found 65 results on 3 pages for 'monads'.

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

  • 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

  • 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

  • Monads with Join() instead of Bind()

    - by MathematicalOrchid
    Monads are usually explained in turns of return and bind. However, I gather you can also implement bind in terms of join (and fmap?) In programming languages lacking first-class functions, bind is excruciatingly awkward to use. join, on the other hand, looks quite easy. I'm not completely sure I understand how join works, however. Obviously, it has the [Haskell] type join :: Monad m = m (m x) - m x For the list monad, this is trivially and obviously concat. But for a general monad, what, operationally, does this method actually do? I see what it does to the type signatures, but I'm trying to figure out how I'd write something like this in, say, Java or similar. (Actually, that's easy: I wouldn't. Because generics is broken. ;-) But in principle the question still stands...) Oops. It looks like this has been asked before: Monad join function Could somebody sketch out some implementations of common monads using return, fmap and join? (I.e., not mentioning >>= at all.) I think perhaps that might help it to sink in to my dumb brain...

    Read the article

  • Resources for learning Monads, Functors, Monoids, Arrows etc

    - by Dony Borris
    Can you people please suggest some good books / weblinks from where I can get to learn about above mentioned concepts? (Please note that I am a Java programmer and have NO prior experience with functional programming. I have been studying Scala since last one month and would appreciate the resources that try to teach the above mentioned concepts with Scala. (or even Java, if posible))

    Read the article

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

    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, thats a monad about random stuff as if it were absolutely obvious and if I didnt 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...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    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

  • Must a Language that Implements Monads be Statically Typed?

    - by Morgan Cheng
    I am learning functional programming style. From this link http://channel9.msdn.com/shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads/, Brian Beckman gave a brilliant introduction about Monad. He mentioned that Monad is about composition of functions so as to address complexity. A Monad includes a unit function that transfers type T to an amplified type M(T); and a Bind function that, given function from T to M(U), transforms type M(T) to another type M(U). (U can be T, but is not necessarily). In my understanding, the language implementing monad should be type-checked statically. Otherwise, type errors cannot be found during compilation and "Complexity" is not controlled. Is my understanding correct?

    Read the article

  • Are monads Writer m and Either e categorically dual?

    - by sdcvvc
    I noticed there is a dual relation between Writer m and Either e monads. If m is a monoid, then unit :: () -> m join :: (m,m) -> m can be used to form a monad: return is composition: a -> ((),a) -> (m,a) join is composition: (m,(m,a)) -> ((m,m),a) -> (m,a) The dual of () is Void (empty type), the dual of product is coproduct. Every type e can be given "comonoid" structure: unit :: Void -> e join :: Either e e -> e in the obvious way. Now, return is composition: a -> Either Void a -> Either e a join is composition: Either e (Either e a) -> Either (Either e e) a -> Either e a and this is the Either e monad. The arrows follow exactly the same pattern. Question: Is it possible to write a single generic code that will be able to perform both as Either e and as Writer m depending on the monoid given?

    Read the article

  • Can Haskell's monads be thought of as using and returning a hidden state parameter?

    - by AJM
    I don't understand the exact algebra and theory behind Haskell's monads. However, when I think about functional programming in general I get the impression that state would be modelled by taking an initial state and generating a copy of it to represent the next state. This is like when one list is appended to another; neither list gets modified, but a third list is created and returned. Is it therefore valid to think of monadic operations as implicitly taking an initial state object as a parameter and implicitly returning a final state object? These state objects would be hidden so that the programmer doesn't have to worry about them and to control how they gets accessed. So, the programmer would not try to copy the object representing the IO stream as it was ten minutes ago. In other words, if we have this code: main = do putStrLn "Enter your name:" name <- getLine putStrLn ( "Hello " ++ name ) ...is it OK to think of the IO monad and the "do" syntax as representing this style of code? putStrLn :: IOState -> String -> IOState getLine :: IOState -> (IOState, String) main :: IOState -> IOState -- main returns an IOState we can call "state3" main state0 = putStrLn state2 ("Hello " ++ name) where (state2, name) = getLine state1 state1 = putStrLn state0 "Enter your name:"

    Read the article

  • Help a C# developer understand: What is a monad?

    - by Charlie Flowers
    There is a lot of talk about monads these days. I have read a few articles / blog posts, but I can't go far enough with their examples to fully grasp the concept. The reason is that monads are a functional language concept, and thus the examples are in languages I haven't worked with (since I haven't used a functional language in depth). I can't grasp the syntax deeply enough to follow the articles fully ... but I can tell there's something worth understanding there. However, I know C# pretty well, including lambda expressions and other functional features. I know C# only has a subset of functional features, and so maybe monads can't be expressed in C#. However, surely it is possible to convey the concept? At least I hope so. Maybe you can present a C# example as a foundation, and then describe what a C# developer would wish he could do from there but can't because the language lacks functional programming features. This would be fantastic, because it would convey the intent and benefits of monads. So here's my question: What is the best explanation you can give of monads to a C# 3 developer? Thanks! (EDIT: By the way, I know there are at least 3 "what is a monad" questions already on SO. However, I face the same problem with them ... so this question is needed imo, because of the C#-developer focus. Thanks.)

    Read the article

  • Monad in plain English? (For the OOP programmer with no FP background)

    - 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? EDIT: To clarify the kind of understanding I was looking for, let's say you were converting an FP application that had monads into an OOP application. What would you do to port the responsibilities of the monads into the OOP app?

    Read the article

  • Monads and custom traversal functions in Haskell

    - by Bill
    Given the following simple BST definition: data Tree x = Empty | Leaf x | Node x (Tree x) (Tree x) deriving (Show, Eq) inOrder :: Tree x -> [x] inOrder Empty = [] inOrder (Leaf x) = [x] inOrder (Node root left right) = inOrder left ++ [root] ++ inOrder right I'd like to write an in-order function that can have side effects. I achieved that with: inOrderM :: (Show x, Monad m) => (x -> m a) -> Tree x -> m () inOrderM f (Empty) = return () inOrderM f (Leaf y) = f y >> return () inOrderM f (Node root left right) = inOrderM f left >> f root >> inOrderM f right -- print tree in order to stdout inOrderM print tree This works fine, but it seems repetitive - the same logic is already present in inOrder and my experience with Haskell leads me to believe that I'm probably doing something wrong if I'm writing a similar thing twice. Is there any way that I can write a single function inOrder that can take either pure or monadic functions?

    Read the article

  • An unusual type signature

    - by Travis Brown
    In Monads for natural language semantics, Chung-Chieh Shan shows how monads can be used to give a nicely uniform restatement of the standard accounts of some different kinds of natural language phenomena (interrogatives, focus, intensionality, and quantification). He defines two composition operations, A_M and A'_M, that are useful for this purpose. The first is simply ap. In the powerset monad ap is non-deterministic function application, which is useful for handling the semantics of interrogatives; in the reader monad it corresponds to the usual analysis of extensional composition; etc. This makes sense. The secondary composition operation, however, has a type signature that just looks bizarre to me: (<?>) :: (Monad m) => m (m a -> b) -> m a -> m b (Shan calls it A'_M, but I'll call it <?> here.) The definition is what you'd expect from the types; it corresponds pretty closely to ap: g <?> x = g >>= \h -> return $ h x I think I can understand how this does what it's supposed to in the context of the paper (handle question-taking verbs for interrogatives, serve as intensional composition, etc.). What it does isn't terribly complicated, but it's a bit odd to see it play such a central role here, since it's not an idiom I've seen in Haskell before. Nothing useful comes up on Hoogle for either m (m a -> b) -> m a -> m b or m (a -> b) -> a -> m b. Does this look familiar to anyone from other contexts? Have you ever written this function?

    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

  • is this a simple monad example?

    - by zcaudate
    This is my attempt to grok monadic functions after watching http://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads. h uses bind to compose together two arbitrary functions f and g. What is the unit operator in this case? ;; f :: int - [str] ;; g :: str = [keyword] ;; bind :: [str] - (str - [keyword]) - [keyword] ;; h :: int - [keyword] (defn f [v] (map str (range v))) (defn g [s] (map keyword (repeat 4 s))) (defn bind [l f] (flatten (map f l))) (f 8) ;; = (0 1 2 3 4 5 6 7) (g "s") ;; = (:s :s :s :s) (defn h [v] (bind (f v) g)) (h 9) ;; = (:0 :0 :0 :0 :1 :1 :1 :1 :2 :2 :2 :2 :3 :3 :3 :3 :4 :4 :4 :4 :5 :5 :5 :5)

    Read the article

  • Where can I learn advanced Haskell?

    - by FredOverflow
    In a comment to one of my answers, SO user sdcwc essentially pointed out that the following code: comb 0 = [[]] comb n = let rest = comb (n-1) in map ('0':) rest ++ map ('1':) rest could be replaced by: comb n = replicateM n "01" which had me completely stunned. Now I am looking for a tutorial, book or PDF that teaches these advanced concepts. I am not looking for a "what's a monad" tutorial aimed at beginners or online references explaining the type of replicateM. I want to learn how to think in monads and use them effectively, monadic "patterns" if you will.

    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

  • Performance of looping over an Unboxed array in Haskell

    - by Joey Adams
    First of all, it's great. However, I came across a situation where my benchmarks turned up weird results. I am new to Haskell, and this is first time I've gotten my hands dirty with mutable arrays and Monads. The code below is based on this example. I wrote a generic monadic for function that takes numbers and a step function rather than a range (like forM_ does). I compared using my generic for function (Loop A) against embedding an equivalent recursive function (Loop B). Having Loop A is noticeably faster than having Loop B. Weirder, having both Loop A and B together is faster than having Loop B by itself (but slightly slower than Loop A by itself). Some possible explanations I can think of for the discrepancies. Note that these are just guesses: Something I haven't learned yet about how Haskell extracts results from monadic functions. Loop B faults the array in a less cache efficient manner than Loop A. Why? I made a dumb mistake; Loop A and Loop B are actually different. Note that in all 3 cases of having either or both Loop A and Loop B, the program produces the same output. Here is the code. I tested it with ghc -O2 for.hs using GHC version 6.10.4 . import Control.Monad import Control.Monad.ST import Data.Array.IArray import Data.Array.MArray import Data.Array.ST import Data.Array.Unboxed for :: (Num a, Ord a, Monad m) => a -> a -> (a -> a) -> (a -> m b) -> m () for start end step f = loop start where loop i | i <= end = do f i loop (step i) | otherwise = return () primesToNA :: Int -> UArray Int Bool primesToNA n = runSTUArray $ do a <- newArray (2,n) True :: ST s (STUArray s Int Bool) let sr = floor . (sqrt::Double->Double) . fromIntegral $ n+1 -- Loop A for 4 n (+ 2) $ \j -> writeArray a j False -- Loop B let f i | i <= n = do writeArray a i False f (i+2) | otherwise = return () in f 4 forM_ [3,5..sr] $ \i -> do si <- readArray a i when si $ forM_ [i*i,i*i+i+i..n] $ \j -> writeArray a j False return a primesTo :: Int -> [Int] primesTo n = [i | (i,p) <- assocs . primesToNA $ n, p] main = print $ primesTo 30000000

    Read the article

  • C# ambiguity in Func + extension methods + lambdas

    - by Hobbes
    I've been trying to make my way through this article: http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx ... And something on page 1 made me uncomfortable. In particular, I was trying to wrap my head around the Compose<() function, and I wrote an example for myself. Consider the following two Func's: Func<double, double> addTenth = x => x + 0.10; Func<double, string> toPercentString = x => (x * 100.0).ToString() + "%"; No problem! It's easy to understand what these two do. Now, following the example from the article, you can write a generic extension method to compose these functions, like so: public static class ExtensionMethods { public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>( this Func<TFirstOutput, TLastOutput> toPercentString, Func<TInput, TFirstOutput> addTenth) { return input => toPercentString(addTenth(input)); } } Fine. So now you can say: string x = toPercentString.Compose<double, double, string>(addTenth)(0.4); And you get the string "50%" So far, so good. But there's something ambiguous here. Let's say you write another extension method, so now you have two functions: public static class ExtensionMethods { public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>( this Func<TFirstOutput, TLastOutput> toPercentString, Func<TInput, TFirstOutput> addTenth) { return input => toPercentString(addTenth(input)); } public static Func<double, string> Compose<TInput, TFirstOutput, TLastOutput>(this Func<double, string> toPercentString, Func<double, double> addTenth) { return input => toPercentString(addTenth(input + 99999)); } } Herein is the ambiguity. Don't these two function have overlapping signatures? Yes. Does this even compile? Yes. Which one get's called? The second one (which clearly gives you the "wrong" result) gets called. If you comment out either function, it still compiles, but you get different results. It seems like nitpicking, but there's something that deeply offends my sensibilities here, and I can't put my finger on it. Does it have to do with extension methods? Does it have to do with lambdas? Or does it have to do with how Func< allows you to parameterize the return type? I'm not sure. I'm guessing that this is all addressed somewhere in the spec, but I don't even know what to Google to find this. Help!

    Read the article

  • Haskell: monadic takeWhile?

    - by Mark Rushakoff
    I have some functions written in C that I call from Haskell. These functions return IO (CInt). Sometimes I want to run all of the functions regardless of what any of them return, and this is easy. For sake of example code, this is the general idea of what's happening currently: Prelude> let f x = print x >> return x Prelude> mapM_ f [0..5] 0 1 2 3 4 5 Prelude> I get my desired side effects, and I don't care about the results. But now I need to stop execution immediately after the first item that doesn't return my desired result. Let's say a return value of 4 or higher requires execution to stop - then what I want to do is this: Prelude> takeWhile (<4) $ mapM f [0..5] Which gives me this error: <interactive:1:22: Couldn't match expected type `[b]' against inferred type `IO a' In the first argument of `mapM', namely `f' In the second argument of `($)', namely `mapM f ([0 .. 5])' In the expression: takeWhile (< 4) $ mapM f ([0 .. 5]) And that makes sense to me - the result is still contained in the IO monad, and I can't just compare two values contained in the IO monad. I know this is precisely the purpose of monads -- chaining results together and discarding operations when a certain condition is met -- but is there an easy way to "wrap up" the IO monad in this case to stop executing the chain upon a condition of my choosing, without writing an instance of MonadPlus? Can I just "unlift" the values from f, for the purposes of the takeWhile? Is this a solution where functors fit? Functors haven't "clicked" with me yet, but I sort of have the impression that this might be a good situation to use them. Update: @sth has the closest answer to what I want - in fact, that's almost exactly what I was going for, but I'd still like to see whether there is a standard solution that isn't explicitly recursive -- this is Haskell, after all! Looking back on how I worded my question, now I can see that I wasn't clear enough about my desired behavior. The f function I used above for an example was merely an example. The real functions are written in C and used exclusively for their side effects. I can't use @Tom's suggestion of mapM_ f (takeWhile (&lt;4) [0..5]) because I have no idea whether any input will really result in success or failure until executed. I don't actually care about the returned list, either -- I just want to call the C functions until either the list is exhausted or the first C function returns a failure code. In C-style pseudocode, my behavior would be: do { result = function_with_side_effects(input_list[index++]); } while (result == success && index < max_index); So again, @sth's answer performs the exact behavior that I want, except that the results may (should?) be discarded. A dropWhileM_ function would be equivalent for my purposes. Why isn't there a function like that or takeWhileM_ in Control.Monad? I see that there was a similar discussion on a mailing list, but it appears that nothing has come of that.

    Read the article

  • Haskell Monad bind currying

    - by Chime
    I am currently in need of a bit of brain training and I found this article on Haskell and Monads I'm having trouble with exercise 7 re. Randomised function bind. To make the problem even simpler to experiment, I replaced the StdGen type with an unspecified type. So instead of... bind :: (a -> StdGen -> (b,StdGen)) -> (StdGen -> (a,StdGen)) -> (StdGen -> (b,StdGen)) I used... bind :: (a -> c -> (b,c)) -> (c -> (a,c)) -> (c -> (b,c)) and for the actual function impelemtation (just straight from the exercise) bind f x seed = let (x',seed') = x seed in f x' seed' and also 2 randomised functions to trial with: rndf1 :: (Num a, Num b) => a -> b -> (a,b) rndf1 a s = (a+1,s+1) rndf2 :: (Num a, Num b) => a -> b -> (a,b) rndf2 a s = (a+8,s+2) So with this in a Haskell compiler (ghci), I get... :t bind rndf2 bind rndf2 :: (Num a, Num c) => (c -> (a, c)) -> c -> (a, c) This matches the bind curried with rndf2 as the first parameter. But the thing I don't understand is how... :t bind rndf2 . rndf1 Suddenly gives bind rndf2 . rndf1 :: (Num a, Num c) => a -> c -> (a, c) This is the correct type of the composition that we are trying to produce because bind rndf2 . rndf1 Is a function that: takes the same parameter type(s) as rndf1 AND takes the return from rndf1 and pipes it as an input of rndf2 to return the same type as rndf2 rndf1 can take 2 parameters a -> c and rndf2 returns (a, c) so it matches that a composition of these function should have type: bind rndf2 . rndf1 :: (Num a, Num c) => a -> c -> (a, c) This does not match the naive type that I initially came up with for bind bind f :: (a -> b -> (c, d)) -> (c, d) -> (e, f) Here bind mythically takes a function that takes two parameters and produces a function that takes a tuple in order that the output from rndf1 can be fed into rndf2 why the bind function needs to be coded as it is Why the bind function does not have the naive type

    Read the article

  • How do i convert String to Integer/Float in Haskell

    - by Ranhiru
    data GroceryItem = CartItem ItemName Price Quantity | StockItem ItemName Price Quantity makeGroceryItem :: String -> Float -> Int -> GroceryItem makeGroceryItem name price quantity = CartItem name price quantity I want to create a GroceryItem when using a String or [String] createGroceryItem :: [String] -> GroceryItem createGroceryItem (a:b:c) = makeGroceryItem a b c The input will be in the format ["Apple","15.00","5"] which i broke up using words function in haskell. I get this error which i think is because the makeGroceryItem accepts a Float and an Int. But how do i make b and c Float and Int respectively? *Type error in application *** Expression : makeGroceryItem a read b read c *** Term : makeGroceryItem *** Type : String -> Float -> Int -> GroceryItem *** Does not match : a -> b -> c -> d -> e -> f* Thanx a lot in advance :)

    Read the article

1 2 3  | Next Page >