Search Results

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

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

  • 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

  • Threading extra state through a parser in Scala

    - by Travis Brown
    I'll give you the tl;dr up front I'm trying to use the state monad transformer in Scalaz 7 to thread extra state through a parser, and I'm having trouble doing anything useful without writing a lot of t m a -> t m b versions of m a -> m b methods. An example parsing problem Suppose I have a string containing nested parentheses with digits inside them: val input = "((617)((0)(32)))" I also have a stream of fresh variable names (characters, in this case): val names = Stream('a' to 'z': _*) I want to pull a name off the top of the stream and assign it to each parenthetical expression as I parse it, and then map that name to a string representing the contents of the parentheses, with the nested parenthetical expressions (if any) replaced by their names. To make this more concrete, here's what I'd want the output to look like for the example input above: val target = Map( 'a' -> "617", 'b' -> "0", 'c' -> "32", 'd' -> "bc", 'e' -> "ad" ) There may be either a string of digits or arbitrarily many sub-expressions at a given level, but these two kinds of content won't be mixed in a single parenthetical expression. To keep things simple, we'll assume that the stream of names will never contain either duplicates or digits, and that it will always contain enough names for our input. Using parser combinators with a bit of mutable state The example above is a slightly simplified version of the parsing problem in this Stack Overflow question. I answered that question with a solution that looked roughly like this: import scala.util.parsing.combinator._ class ParenParser(names: Iterator[Char]) extends RegexParsers { def paren: Parser[List[(Char, String)]] = "(" ~> contents <~ ")" ^^ { case (s, m) => (names.next -> s) :: m } def contents: Parser[(String, List[(Char, String)])] = "\\d+".r ^^ (_ -> Nil) | rep1(paren) ^^ ( ps => ps.map(_.head._1).mkString -> ps.flatten ) def parse(s: String) = parseAll(paren, s).map(_.toMap) } It's not too bad, but I'd prefer to avoid the mutable state. What I want Haskell's Parsec library makes adding user state to a parser trivially easy: import Control.Applicative ((*>), (<$>), (<*)) import Data.Map (fromList) import Text.Parsec paren = do (s, m) <- char '(' *> contents <* char ')' h : t <- getState putState t return $ (h, s) : m where contents = flip (,) [] <$> many1 digit <|> (\ps -> (map (fst . head) ps, concat ps)) <$> many1 paren main = print $ runParser (fromList <$> paren) ['a'..'z'] "example" "((617)((0)(32)))" This is a fairly straightforward translation of my Scala parser above, but without mutable state. What I've tried I'm trying to get as close to the Parsec solution as I can using Scalaz's state monad transformer, so instead of Parser[A] I'm working with StateT[Parser, Stream[Char], A]. I have a "solution" that allows me to write the following: import scala.util.parsing.combinator._ import scalaz._, Scalaz._ object ParenParser extends ExtraStateParsers[Stream[Char]] with RegexParsers { protected implicit def monadInstance = parserMonad(this) def paren: ESP[List[(Char, String)]] = (lift("(" ) ~> contents <~ lift(")")).flatMap { case (s, m) => get.flatMap( names => put(names.tail).map(_ => (names.head -> s) :: m) ) } def contents: ESP[(String, List[(Char, String)])] = lift("\\d+".r ^^ (_ -> Nil)) | rep1(paren).map( ps => ps.map(_.head._1).mkString -> ps.flatten ) def parse(s: String, names: Stream[Char]) = parseAll(paren.eval(names), s).map(_.toMap) } This works, and it's not that much less concise than either the mutable state version or the Parsec version. But my ExtraStateParsers is ugly as sin—I don't want to try your patience more than I already have, so I won't include it here (although here's a link, if you really want it). I've had to write new versions of every Parser and Parsers method I use above for my ExtraStateParsers and ESP types (rep1, ~>, <~, and |, in case you're counting). If I had needed to use other combinators, I'd have had to write new state transformer-level versions of them as well. Is there a cleaner way to do this? I'd love to see an example of a Scalaz 7's state monad transformer being used to thread state through a parser, but Scala 6 or Haskell examples would also be useful.

    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

  • 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

  • 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

  • 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

  • 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

  • Avoiding explicit recursion in Haskell

    - by Travis Brown
    The following simple function applies a given monadic function iteratively until it hits a Nothing, at which point it returns the last non-Nothing value. It does what I need, and I understand how it works. lastJustM :: (Monad m) => (a -> m (Maybe a)) -> a -> m a lastJustM g x = g x >>= maybe (return x) (lastJustM g) As part of my self-education in Haskell I'm trying to avoid explicit recursion (or at least understand how to) whenever I can. It seems like there should be a simple non-explicitly recursive solution in this case, but I'm having trouble figuring it out. I don't want something like a monadic version of takeWhile, since it could be expensive to collect all the pre-Nothing values, and I don't care about them anyway. I checked Hoogle for the signature and nothing shows up. The m (Maybe a) bit makes me think a monad transformer might be useful here, but I don't really have the intuitions I'd need to come up with the details (yet). It's probably either embarrassingly easy to do this or embarrassingly easy to see why it can't or shouldn't be done, but this wouldn't be the first time I've used self-embarrassment as a pedagogical strategy. Background: Here's a simplified working example for context: suppose we're interested in random walks in the unit square, but we only care about points of exit. We have the following step function: randomStep :: (Floating a, Ord a, Random a) => a -> (a, a) -> State StdGen (Maybe (a, a)) randomStep s (x, y) = do (a, gen') <- randomR (0, 2 * pi) <$> get put gen' let (x', y') = (x + s * cos a, y + s * sin a) if x' < 0 || x' > 1 || y' < 0 || y' > 1 then return Nothing else return $ Just (x', y') Something like evalState (lastJustM (randomStep 0.01) (0.5, 0.5)) <$> newStdGen will give us a new data point.

    Read the article

  • Linking/Combining Type Classes in Haskell

    - by thegravian
    Say I have two type classes defined as follows that are identical in function but different in names: class Monad m where (>>=) :: m a -> (a -> m b) -> m b return :: a -> m a class PhantomMonad p where pbind :: p a -> (a -> p b) -> p b preturn :: a -> p b Is there a way to tie these two classes together so something that is an instance of PhantomMonad will automatically be an instance of Monad, or will instances for each class have to be explicitly written? Any insight would be most appreciated, thanks!

    Read the article

  • Haskell and random numbers

    - by John D.
    Hi, I've been messing with Haskell few days and stumbled into a problem. I need a method that returns a random list of integers ( Rand [[Int]] ). So, I defined a type: type Rand a = StdGen -> (a, StdGen). I was able to produce Rand IO Integer and Rand [IO Integer] ( (returnR lst) :: StdGen -> ([IO Integer], StdGen) ) somehow. Any tips how to produce Rand [[Int]]?

    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

  • What advantage does Monad give us over an Applicative?

    - by arrowdodger
    I've read this article, but didn't understand last section. The author says that Monad gives us context sensitivity, but it's possible to achieve the same result using only an Applicative instance: let maybeAge = (\futureYear birthYear -> if futureYear < birthYear then yearDiff birthYear futureYear else yearDiff futureYear birthYear) <$> (readMay futureYearString) <*> (readMay birthYearString) It's uglier for sure, but beside that I don't see why we need Monad. Can anyone clear this up for me?

    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

  • Do any languages other than haskell/agda have a hindley-milner type system and type classes?

    - by Jimmy Hoffa
    In pondering what gives Haskell such a layer of mental pain in becoming proficient the main thing I can think of are the Monads, Applicatives, Functors, and gaining an intuition to know how a list or maybe will behave in regards to sequence or alternate or bind etc. But why haven't other languages presented these same concepts given the usefulness of monads/applicatives/etc? It occurs to me, type classes are the key, so the question is: Have any languages other than Haskell/Agda actually implemented type classes in the same or similar way?

    Read the article

  • Haskell mutability in compiled state?

    - by pile of junk
    I do not know much about Haskell, but from what I have read about the mutability of computations (e.g: functions returning functions, complex monads and functions, etc.) it seems like you can do a lot of meta-programming, even at runtime. How can Haskell, if everything like functions and monads are so complex, compile to machine code and retain all this?

    Read the article

  • Programming concepts taken from the arts and humanities

    - by Joey Adams
    After reading Paul Graham's essay Hackers and Painters and Joel Spolsky's Advice for Computer Science College Students, I think I've finally gotten it through my thick skull that I should not be loath to work hard in academic courses that aren't "programming" or "computer science" courses. To quote the former: I've found that the best sources of ideas are not the other fields that have the word "computer" in their names, but the other fields inhabited by makers. Painting has been a much richer source of ideas than the theory of computation. — Paul Graham, "Hackers and Painters" There are certainly other, much stronger reasons to work hard in the "boring" classes. However, it'd also be neat to know that these classes may someday inspire me in programming. My question is: what are some specific examples where ideas from literature, art, humanities, philosophy, and other fields made their way into programming? In particular, ideas that weren't obviously applied the way they were meant to (like most math and domain-specific knowledge), but instead gave utterance or inspiration to a program's design and choice of names. Good examples: The term endian comes from Gulliver's Travels by Tom Swift (see here), where it refers to the trivial matter of which side people crack open their eggs. The terms journal and transaction refer to nearly identical concepts in both filesystem design and double-entry bookkeeping (financial accounting). mkfs.ext2 even says: Writing superblocks and filesystem accounting information: done Off-topic: Learning to write English well is important, as it enables a programmer to document and evangelize his/her software, as well as appear competent to other programmers online. Trigonometry is used in 2D and 3D games to implement rotation and direction aspects. Knowing finance will come in handy if you want to write an accounting package. Knowing XYZ will come in handy if you want to write an XYZ package. Arguably on-topic: The Monad class in Haskell is based on a concept by the same name from category theory. Actually, Monads in Haskell are monads in the category of Haskell types and functions. Whatever that means...

    Read the article

  • What Functional features are worth a little OOP confusion for the benefits they bring?

    - by bonomo
    After learning functional programming in Haskell and F#, the OOP paradigm seems ass-backwards with classes, interfaces, objects. Which aspects of FP can I bring to work that my co-workers can understand? Are any FP styles worth talking to my boss about retraining my team so that we can use them? Possible aspects of FP: Immutability Partial Application and Currying First Class Functions (function pointers / Functional Objects / Strategy Pattern) Lazy Evaluation (and Monads) Pure Functions (no side effects) Expressions (vs. Statements - each line of code produces a value instead of, or in addition to causing side effects) Recursion Pattern Matching Is it a free-for-all where we can do whatever the programming language supports to the limit that language supports it? Or is there a better guideline?

    Read the article

  • Acceptable GC frequency for a SlimDX/Windows/.NET game?

    - by Rei Miyasaka
    I understand that the Windows GC is much better than the Xbox/WP7 GC, being that it's generational and multithreaded -- so I don't need to worry quite as much about avoiding memory allocation. SlimDX even has some unavoidable functions that generate some amount of garbage (specifically, MapSubresource creates DataBoxes), yet people don't seem to be too upset about it. I'd like to use some functional paradigms to write my code too, which also means creating objects like closures and monads. I know premature optimization isn't a good thing, but are there rules of thumb or metrics that I can follow to know whether I need to cut down on allocations? Is, say, one gen 0 GC per frame too much? One thing that has me stumped is object promotions. Gen 0 GCs will supposedly finish within a millisecond or two, but if I'm understanding correctly, it's the gen 1 and 2 promotions that start to hurt. I'm not too sure how I can predict/prevent these.

    Read the article

  • What is an acceptable GC frequency for a SlimDX/Windows/.NET game?

    - by Rei Miyasaka
    I understand that the Windows GC is much better than the Xbox/WP7 GC, being that it's generational and multithreaded -- so I don't need to worry quite as much about avoiding memory allocation. SlimDX even has some unavoidable functions that generate some amount of garbage (specifically, MapSubresource creates DataBoxes), yet people don't seem to be too upset about it. I'd like to use some functional paradigms to write my code too, which also means creating objects like closures and monads. I know premature optimization isn't a good thing, but are there rules of thumb or metrics that I can follow to know whether I need to cut down on allocations? Is, say, one gen 0 GC per frame too much? One thing that has me stumped is object promotions. Gen 0 GCs will supposedly finish within a millisecond or two, but if I'm understanding correctly, it's the gen 1 and 2 promotions that start to hurt. I'm not too sure how I can predict/prevent these.

    Read the article

  • Can all code be represented as a series of Map / Filter / Reduce operations?

    - by Mongus Pong
    I have recently been refactoring large chunks of code and replacing them with Linq queries. Removing the language bias - Linq is essentially a set of Map / Filter and Reduce operations that operate on a sequence of data. This got me thinking, how far would I theoretically be able to take this. Would I be able to rewrite the whole code base into a series (or even a single) of Map / Filter and Reduce operations. Unfortunately I get paid to do useful stuff, so I haven't been able to experiment much further, but I can't think of any code structure that couldn't be re structured as such. Side effected code can be dealt with via monads.. Even output is essentially mapping memory addresses to screen addresses. Is there anything that couldn't be (theoretically) rewritten as a Linq query?

    Read the article

  • Is there an imperative language with a Haskell-like type system?

    - by Graham Kaemmer
    I've tried to learn Haskell a few times over the last few years, and, maybe because I know mainly scripting languages, the functional-ness of it has always bothered me (monads seem like a huge mess for doing lots of I/O). However, I think it's type system is perfect. Reading through a guide to Haskell's types and typeclasses (like this), I don't really see a reason why they would require a functional language, and furthermore, they seem like they would be perfect for an industry-grade object-oriented language (like Java). This all begs the question: has anyone ever taken Haskell's typing system and made a imperative, OOP language with it? If so, I want to use it.

    Read the article

  • Which is your favorite "hidden gem" package on Hackage?

    - by finnsson
    There are a lot of packages on Hackage, some well known (such as HUnit) and some less known (such as AspectAG). I'm wondering which package you think is a hidden gem that deserves more users. Maybe a useful data structure, helpers for monads, networking, test, ...? Which is your favorite "hidden gem" package on Hackage?

    Read the article

< Previous Page | 1 2 3  | Next Page >