Creating a list with do notation
List is a monad, does that mean i can create a list with do notation? My intuition led me to believe this would work: main = do x <- return $ do 1 2 3 print (x :: [Int]) However it didn't. Is this possible?
Yes, but it might not work quite the way you expect: Prelude> do { a <- [1]; (a:[2]) } [1,2] Prelude> do { a <- [1]; b <- (a:[2]); (b:[3]) } [1,3,2,3] - Lucas Paul On Thu, Jan 22, 2015 at 9:04 PM, Cody Goodman <codygman.consulting@gmail.com> wrote:
List is a monad, does that mean i can create a list with do notation?
My intuition led me to believe this would work:
main = do x <- return $ do 1 2 3 print (x :: [Int])
However it didn't. Is this possible?
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
The items in your do-block must be in the same monad as you're operating in - in this example - the list monad: main = do x <- return $ do [ 1 ] [ 2 ] [ 3 ] print (x :: [Int]) Unfortunately, there is no accumulation of items. You can reason this out if you desugar the do-notation into binds: [ 1 ] >> [ 2 ] >> [ 3 ] [ 1 ] >>= (\x -> [ 2 ] >>= (\y -> [ 3 ])) and then examine the list Monad instance. You can achieve something similar to what you're looking for with the writer monad: import Control.Monad.Writer.Lazy main = do x <- return $ execWriter $ do tell [1] tell [2] tell [3] print (x :: [Int]) On Fri, Jan 23, 2015 at 3:04 PM, Cody Goodman <codygman.consulting@gmail.com
wrote:
List is a monad, does that mean i can create a list with do notation?
My intuition led me to believe this would work:
main = do x <- return $ do 1 2 3 print (x :: [Int])
However it didn't. Is this possible?
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
On 2015-01-22 11:04 PM, Cody Goodman wrote:
List is a monad, does that mean i can create a list with do notation?
My http://www.vex.net/~trebla/haskell/forwardconstraint/ForwardConstraint.html is a great example. The source code is behind some link at the top.
participants (4)
-
Albert Y. C. Lai -
Cody Goodman -
Lucas Paul -
Lyndon Maydwell