From objitsu at gmail.com Wed Apr 1 08:44:30 2015 From: objitsu at gmail.com (emacstheviking) Date: Wed, 1 Apr 2015 09:44:30 +0100 Subject: [Haskell-beginners] Mutable collection of gui objects (wxHaskell) In-Reply-To: References: Message-ID: No wonder Haskell won't catch on... I saw code that looked just like that on the wall of a pyramid on an episode Ancient Aliens recently! April fool by the way! On 31 March 2015 at 23:51, Henk-Jan van Tuyl wrote: > On Tue, 31 Mar 2015 22:11:47 +0200, Jeffrey Brown > wrote: > > It works! And I don't understand it! Particularly this line: >> >> inputs <- map (\e -> [hfill $ widget e]) <$> varGet myVar >> >> I'm considering the type signatures: >> map :: (a -> b) -> [a] -> [b] >> (<$>) :: Functor f => (a -> b) -> f a -> f b >> varGet :: Var a -> IO a >> map and <$> (fmap) are nearly synonymous; map seems like a special case of >> fmap. I gather the fmap must be to map inside the IO type that varGet >> returns, and the map must be mapping across some list. But what about >> their >> function arguments? Is map using the lambda expression, or is fmap? What >> function argument is the other one using? Are they both somehow sharing >> the >> lambda expression? >> > > The expression > f <$> x > is equal to > fmap f x > . If > f :: a -> b > x :: IO a > then > fmap f :: IO a -> IO b > . You could say, fmap lifts f to the IO monad (you could also use liftM > for this). > > In your case, f is > map (\e -> [hfill $ widget e]) > and x is > varGet myVar > You stored a list of textEntrys in myVar, the lambda expression is mapped > over this list. > > Another way to look at it: you can replace the line > inputs <- map (\e -> [hfill $ widget e]) <$> varGet myVar > with > xs <- varGet myVar > let inputs = map (\e -> [hfill $ widget e]) xs > > Regards, > Henk-Jan van Tuyl > > > -- > Folding at home > What if you could share your unused computer power to help find a cure? In > just 5 minutes you can join the world's biggest networked computer and get > us closer sooner. Watch the video. > http://folding.stanford.edu/ > > > http://Van.Tuyl.eu/ > http://members.chello.nl/hjgtuyl/tourdemonad.html > Haskell programming > -- > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Wed Apr 1 15:08:42 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Wed, 1 Apr 2015 16:08:42 +0100 Subject: [Haskell-beginners] Random Generator Message-ID: Hi, I am trying to use the output value from the random function to generate the random generator for the next value in list. Below is the code - ---- import System.Random myrandoms :: (RandomGen g, Random a) => g -> [a] myrandoms gen = let (value, newGen) = random gen in value:myrandoms (mkStdGen (value::Int)) ---- however the compilation fails when the module is loaded - [1 of 1] Compiling Main ( myrandoms.hs, interpreted ) myrandoms.hs:3:80: Could not deduce (a ~ Int) from the context (RandomGen g, Random a) bound by the type signature for myrandoms :: (RandomGen g, Random a) => g -> [a] at myrandoms.hs:2:14-48 `a' is a rigid type variable bound by the type signature for myrandoms :: (RandomGen g, Random a) => g -> [a] at myrandoms.hs:2:14 Relevant bindings include value :: a (bound at myrandoms.hs:3:22) myrandoms :: g -> [a] (bound at myrandoms.hs:3:1) In the first argument of `mkStdGen', namely `(value :: Int)' In the first argument of `myrandoms', namely `(mkStdGen (value :: Int))' ---------- Even though I am converting my 'value' parameter to Int in my new generator, I am unable to see the error behind this. Please can someone explain or even better provide a fix. Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From allbery.b at gmail.com Wed Apr 1 15:19:47 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Wed, 1 Apr 2015 11:19:47 -0400 Subject: [Haskell-beginners] Random Generator In-Reply-To: References: Message-ID: On Wed, Apr 1, 2015 at 11:08 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > myrandoms :: (RandomGen g, Random a) => g -> [a] > myrandoms gen = let (value, newGen) = random gen in value:myrandoms > (mkStdGen (value::Int)) > You have declared a function that says that it can deal with any type `a` that the *caller* chooses, then provided an implementation that only supports Int. Note that :: does not do conversion (as you said "Even though I am converting my 'value' parameter to Int"); it declares that the type of `value` *is* Int. Other types will be inferred to match, and this fails at `value:` in a context which wants the type to be a caller-specified `a`, not Int. (I don't think you can coerce an unknown type `a` to Int given only the context `Random a`. You must find a different way to implement this.) -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From toad3k at gmail.com Wed Apr 1 15:32:48 2015 From: toad3k at gmail.com (David McBride) Date: Wed, 1 Apr 2015 11:32:48 -0400 Subject: [Haskell-beginners] Random Generator In-Reply-To: References: Message-ID: mkStdGen only accepts Ints as seeds. But your random function, as you typed it, can return any type of random. You either have to restrict your random function to returning ints, like so: myrandoms :: (RandomGen g) => g -> [Int] myrandoms gen = let (value, newGen) = random gen in value:myrandoms (mkStdGen value) Or you have to find a way to convert any Random a into an Int (not possible), or put another constraint on it, such that you can return all the types you might want that you have the ability to turn into ints, for example: myrandoms :: (RandomGen g, Random a, Intable a) => g -> [a] myrandoms gen = let (value, newGen) = random gen in value:myrandoms (mkStdGen $ convertToInt value) class Intable a where convertToInt :: a -> Int instance Intable Int where convertToInt = id instance Intable Integer where convertToInt = fromIntegral instance Intable Char where convertToInt s = undefined -- something Which is obviously tedious, but may be worthwhile depending on your application. On Wed, Apr 1, 2015 at 11:08 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > Hi, > > I am trying to use the output value from the random function to generate > the random generator for the next value in list. > > Below is the code - > > ---- > import System.Random > myrandoms :: (RandomGen g, Random a) => g -> [a] > myrandoms gen = let (value, newGen) = random gen in value:myrandoms > (mkStdGen (value::Int)) > ---- > > however the compilation fails when the module is loaded - > > [1 of 1] Compiling Main ( myrandoms.hs, interpreted ) > > myrandoms.hs:3:80: > Could not deduce (a ~ Int) > from the context (RandomGen g, Random a) > bound by the type signature for > myrandoms :: (RandomGen g, Random a) => g -> [a] > at myrandoms.hs:2:14-48 > `a' is a rigid type variable bound by > the type signature for > myrandoms :: (RandomGen g, Random a) => g -> [a] > at myrandoms.hs:2:14 > Relevant bindings include > value :: a (bound at myrandoms.hs:3:22) > myrandoms :: g -> [a] (bound at myrandoms.hs:3:1) > In the first argument of `mkStdGen', namely `(value :: Int)' > In the first argument of `myrandoms', namely > `(mkStdGen (value :: Int))' > > ---------- > > Even though I am converting my 'value' parameter to Int in my new > generator, I am unable to see the error behind this. > > Please can someone explain or even better provide a fix. > > Thanks, > Shishir > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chaddai.fouche at gmail.com Wed Apr 1 20:43:47 2015 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Wed, 1 Apr 2015 22:43:47 +0200 Subject: [Haskell-beginners] Why does QuickCheck insist on this class constraint? In-Reply-To: <55193204.90305@web.de> References: <55193204.90305@web.de> Message-ID: Why are you putting those type signatures everywhere ? Won't your code compile without them ? It seems to me that absent a strange Change type, all those things can be inferred... Are you doing this as an exercise or because you think it is more readable ? -- Jeda? -------------- next part -------------- An HTML attachment was scrubbed... URL: From chaddai.fouche at gmail.com Wed Apr 1 21:04:05 2015 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Wed, 1 Apr 2015 23:04:05 +0200 Subject: [Haskell-beginners] Random Generator In-Reply-To: References: Message-ID: On Wed, Apr 1, 2015 at 5:32 PM, David McBride wrote: > mkStdGen only accepts Ints as seeds. But your random function, as you > typed it, can return any type of random. You either have to restrict your > random function to returning ints, like so: > > myrandoms :: (RandomGen g) => g -> [Int] > myrandoms gen = let (value, newGen) = random gen in value:myrandoms > (mkStdGen value) > *Is there any good reason we're not using newGen for its intended purpose here and instead weakening our randomness, maybe extremely (imagine if a list a Bool is asked for...) ???* > > Or you have to find a way to convert any Random a into an Int (not > possible), or put another constraint on it, such that you can return all > the types you might want that you have the ability to turn into ints, for > example: > > myrandoms :: (RandomGen g, Random a, Intable a) => g -> [a] > myrandoms gen = let (value, newGen) = random gen in value:myrandoms > (mkStdGen $ convertToInt value) > > class Intable a where > convertToInt :: a -> Int > > instance Intable Int where convertToInt = id > instance Intable Integer where convertToInt = fromIntegral > instance Intable Char where convertToInt s = undefined -- something > > Which is obviously tedious, but may be worthwhile depending on your > application. > > If this was really the way Shishir wanted to go, I would suggest simply reusing the Enum typeclass rather than creating a new Intable typeclass, since : fromEnum :: (Enum a) => a -> Int Still a very bad and puzzling idea by the way... -- Jeda? -------------- next part -------------- An HTML attachment was scrubbed... URL: From konstantin.saveljev at gmail.com Wed Apr 1 21:11:58 2015 From: konstantin.saveljev at gmail.com (Konstantin Saveljev) Date: Thu, 2 Apr 2015 00:11:58 +0300 Subject: [Haskell-beginners] Lens: zooming Message-ID: Hello, I have this newtype: newtype Awesome a = Awesome (StateT AwesomeState (ExceptT B.ByteString IO) a) deriving (Functor, Applicative, Monad, MonadIO, MonadError B.ByteString, MonadState AwesomeState) AwesomeState is quite deeply nested record. I'm using lens package in my project and can use some basic primitives from that package. But today I read about 'zoom' from lens package and think it might help me write my code a bit faster and cleaner. Right now if I try to update something deeply nested in my state I do it by hand (pseudocode follows): smth <- use $ myState.thisField.otherField myState.thisField.otherField .= smth { _someProperty = "aaa", _otherThing = (smth^.otherThing) { _hereIsSomethingElse = 2 } } and so on. I hope you get the picture. Now I though with zooming I would be able to do it more easily: zoom (myState.thisField.OtherField) $ do someProperty .= "aaa" otherThing.hereIsSomethingElse .= 2 But the problem is that if I try to use zoom I get an error message which I do not understand how to handle. Tried to search for information but couldn't get anything that I could understand (just found a single stackoverflow question which didn't clear it enough for me). The error message: Couldn't match type ?Control.Lens.Internal.Zoom.Zoomed Awesome? with ?Control.Lens.Internal.Zoom.Zoomed m0? Anyone could suggest what it is that I need to do to be able to use 'zoom'? Best regards, Konstantin Saveljev -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcin.jan.mrotek at gmail.com Wed Apr 1 21:44:38 2015 From: marcin.jan.mrotek at gmail.com (Marcin Mrotek) Date: Wed, 1 Apr 2015 23:44:38 +0200 Subject: [Haskell-beginners] Lens: zooming In-Reply-To: References: Message-ID: Hello, Well, to properly implement zoom, you'd have to use a similar approach to http://hackage.haskell.org/package/lens-4.8/docs/Control-Lens-Internal-Zoom.html and implement the Zoom type class. Perhaps try implementing http://hackage.haskell.org/package/mmorph-1.0.4/docs/Control-Monad-Morph.html and use (hoist $ zoom whatever) instead? Best regards, Marcin Mrotek From filtered02 at seesolve.com Fri Apr 3 20:13:47 2015 From: filtered02 at seesolve.com (sojourner) Date: Fri, 3 Apr 2015 16:13:47 -0400 Subject: [Haskell-beginners] Haskell Platform SHA Message-ID: Downloaded Haskell Platform 2014.2.0.0.0 for Mac OSX from https://www.haskell.org/platform/mac.html. Twice. The SHA-256 on the web page is 62f39246ad95dd2aed6ece5138f6297f945d2b450f215d074820294310e0c48a. But running shasum or openssl on the downloaded file results in 7c00f945fa7afb0f264bf253759f3dd02944a0ffef7b5f13317fa835ce841952. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cma at bitemyapp.com Fri Apr 3 20:30:37 2015 From: cma at bitemyapp.com (Christopher Allen) Date: Fri, 3 Apr 2015 15:30:37 -0500 Subject: [Haskell-beginners] Haskell Platform SHA In-Reply-To: References: Message-ID: Seems okay to me if I use sha256. I can't reproduce the hash you got with any of the algorithms shasum offers. [callen at atlantis ~/Downloads]$ sha256sum Haskell\ Platform\ 2014.2.0.0\ 64bit.signed.pkg 62f39246ad95dd2aed6ece5138f6297f945d2b450f215d074820294310e0c48a Haskell Platform 2014.2.0.0 64bit.signed.pkg [callen at atlantis ~/Downloads]$ sha1sum Haskell\ Platform\ 2014.2.0.0\ 64bit.signed.pkg 5741fc1d9253568d3388fbe21c41d746acede9ab Haskell Platform 2014.2.0.0 64bit.signed.pkg [callen at atlantis ~/Downloads]$ sha224sum Haskell\ Platform\ 2014.2.0.0\ 64bit.signed.pkg 6f5254d1ac958001eb93f1e30b4df0f34f372b791abd4bf66fd88c74 Haskell Platform 2014.2.0.0 64bit.signed.pkg [callen at atlantis ~/Downloads]$ sha512sum Haskell\ Platform\ 2014.2.0.0\ 64bit.signed.pkg 7f6a0e90966c3cc7f5000b4d2e92414a4959a22a6fed445547d9b01418bc4e4e3f391e3ec5f7713875753932a1b4880c57c30a3683885bb0209136080e6cb32c Haskell Platform 2014.2.0.0 64bit.signed.pkg [callen at atlantis ~/Downloads]$ sha384sum Haskell\ Platform\ 2014.2.0.0\ 64bit.signed.pkg 63fed8f9b8e8b51421462e0d12e45a8baa50e14640bc4f7ce8cbbfdc20f11cb8e0af5f1aee32c312f891569e95454ceb Haskell Platform 2014.2.0.0 64bit.signed.pkg [callen at atlantis ~/Downloads]$ sha224sum Haskell\ Platform\ 2014.2.0.0\ 64bit.signed.pkg 6f5254d1ac958001eb93f1e30b4df0f34f372b791abd4bf66fd88c74 Haskell Platform 2014.2.0.0 64bit.signed.pkg On Fri, Apr 3, 2015 at 3:13 PM, sojourner wrote: > Downloaded Haskell Platform 2014.2.0.0.0 for Mac OSX from > https://www.haskell.org/platform/mac.html. Twice. The SHA-256 on the web > page is 62f39246ad95dd2aed6ece5138f6297f945d2b450f215d074820294310e0c48a. > But running shasum or openssl on the downloaded file results > in 7c00f945fa7afb0f264bf253759f3dd02944a0ffef7b5f13317fa835ce841952. > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vale.cofershabica at gmail.com Sat Apr 4 02:23:52 2015 From: vale.cofershabica at gmail.com (Vale Cofer-Shabica) Date: Fri, 3 Apr 2015 22:23:52 -0400 Subject: [Haskell-beginners] (.) vs ($) Message-ID: Could someone please explain why the commented line fails spectacularly while the final line succeeds? >import System.IO (getContents) >import System.Environment (getArgs) >fileInput :: IO String >fileInput = getArgs>>=readFirst where > readFirst :: [FilePath] -> IO String > readFirst [] = System.IO.getContents >--readFirst xs = readFile.head xs > readFirst xs = readFile $ head xs I'm particularly confused given the following typings (from ghci): readFile.head :: [FilePath] -> IO String readFile.head [] :: a -> IO String And this is still stranger: :type readFile.head ["foo", "bar"] :28:16: Couldn't match expected type `a0 -> FilePath' with actual type `[Char]' In the expression: "foo" In the first argument of `head', namely `["foo", "bar"]' In the second argument of `(.)', namely `head ["foo", "bar"]' :28:23: Couldn't match expected type `a0 -> FilePath' with actual type `[Char]' In the expression: "bar" In the first argument of `head', namely `["foo", "bar"]' In the second argument of `(.)', namely `head ["foo", "bar"]' Many thanks in advance, vale From math.simplex at gmail.com Sat Apr 4 02:34:37 2015 From: math.simplex at gmail.com (Graham Gill) Date: Fri, 03 Apr 2015 22:34:37 -0400 Subject: [Haskell-beginners] (.) vs ($) In-Reply-To: References: Message-ID: <551F4DBD.8010800@gmail.com> readFile.head xs = readFile . (head xs) For that to work, (head xs) must evaluate to a function with which readFile can compose. But that wouldn't be the type you're wanting. readFile $ head xs = readFile (head xs) Graham On 03/04/2015 10:23 PM, Vale Cofer-Shabica wrote: > Could someone please explain why the commented line fails > spectacularly while the final line succeeds? > >> import System.IO (getContents) >> import System.Environment (getArgs) >> fileInput :: IO String >> fileInput = getArgs>>=readFirst where >> readFirst :: [FilePath] -> IO String >> readFirst [] = System.IO.getContents >> --readFirst xs = readFile.head xs >> readFirst xs = readFile $ head xs > > I'm particularly confused given the following typings (from ghci): > > readFile.head :: [FilePath] -> IO String > readFile.head [] :: a -> IO String > > And this is still stranger: > > :type readFile.head ["foo", "bar"] > > :28:16: > Couldn't match expected type `a0 -> FilePath' > with actual type `[Char]' > In the expression: "foo" > In the first argument of `head', namely `["foo", "bar"]' > In the second argument of `(.)', namely `head ["foo", "bar"]' > > :28:23: > Couldn't match expected type `a0 -> FilePath' > with actual type `[Char]' > In the expression: "bar" > In the first argument of `head', namely `["foo", "bar"]' > In the second argument of `(.)', namely `head ["foo", "bar"]' > > > Many thanks in advance, > vale > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From mwm at mired.org Sat Apr 4 02:40:08 2015 From: mwm at mired.org (Mike Meyer) Date: Fri, 3 Apr 2015 21:40:08 -0500 Subject: [Haskell-beginners] (.) vs ($) In-Reply-To: References: Message-ID: As is often the case with Haskell, your answer is in the types: Prelude> :t ($) ($) :: (a -> b) -> a -> b Prelude> :t (.) (.) :: (b -> c) -> (a -> b) -> a -> c So $ takes a function and applies it to a value. . takes two functions and composes them and applies the result to a value. So readFirst xs = (readFile.head) xs, or just readFirst = readFile . head. But readFirst xs = (readFile $ head) xs will also fail, because readFile doesn't work on objects of type head. On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica < vale.cofershabica at gmail.com> wrote: > Could someone please explain why the commented line fails > spectacularly while the final line succeeds? > > >import System.IO (getContents) > >import System.Environment (getArgs) > > >fileInput :: IO String > >fileInput = getArgs>>=readFirst where > > readFirst :: [FilePath] -> IO String > > readFirst [] = System.IO.getContents > >--readFirst xs = readFile.head xs > > readFirst xs = readFile $ head xs > > > I'm particularly confused given the following typings (from ghci): > > readFile.head :: [FilePath] -> IO String > readFile.head [] :: a -> IO String > > And this is still stranger: > > :type readFile.head ["foo", "bar"] > > :28:16: > Couldn't match expected type `a0 -> FilePath' > with actual type `[Char]' > In the expression: "foo" > In the first argument of `head', namely `["foo", "bar"]' > In the second argument of `(.)', namely `head ["foo", "bar"]' > > :28:23: > Couldn't match expected type `a0 -> FilePath' > with actual type `[Char]' > In the expression: "bar" > In the first argument of `head', namely `["foo", "bar"]' > In the second argument of `(.)', namely `head ["foo", "bar"]' > > > Many thanks in advance, > vale > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica < vale.cofershabica at gmail.com> wrote: > Could someone please explain why the commented line fails > spectacularly while the final line succeeds? > > >import System.IO (getContents) > >import System.Environment (getArgs) > > >fileInput :: IO String > >fileInput = getArgs>>=readFirst where > > readFirst :: [FilePath] -> IO String > > readFirst [] = System.IO.getContents > >--readFirst xs = readFile.head xs > > readFirst xs = readFile $ head xs > > > I'm particularly confused given the following typings (from ghci): > > readFile.head :: [FilePath] -> IO String > readFile.head [] :: a -> IO String > > And this is still stranger: > > :type readFile.head ["foo", "bar"] > > :28:16: > Couldn't match expected type `a0 -> FilePath' > with actual type `[Char]' > In the expression: "foo" > In the first argument of `head', namely `["foo", "bar"]' > In the second argument of `(.)', namely `head ["foo", "bar"]' > > :28:23: > Couldn't match expected type `a0 -> FilePath' > with actual type `[Char]' > In the expression: "bar" > In the first argument of `head', namely `["foo", "bar"]' > In the second argument of `(.)', namely `head ["foo", "bar"]' > > > Many thanks in advance, > vale > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumit.sahrawat.apm13 at iitbhu.ac.in Sat Apr 4 05:46:59 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Sat, 4 Apr 2015 11:16:59 +0530 Subject: [Haskell-beginners] (.) vs ($) In-Reply-To: References: Message-ID: To reiterate what others have said, readFile . head xs == readFile . (head xs) { function application binds strongest } == (.) readFile (head xs) { operators are also functions } The types, (.) :: (b -> c) -> (a -> b) -> (a -> c) readFile :: FilePath -> IO String head xs :: FilePath This cannot work as the types don't match. On the other hand, using ($) instead of (.) will work. Try writing that out and reasoning with the types on pen and paper, as an exercise. If you're interested, there is an excellent post about equational reasoning here: http://www.haskellforall.com/2013/12/equational-reasoning.html Enjoy :) On 4 April 2015 at 08:10, Mike Meyer wrote: > As is often the case with Haskell, your answer is in the types: > > Prelude> :t ($) > ($) :: (a -> b) -> a -> b > Prelude> :t (.) > (.) :: (b -> c) -> (a -> b) -> a -> c > > So $ takes a function and applies it to a value. . takes two functions and > composes them and applies the result to a value. > > So readFirst xs = (readFile.head) xs, or just readFirst = readFile . > head. But readFirst xs = (readFile $ head) xs will also fail, because > readFile doesn't work on objects of type head. > > On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica < > vale.cofershabica at gmail.com> wrote: > >> Could someone please explain why the commented line fails >> spectacularly while the final line succeeds? >> >> >import System.IO (getContents) >> >import System.Environment (getArgs) >> >> >fileInput :: IO String >> >fileInput = getArgs>>=readFirst where >> > readFirst :: [FilePath] -> IO String >> > readFirst [] = System.IO.getContents >> >--readFirst xs = readFile.head xs >> > readFirst xs = readFile $ head xs >> >> >> I'm particularly confused given the following typings (from ghci): >> >> readFile.head :: [FilePath] -> IO String >> readFile.head [] :: a -> IO String >> >> And this is still stranger: >> >> :type readFile.head ["foo", "bar"] >> >> :28:16: >> Couldn't match expected type `a0 -> FilePath' >> with actual type `[Char]' >> In the expression: "foo" >> In the first argument of `head', namely `["foo", "bar"]' >> In the second argument of `(.)', namely `head ["foo", "bar"]' >> >> :28:23: >> Couldn't match expected type `a0 -> FilePath' >> with actual type `[Char]' >> In the expression: "bar" >> In the first argument of `head', namely `["foo", "bar"]' >> In the second argument of `(.)', namely `head ["foo", "bar"]' >> >> >> Many thanks in advance, >> vale >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > > On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica < > vale.cofershabica at gmail.com> wrote: > >> Could someone please explain why the commented line fails >> spectacularly while the final line succeeds? >> >> >import System.IO (getContents) >> >import System.Environment (getArgs) >> >> >fileInput :: IO String >> >fileInput = getArgs>>=readFirst where >> > readFirst :: [FilePath] -> IO String >> > readFirst [] = System.IO.getContents >> >--readFirst xs = readFile.head xs >> > readFirst xs = readFile $ head xs >> >> >> I'm particularly confused given the following typings (from ghci): >> >> readFile.head :: [FilePath] -> IO String >> readFile.head [] :: a -> IO String >> >> And this is still stranger: >> >> :type readFile.head ["foo", "bar"] >> >> :28:16: >> Couldn't match expected type `a0 -> FilePath' >> with actual type `[Char]' >> In the expression: "foo" >> In the first argument of `head', namely `["foo", "bar"]' >> In the second argument of `(.)', namely `head ["foo", "bar"]' >> >> :28:23: >> Couldn't match expected type `a0 -> FilePath' >> with actual type `[Char]' >> In the expression: "bar" >> In the first argument of `head', namely `["foo", "bar"]' >> In the second argument of `(.)', namely `head ["foo", "bar"]' >> >> >> Many thanks in advance, >> vale >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From raabe at froglogic.com Sat Apr 4 08:12:44 2015 From: raabe at froglogic.com (Frerich Raabe) Date: Sat, 04 Apr 2015 10:12:44 +0200 Subject: [Haskell-beginners] Haskell Platform SHA In-Reply-To: References: Message-ID: <7aa6ccd03da4f76a1ed52a6f1a5de9e9@roundcube.froglogic.com> On 2015-04-03 22:13, sojourner wrote: > Downloaded Haskell Platform 2014.2.0.0.0 for Mac OSX from > https://www.haskell.org/platform/mac.html [1]. Twice. The SHA-256 on the web > page is > 62f39246ad95dd2aed6ece5138f6297f945d2b450f215d074820294310e0c48a. But > running shasum or openssl on the downloaded file results in > 7c00f945fa7afb0f264bf253759f3dd02944a0ffef7b5f13317fa835ce841952. I couldn't reproduce this; make sure not to run 'shasum' directly (since that'll default to SHA-1). Invoke it like 'shasum -a 256 '. For me, that gives: $ shasum -a 256 ~/Downloads/Haskell\ Platform\ 2014.2.0.0\ 64bit.signed.pkg 62f39246ad95dd2aed6ece5138f6297f945d2b450f215d074820294310e0c48a /Users/frerich/Downloads/Haskell Platform 2014.2.0.0 64bit.signed.pkg -- Frerich Raabe - raabe at froglogic.com www.froglogic.com - Multi-Platform GUI Testing From vale.cofershabica at gmail.com Sat Apr 4 19:31:52 2015 From: vale.cofershabica at gmail.com (Vale Cofer-Shabica) Date: Sat, 4 Apr 2015 15:31:52 -0400 Subject: [Haskell-beginners] (.) vs ($) In-Reply-To: References: Message-ID: Thank you for all the responses! Sumit's point about function application binding most strongly was the point I was missing. I was lured by the possibility of writing my function in point-free style as Mike indicated: readFirst = readFile.head, but ghc complained about differing numbers of arguments when I included the different case for the empty list. Thanks again, vale On Sat, Apr 4, 2015 at 1:46 AM, Sumit Sahrawat, Maths & Computing, IIT (BHU) wrote: > To reiterate what others have said, > > readFile . head xs > == readFile . (head xs) { function application binds strongest } > == (.) readFile (head xs) { operators are also functions } > > The types, > > (.) :: (b -> c) -> (a -> b) -> (a -> c) > readFile :: FilePath -> IO String > head xs :: FilePath > > This cannot work as the types don't match. On the other hand, using ($) > instead of (.) will work. > Try writing that out and reasoning with the types on pen and paper, as an > exercise. > > If you're interested, there is an excellent post about equational reasoning > here: http://www.haskellforall.com/2013/12/equational-reasoning.html > > Enjoy :) > > On 4 April 2015 at 08:10, Mike Meyer wrote: >> >> As is often the case with Haskell, your answer is in the types: >> >> Prelude> :t ($) >> ($) :: (a -> b) -> a -> b >> Prelude> :t (.) >> (.) :: (b -> c) -> (a -> b) -> a -> c >> >> So $ takes a function and applies it to a value. . takes two functions and >> composes them and applies the result to a value. >> >> So readFirst xs = (readFile.head) xs, or just readFirst = readFile . head. >> But readFirst xs = (readFile $ head) xs will also fail, because readFile >> doesn't work on objects of type head. >> >> On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica >> wrote: >>> >>> Could someone please explain why the commented line fails >>> spectacularly while the final line succeeds? >>> >>> >import System.IO (getContents) >>> >import System.Environment (getArgs) >>> >>> >fileInput :: IO String >>> >fileInput = getArgs>>=readFirst where >>> > readFirst :: [FilePath] -> IO String >>> > readFirst [] = System.IO.getContents >>> >--readFirst xs = readFile.head xs >>> > readFirst xs = readFile $ head xs >>> >>> >>> I'm particularly confused given the following typings (from ghci): >>> >>> readFile.head :: [FilePath] -> IO String >>> readFile.head [] :: a -> IO String >>> >>> And this is still stranger: >>> >>> :type readFile.head ["foo", "bar"] >>> >>> :28:16: >>> Couldn't match expected type `a0 -> FilePath' >>> with actual type `[Char]' >>> In the expression: "foo" >>> In the first argument of `head', namely `["foo", "bar"]' >>> In the second argument of `(.)', namely `head ["foo", "bar"]' >>> >>> :28:23: >>> Couldn't match expected type `a0 -> FilePath' >>> with actual type `[Char]' >>> In the expression: "bar" >>> In the first argument of `head', namely `["foo", "bar"]' >>> In the second argument of `(.)', namely `head ["foo", "bar"]' >>> >>> >>> Many thanks in advance, >>> vale >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> >> >> On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica >> wrote: >>> >>> Could someone please explain why the commented line fails >>> spectacularly while the final line succeeds? >>> >>> >import System.IO (getContents) >>> >import System.Environment (getArgs) >>> >>> >fileInput :: IO String >>> >fileInput = getArgs>>=readFirst where >>> > readFirst :: [FilePath] -> IO String >>> > readFirst [] = System.IO.getContents >>> >--readFirst xs = readFile.head xs >>> > readFirst xs = readFile $ head xs >>> >>> >>> I'm particularly confused given the following typings (from ghci): >>> >>> readFile.head :: [FilePath] -> IO String >>> readFile.head [] :: a -> IO String >>> >>> And this is still stranger: >>> >>> :type readFile.head ["foo", "bar"] >>> >>> :28:16: >>> Couldn't match expected type `a0 -> FilePath' >>> with actual type `[Char]' >>> In the expression: "foo" >>> In the first argument of `head', namely `["foo", "bar"]' >>> In the second argument of `(.)', namely `head ["foo", "bar"]' >>> >>> :28:23: >>> Couldn't match expected type `a0 -> FilePath' >>> with actual type `[Char]' >>> In the expression: "bar" >>> In the first argument of `head', namely `["foo", "bar"]' >>> In the second argument of `(.)', namely `head ["foo", "bar"]' >>> >>> >>> Many thanks in advance, >>> vale >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > > > -- > Regards > > Sumit Sahrawat From ky3 at atamo.com Sun Apr 5 02:51:27 2015 From: ky3 at atamo.com (Kim-Ee Yeoh) Date: Sun, 5 Apr 2015 09:51:27 +0700 Subject: [Haskell-beginners] (.) vs ($) In-Reply-To: References: Message-ID: Hi Vale, Here's something to consider: readFirst [] = System.IO.getContents readFirst (x:_) = readFile x This is considered good style because the pattern-matching is obviously complete. In the original, the use of "head" might be flagged by various lint-like tools even though it's safe in the context, albeit not immediately so. -- Kim-Ee On Sun, Apr 5, 2015 at 2:31 AM, Vale Cofer-Shabica < vale.cofershabica at gmail.com> wrote: > Thank you for all the responses! Sumit's point about function > application binding most strongly was the point I was missing. I was > lured by the possibility of writing my function in point-free style as > Mike indicated: readFirst = readFile.head, but ghc complained about > differing numbers of arguments when I included the different case for > the empty list. > > Thanks again, > vale > > > > On Sat, Apr 4, 2015 at 1:46 AM, Sumit Sahrawat, Maths & Computing, IIT > (BHU) wrote: > > To reiterate what others have said, > > > > readFile . head xs > > == readFile . (head xs) { function application binds strongest } > > == (.) readFile (head xs) { operators are also functions } > > > > The types, > > > > (.) :: (b -> c) -> (a -> b) -> (a -> c) > > readFile :: FilePath -> IO String > > head xs :: FilePath > > > > This cannot work as the types don't match. On the other hand, using ($) > > instead of (.) will work. > > Try writing that out and reasoning with the types on pen and paper, as an > > exercise. > > > > If you're interested, there is an excellent post about equational > reasoning > > here: http://www.haskellforall.com/2013/12/equational-reasoning.html > > > > Enjoy :) > > > > On 4 April 2015 at 08:10, Mike Meyer wrote: > >> > >> As is often the case with Haskell, your answer is in the types: > >> > >> Prelude> :t ($) > >> ($) :: (a -> b) -> a -> b > >> Prelude> :t (.) > >> (.) :: (b -> c) -> (a -> b) -> a -> c > >> > >> So $ takes a function and applies it to a value. . takes two functions > and > >> composes them and applies the result to a value. > >> > >> So readFirst xs = (readFile.head) xs, or just readFirst = readFile . > head. > >> But readFirst xs = (readFile $ head) xs will also fail, because readFile > >> doesn't work on objects of type head. > >> > >> On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica > >> wrote: > >>> > >>> Could someone please explain why the commented line fails > >>> spectacularly while the final line succeeds? > >>> > >>> >import System.IO (getContents) > >>> >import System.Environment (getArgs) > >>> > >>> >fileInput :: IO String > >>> >fileInput = getArgs>>=readFirst where > >>> > readFirst :: [FilePath] -> IO String > >>> > readFirst [] = System.IO.getContents > >>> >--readFirst xs = readFile.head xs > >>> > readFirst xs = readFile $ head xs > >>> > >>> > >>> I'm particularly confused given the following typings (from ghci): > >>> > >>> readFile.head :: [FilePath] -> IO String > >>> readFile.head [] :: a -> IO String > >>> > >>> And this is still stranger: > >>> > >>> :type readFile.head ["foo", "bar"] > >>> > >>> :28:16: > >>> Couldn't match expected type `a0 -> FilePath' > >>> with actual type `[Char]' > >>> In the expression: "foo" > >>> In the first argument of `head', namely `["foo", "bar"]' > >>> In the second argument of `(.)', namely `head ["foo", "bar"]' > >>> > >>> :28:23: > >>> Couldn't match expected type `a0 -> FilePath' > >>> with actual type `[Char]' > >>> In the expression: "bar" > >>> In the first argument of `head', namely `["foo", "bar"]' > >>> In the second argument of `(.)', namely `head ["foo", "bar"]' > >>> > >>> > >>> Many thanks in advance, > >>> vale > >>> _______________________________________________ > >>> Beginners mailing list > >>> Beginners at haskell.org > >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > >> > >> > >> > >> On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica > >> wrote: > >>> > >>> Could someone please explain why the commented line fails > >>> spectacularly while the final line succeeds? > >>> > >>> >import System.IO (getContents) > >>> >import System.Environment (getArgs) > >>> > >>> >fileInput :: IO String > >>> >fileInput = getArgs>>=readFirst where > >>> > readFirst :: [FilePath] -> IO String > >>> > readFirst [] = System.IO.getContents > >>> >--readFirst xs = readFile.head xs > >>> > readFirst xs = readFile $ head xs > >>> > >>> > >>> I'm particularly confused given the following typings (from ghci): > >>> > >>> readFile.head :: [FilePath] -> IO String > >>> readFile.head [] :: a -> IO String > >>> > >>> And this is still stranger: > >>> > >>> :type readFile.head ["foo", "bar"] > >>> > >>> :28:16: > >>> Couldn't match expected type `a0 -> FilePath' > >>> with actual type `[Char]' > >>> In the expression: "foo" > >>> In the first argument of `head', namely `["foo", "bar"]' > >>> In the second argument of `(.)', namely `head ["foo", "bar"]' > >>> > >>> :28:23: > >>> Couldn't match expected type `a0 -> FilePath' > >>> with actual type `[Char]' > >>> In the expression: "bar" > >>> In the first argument of `head', namely `["foo", "bar"]' > >>> In the second argument of `(.)', namely `head ["foo", "bar"]' > >>> > >>> > >>> Many thanks in advance, > >>> vale > >>> _______________________________________________ > >>> Beginners mailing list > >>> Beginners at haskell.org > >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > >> > >> > >> > >> _______________________________________________ > >> Beginners mailing list > >> Beginners at haskell.org > >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > >> > > > > > > > > -- > > Regards > > > > Sumit Sahrawat > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vale.cofershabica at gmail.com Mon Apr 6 15:31:54 2015 From: vale.cofershabica at gmail.com (Vale Cofer-Shabica) Date: Mon, 6 Apr 2015 11:31:54 -0400 Subject: [Haskell-beginners] (.) vs ($) In-Reply-To: References: Message-ID: Thank you Kim-Ee, This is the version I ended up using! -vale On Sat, Apr 4, 2015 at 10:51 PM, Kim-Ee Yeoh wrote: > Hi Vale, > > Here's something to consider: > > readFirst [] = System.IO.getContents > readFirst (x:_) = readFile x > > This is considered good style because the pattern-matching is obviously > complete. > > In the original, the use of "head" might be flagged by various lint-like > tools even though it's safe in the context, albeit not immediately so. > > > -- Kim-Ee > > On Sun, Apr 5, 2015 at 2:31 AM, Vale Cofer-Shabica > wrote: >> >> Thank you for all the responses! Sumit's point about function >> application binding most strongly was the point I was missing. I was >> lured by the possibility of writing my function in point-free style as >> Mike indicated: readFirst = readFile.head, but ghc complained about >> differing numbers of arguments when I included the different case for >> the empty list. >> >> Thanks again, >> vale >> >> >> >> On Sat, Apr 4, 2015 at 1:46 AM, Sumit Sahrawat, Maths & Computing, IIT >> (BHU) wrote: >> > To reiterate what others have said, >> > >> > readFile . head xs >> > == readFile . (head xs) { function application binds strongest } >> > == (.) readFile (head xs) { operators are also functions } >> > >> > The types, >> > >> > (.) :: (b -> c) -> (a -> b) -> (a -> c) >> > readFile :: FilePath -> IO String >> > head xs :: FilePath >> > >> > This cannot work as the types don't match. On the other hand, using ($) >> > instead of (.) will work. >> > Try writing that out and reasoning with the types on pen and paper, as >> > an >> > exercise. >> > >> > If you're interested, there is an excellent post about equational >> > reasoning >> > here: http://www.haskellforall.com/2013/12/equational-reasoning.html >> > >> > Enjoy :) >> > >> > On 4 April 2015 at 08:10, Mike Meyer wrote: >> >> >> >> As is often the case with Haskell, your answer is in the types: >> >> >> >> Prelude> :t ($) >> >> ($) :: (a -> b) -> a -> b >> >> Prelude> :t (.) >> >> (.) :: (b -> c) -> (a -> b) -> a -> c >> >> >> >> So $ takes a function and applies it to a value. . takes two functions >> >> and >> >> composes them and applies the result to a value. >> >> >> >> So readFirst xs = (readFile.head) xs, or just readFirst = readFile . >> >> head. >> >> But readFirst xs = (readFile $ head) xs will also fail, because >> >> readFile >> >> doesn't work on objects of type head. >> >> >> >> On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica >> >> wrote: >> >>> >> >>> Could someone please explain why the commented line fails >> >>> spectacularly while the final line succeeds? >> >>> >> >>> >import System.IO (getContents) >> >>> >import System.Environment (getArgs) >> >>> >> >>> >fileInput :: IO String >> >>> >fileInput = getArgs>>=readFirst where >> >>> > readFirst :: [FilePath] -> IO String >> >>> > readFirst [] = System.IO.getContents >> >>> >--readFirst xs = readFile.head xs >> >>> > readFirst xs = readFile $ head xs >> >>> >> >>> >> >>> I'm particularly confused given the following typings (from ghci): >> >>> >> >>> readFile.head :: [FilePath] -> IO String >> >>> readFile.head [] :: a -> IO String >> >>> >> >>> And this is still stranger: >> >>> >> >>> :type readFile.head ["foo", "bar"] >> >>> >> >>> :28:16: >> >>> Couldn't match expected type `a0 -> FilePath' >> >>> with actual type `[Char]' >> >>> In the expression: "foo" >> >>> In the first argument of `head', namely `["foo", "bar"]' >> >>> In the second argument of `(.)', namely `head ["foo", "bar"]' >> >>> >> >>> :28:23: >> >>> Couldn't match expected type `a0 -> FilePath' >> >>> with actual type `[Char]' >> >>> In the expression: "bar" >> >>> In the first argument of `head', namely `["foo", "bar"]' >> >>> In the second argument of `(.)', namely `head ["foo", "bar"]' >> >>> >> >>> >> >>> Many thanks in advance, >> >>> vale >> >>> _______________________________________________ >> >>> Beginners mailing list >> >>> Beginners at haskell.org >> >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> >> >> >> >> >> >> On Fri, Apr 3, 2015 at 9:23 PM, Vale Cofer-Shabica >> >> wrote: >> >>> >> >>> Could someone please explain why the commented line fails >> >>> spectacularly while the final line succeeds? >> >>> >> >>> >import System.IO (getContents) >> >>> >import System.Environment (getArgs) >> >>> >> >>> >fileInput :: IO String >> >>> >fileInput = getArgs>>=readFirst where >> >>> > readFirst :: [FilePath] -> IO String >> >>> > readFirst [] = System.IO.getContents >> >>> >--readFirst xs = readFile.head xs >> >>> > readFirst xs = readFile $ head xs >> >>> >> >>> >> >>> I'm particularly confused given the following typings (from ghci): >> >>> >> >>> readFile.head :: [FilePath] -> IO String >> >>> readFile.head [] :: a -> IO String >> >>> >> >>> And this is still stranger: >> >>> >> >>> :type readFile.head ["foo", "bar"] >> >>> >> >>> :28:16: >> >>> Couldn't match expected type `a0 -> FilePath' >> >>> with actual type `[Char]' >> >>> In the expression: "foo" >> >>> In the first argument of `head', namely `["foo", "bar"]' >> >>> In the second argument of `(.)', namely `head ["foo", "bar"]' >> >>> >> >>> :28:23: >> >>> Couldn't match expected type `a0 -> FilePath' >> >>> with actual type `[Char]' >> >>> In the expression: "bar" >> >>> In the first argument of `head', namely `["foo", "bar"]' >> >>> In the second argument of `(.)', namely `head ["foo", "bar"]' >> >>> >> >>> >> >>> Many thanks in advance, >> >>> vale >> >>> _______________________________________________ >> >>> Beginners mailing list >> >>> Beginners at haskell.org >> >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> >> >> >> >> >> >> _______________________________________________ >> >> Beginners mailing list >> >> Beginners at haskell.org >> >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> >> > >> > >> > >> > -- >> > Regards >> > >> > Sumit Sahrawat >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > From defigueiredo at ucdavis.edu Thu Apr 9 01:21:05 2015 From: defigueiredo at ucdavis.edu (Dimitri DeFigueiredo) Date: Wed, 08 Apr 2015 18:21:05 -0700 Subject: [Haskell-beginners] Debugging in Haskell Message-ID: <5525D401.1020301@ucdavis.edu> I need to improve my Haskell debugging skills. I know of quickcheck, but that's for testing. It seems that: - Debug.Trace and - dynamic breakpoints in GHCi Are the two easy ways to check the state of your program at a specific point in execution. Is there another simple tool that I should know about? Any tips? Thank you, Dimitri From objitsu at gmail.com Thu Apr 9 09:03:45 2015 From: objitsu at gmail.com (emacstheviking) Date: Thu, 9 Apr 2015 10:03:45 +0100 Subject: [Haskell-beginners] Debugging in Haskell In-Reply-To: <5525D401.1020301@ucdavis.edu> References: <5525D401.1020301@ucdavis.edu> Message-ID: That's interesting. I must confess that I find the need to debug in Haskell greatly reduced because I tend to design stuff in small incremental steps in ghci / emac in a Lisp like way which means that I am reasoning out my code as I write it which usually means there are no logical bugs at least. However I can see the need on occasion to maybe debug into issues relating to threads / STM and behaviours between processes in general. Have you tried using Leksah, the Haskell IDE? On 9 April 2015 at 02:21, Dimitri DeFigueiredo wrote: > I need to improve my Haskell debugging skills. I know of quickcheck, but > that's for testing. It seems that: > > - Debug.Trace and > - dynamic breakpoints in GHCi > > Are the two easy ways to check the state of your program at a specific > point in execution. > Is there another simple tool that I should know about? Any tips? > > Thank you, > > Dimitri > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From defigueiredo at ucdavis.edu Fri Apr 10 00:18:03 2015 From: defigueiredo at ucdavis.edu (Dimitri DeFigueiredo) Date: Thu, 09 Apr 2015 17:18:03 -0700 Subject: [Haskell-beginners] Debugging in Haskell In-Reply-To: References: <5525D401.1020301@ucdavis.edu> Message-ID: <552716BB.3020705@ucdavis.edu> I did try to use Leksah, but did not like the interface. I don't think it helped with debugging, but may be mistaken. I'm now using sublime 3 and hoping that someday I will be able to use Atom. Emacs appears to be the standard, but it is just too ugly for me. Dimitri On 09/04/15 02:03, emacstheviking wrote: > That's interesting. > > I must confess that I find the need to debug in Haskell greatly > reduced because I tend to design stuff in small incremental steps in > ghci / emac in a Lisp like way which means that I am reasoning out my > code as I write it which usually means there are no logical bugs at least. > > However I can see the need on occasion to maybe debug into issues > relating to threads / STM and behaviours between processes in general. > > Have you tried using Leksah, the Haskell IDE? > > > > On 9 April 2015 at 02:21, Dimitri DeFigueiredo > > wrote: > > I need to improve my Haskell debugging skills. I know of > quickcheck, but that's for testing. It seems that: > > - Debug.Trace and > - dynamic breakpoints in GHCi > > Are the two easy ways to check the state of your program at a > specific point in execution. > Is there another simple tool that I should know about? Any tips? > > Thank you, > > Dimitri > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.drautzburg at web.de Fri Apr 10 17:02:13 2015 From: martin.drautzburg at web.de (martin) Date: Fri, 10 Apr 2015 19:02:13 +0200 Subject: [Haskell-beginners] Need help to write join on my Temporals Message-ID: <55280215.7090300@web.de> Hello all, I have these Types type Time = Integer data Change a = Chg { ct :: Time, -- "change time" cv :: a -- "change value" } deriving (Eq,Show) data Temporal a = Temporal { td :: a, -- "temporal default" tc :: [Change a] -- "temporal changes" } deriving (Eq, Show) And I am trying to make Temporal a Monad by implementing join. My first Attempt was awfully verbose. It was also faulty, which was revealed by this QuickQueck (I am happy with my implementation of <*>) prop_tJoin tpr1 tpr2 = let f = (*) y1 = f <$> tpr1 <*> tpr2 y2 = (f <$> tpr1) `ap` tpr2 in y1 == y2 While I understand why my first implementatin was faulty, I fail to come up with anything remotely readable. I don't understand why I am having such difficulties, let alone solve them. I feel I am approaching this from the wrong angle. Any advice would be very much appreciated. From martin.drautzburg at web.de Fri Apr 10 17:25:04 2015 From: martin.drautzburg at web.de (martin) Date: Fri, 10 Apr 2015 19:25:04 +0200 Subject: [Haskell-beginners] Why does QuickCheck insist on this class constraint? In-Reply-To: References: <55193204.90305@web.de> Message-ID: <55280770.9090008@web.de> Am 04/01/2015 um 10:43 PM schrieb Chadda? Fouch?: > Why are you putting those type signatures everywhere ? Won't your code compile without them ? It seems to me that > absent a strange Change type, all those things can be inferred... Are you doing this as an exercise or because you > think it is more readable ? I had put them there, because I thought QuickCheck needs them. But you're right they are not needed and then my question becomes a non-issue. From andres at well-typed.com Fri Apr 10 17:51:23 2015 From: andres at well-typed.com (=?UTF-8?Q?Andres_L=C3=B6h?=) Date: Fri, 10 Apr 2015 19:51:23 +0200 Subject: [Haskell-beginners] Why does QuickCheck insist on this class constraint? In-Reply-To: <55280770.9090008@web.de> References: <55193204.90305@web.de> <55280770.9090008@web.de> Message-ID: Hi. To answer your original question anyway: In Haskell 2010, all type variables that appear in any type annotation are implicitly quantified. They're not "scoped". So e.g. here: instance (Arbitrary a, Eq a) => Arbitrary (Temporal a) where arbitrary = do d <- arbitrary (CList cs) <- arbitrary :: (Arbitrary a, Eq a) => Gen (CList a) -- <=== return (Temporal d cs) if you say just "Gen (CList a)", it's the same as if you'd write "Gen (CList b)", and it means "forall b. Gen (CList b)". But that's not true! The term "arbitrary" cannot have the type "forall b. Gen (CList b)", because the instance for "Gen (CList c)" requires "(Arbitray c, Eq c)". That's why GHC wants you to add the constraint. However, you can make type variables scoped in GHC, by enabling the "ScopedTypeVariables" extension. So if you add the pragma {-# LANGUAGE ScopedTypeVariables #-} as the first line of your module, then the type variables that occur in the instance declaration scope over the body of the instance, and your annotations should mean what you originally expected and work without the extra constraints. But of course, as has already been stated, the type annotations are unnecessary here, because GHC can infer everything anyway. Cheers, Andres -- Andres L?h, Haskell Consultant Well-Typed LLP, http://www.well-typed.com Registered in England & Wales, OC335890 250 Ice Wharf, 17 New Wharf Road, London N1 9RF, England From objitsu at gmail.com Fri Apr 10 19:04:00 2015 From: objitsu at gmail.com (emacstheviking) Date: Fri, 10 Apr 2015 20:04:00 +0100 Subject: [Haskell-beginners] Debugging in Haskell In-Reply-To: <552716BB.3020705@ucdavis.edu> References: <5525D401.1020301@ucdavis.edu> <552716BB.3020705@ucdavis.edu> Message-ID: I've used Emacs for 30 years so I guess I am biased! One of the real plus points is its auto-indenting, it's great for avoiding problems on that front IMHO. "Ugly" is subjective I guess... try vim them, YouTube has some great videos on Vim and Haskell. https://www.youtube.com/results?search_query=haskell+vim The Haskell Live video is good. All the best, Sean. On 10 April 2015 at 01:18, Dimitri DeFigueiredo wrote: > I did try to use Leksah, but did not like the interface. I don't think it > helped with debugging, but may be mistaken. I'm now using sublime 3 and > hoping that someday I will be able to use Atom. Emacs appears to be the > standard, but it is just too ugly for me. > > Dimitri > > > > On 09/04/15 02:03, emacstheviking wrote: > > That's interesting. > > I must confess that I find the need to debug in Haskell greatly reduced > because I tend to design stuff in small incremental steps in ghci / emac in > a Lisp like way which means that I am reasoning out my code as I write it > which usually means there are no logical bugs at least. > > However I can see the need on occasion to maybe debug into issues relating > to threads / STM and behaviours between processes in general. > > Have you tried using Leksah, the Haskell IDE? > > > > On 9 April 2015 at 02:21, Dimitri DeFigueiredo > wrote: > >> I need to improve my Haskell debugging skills. I know of quickcheck, but >> that's for testing. It seems that: >> >> - Debug.Trace and >> - dynamic breakpoints in GHCi >> >> Are the two easy ways to check the state of your program at a specific >> point in execution. >> Is there another simple tool that I should know about? Any tips? >> >> Thank you, >> >> Dimitri >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > > > _______________________________________________ > Beginners mailing listBeginners at haskell.orghttp://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stuart.hungerford at gmail.com Fri Apr 10 22:17:13 2015 From: stuart.hungerford at gmail.com (Stuart Hungerford) Date: Sat, 11 Apr 2015 08:17:13 +1000 Subject: [Haskell-beginners] Managing boilerplate code in QuickCheck properties... Message-ID: Hi, I'm using the wonderful QuickCheck and Tasty libraries to test a bunch of properties (actually axioms for typeclasses): positivity_suite :: TestTree positivity_suite = testGroup "positivity axiom" [ testProperty "Float" (axiom_positivity :: Float -> Bool), testProperty "(Float, Float)" (axiom_positivity :: (Float, Float) -> Bool), -- etc ] symmetry_suite :: TestTree symmetry_suite = testGroup "symmetry axiom" [ testProperty "Float" (axiom_symmetry :: Float -> Float -> Bool), testProperty "(Float, Float)" (axiom_symmetry :: (Float, Float) -> (Float, Float) -> Bool), -- etc ] Over multiple typeclasses, axioms and instance types this leads to a huge amount of repeated, boilerplate code. I asked an earlier question on the Haskell Cafe mailing list about testing polymorphic typeclasses in QuickCheck but I'm realizing the issue is going to crop up beyond testing typeclass axioms and perhaps beyond testing. I can see several workarounds for managing the boilerplate code: 1. Define a set of CPP macros for the property type signatures 2. Do the same sort of thing with Template Haskell but with mapping over a list of desired test types 3. Define a very tedious but succinct set of type aliases allowing most properties to become more cryptic one-liners type Pr_F_F = Float -> Float -> Bool type Pr_F2_F2 = (Float, Float) -> (Float, Float) -> Bool -- etc, then testProperty "(Float, Float)" (axiom_symmetry :: Pr_F2_F2) How do experienced Haskellers deal with this situation? I feel I'm missing something in how I've gone about this. Thanks, Stu From dot_wangyushi at yeah.net Sun Apr 12 06:16:14 2015 From: dot_wangyushi at yeah.net (m00nlight) Date: Sun, 12 Apr 2015 14:16:14 +0800 (CST) Subject: [Haskell-beginners] Debugging in Haskell In-Reply-To: <552716BB.3020705@ucdavis.edu> References: <5525D401.1020301@ucdavis.edu> <552716BB.3020705@ucdavis.edu> Message-ID: <5a2992d.1c6.14cac456ff6.Coremail.dot_wangyushi@yeah.net> Emacs can be configured to look great, see the following quora answer for example. You can just try to get used to it and add your configuration incremently. After a few time, it will be of beautiful appearance. http://www.quora.com/How-can-I-go-from-good-to-great-in-Emacs --m00nlight ?2015?04?10 08?18?, "Dimitri DeFigueiredo"??: I did try to use Leksah, but did not like the interface. I don't think it helped with debugging, but may be mistaken. I'm now using sublime 3 and hoping that someday I will be able to use Atom. Emacs appears to be the standard, but it is just too ugly for me. Dimitri On 09/04/15 02:03, emacstheviking wrote: That's interesting. I must confess that I find the need to debug in Haskell greatly reduced because I tend to design stuff in small incremental steps in ghci / emac in a Lisp like way which means that I am reasoning out my code as I write it which usually means there are no logical bugs at least. However I can see the need on occasion to maybe debug into issues relating to threads / STM and behaviours between processes in general. Have you tried using Leksah, the Haskell IDE? On 9 April 2015 at 02:21, Dimitri DeFigueiredo wrote: I need to improve my Haskell debugging skills. I know of quickcheck, but that's for testing. It seems that: - Debug.Trace and - dynamic breakpoints in GHCi Are the two easy ways to check the state of your program at a specific point in execution. Is there another simple tool that I should know about? Any tips? Thank you, Dimitri _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners _______________________________________________ Beginners mailing listBeginners at haskell.orghttp://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From hjgtuyl at chello.nl Sun Apr 12 09:09:25 2015 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Sun, 12 Apr 2015 11:09:25 +0200 Subject: [Haskell-beginners] Debugging in Haskell In-Reply-To: <5525D401.1020301@ucdavis.edu> References: <5525D401.1020301@ucdavis.edu> Message-ID: On Thu, 09 Apr 2015 03:21:05 +0200, Dimitri DeFigueiredo wrote: > I need to improve my Haskell debugging skills. I know of quickcheck, but > that's for testing. It seems that: > > - Debug.Trace and > - dynamic breakpoints in GHCi > > Are the two easy ways to check the state of your program at a specific > point in execution. > Is there another simple tool that I should know about? Any tips? GHC 7.10 can generate debug information, see the Release notes for version 7.10.1 [0]. Regards, Henk-Jan van Tuyl [0] https://downloads.haskell.org/~ghc/7.10.1/docs/html/users_guide/release-7-10-1.html -- Folding at home What if you could share your unused computer power to help find a cure? In just 5 minutes you can join the world's biggest networked computer and get us closer sooner. Watch the video. http://folding.stanford.edu/ http://Van.Tuyl.eu/ http://members.chello.nl/hjgtuyl/tourdemonad.html Haskell programming -- From martin.drautzburg at web.de Sun Apr 12 09:49:13 2015 From: martin.drautzburg at web.de (martin) Date: Sun, 12 Apr 2015 11:49:13 +0200 Subject: [Haskell-beginners] Need help to write join on my Temporals In-Reply-To: <55280215.7090300@web.de> References: <55280215.7090300@web.de> Message-ID: <552A3F99.3070607@web.de> So I have a solution now, it passes my tests but it is ugly. While I am unnesting I sometimes have to add the default as a new change and sometimes add the last old change with its time advanced. The problem is, I don't really know the semantics of a Temporal Temporal, but I know the semantics of <*> and that <*> must be the same as `ap`. Any comments will be very welcome. -- cBetween :: Time -> Time -> [Change a] -> [Change a] -- cAfter :: Time -> [Change a] -> [Change a] -- cBefore :: Time -> [Change a] -> [Change a] tJoin :: Temporal (Temporal a) -> Temporal a tJoin (Temporal tdef []) = tdef tJoin tp@(Temporal tdef ctps) | null cs' = Temporal (td tdef) (tj ctps) | otherwise = Temporal (td tdef) (cs' ++ tj' ctps) where cs = tc tdef cs' = cBefore (ct $ head ctps) cs tj, tj' :: [Change (Temporal a)] -> [Change a] -- before first change was found tj ((Chg t (Temporal d [])):[]) = [Chg t d] tj ((Chg t (Temporal d cs)):[]) = preDef t d cs (cAfter t cs) tj ((Chg t (Temporal d [])):cts) = (Chg t d) : (tj cts) tj ((Chg t (Temporal d cs)):cts) | null cs' = preDef t d cs (tj cts) | otherwise = preDef t d cs cs' ++ (tj' cts) where cs' = cBetween t (ct $ head cts) cs -- after first change was found tj' ((Chg t (Temporal d cs)):[]) = preC0 t cs (cAfter t cs) tj' ((Chg t (Temporal d cs)):cts) = preC0 t cs cs' ++ (tj' cts) where cs' = cBetween t (ct $ head cts) cs -- prepend first change if required preC0 t cs cs' | null bef = cs' | tx == t = cs' | otherwise = (Chg t vx) : cs' where bef = cBefore' t cs (Chg tx vx) = last bef -- prepend default as new change preDef t d cs cs' | null cs = cs' | t == tx = cs' | otherwise = (Chg t d) : cs' where (Chg tx vx) = head cs Am 04/10/2015 um 07:02 PM schrieb martin: > type Time = Integer > data Change a = Chg { > ct :: Time, -- "change time" > cv :: a -- "change value" > } deriving (Eq,Show) > > data Temporal a = Temporal { > td :: a, -- "temporal default" > tc :: [Change a] -- "temporal changes" > } deriving (Eq, Show) From martin.drautzburg at web.de Sun Apr 12 11:55:45 2015 From: martin.drautzburg at web.de (martin) Date: Sun, 12 Apr 2015 13:55:45 +0200 Subject: [Haskell-beginners] Linebreaks in lhs2tex eval Message-ID: <552A5D41.8040906@web.de> Hello all, it appears lhs2tex's \eval command does not show linebreaks. This is a pity, particularly when the output is formatted with a pretty printer. Is there a way to teach \eval to respect the linebreaks? From sumit.sahrawat.apm13 at iitbhu.ac.in Sun Apr 12 15:39:33 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Sun, 12 Apr 2015 21:09:33 +0530 Subject: [Haskell-beginners] Linebreaks in lhs2tex eval In-Reply-To: <552A5D41.8040906@web.de> References: <552A5D41.8040906@web.de> Message-ID: Try opening an issue here: https://github.com/kosmikus/lhs2tex/issues. On 12 April 2015 at 17:25, martin wrote: > Hello all, > > it appears lhs2tex's \eval command does not show linebreaks. This is a > pity, particularly when the output is formatted > with a pretty printer. > > Is there a way to teach \eval to respect the linebreaks? > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From christian.sperandio at gmail.com Sun Apr 12 16:41:50 2015 From: christian.sperandio at gmail.com (Christian Sperandio) Date: Sun, 12 Apr 2015 18:41:50 +0200 Subject: [Haskell-beginners] Type declaration Message-ID: Hi, I?m currently playing with the mutable array to implement an heap sort sort (from The Art of Computer Programming) and I?m puzzled with an error. When I code: toHeap :: Ord a => [a] -> IO [a] toHeap [] = return [] toHeap [x] = return [x] toHeap xs = do arr <- newListArray (1, length xs) xs :: IO (IOArray Int a) getElems arr I?ve got this error: Could not deduce (a ~ a1) from the context (Ord a) bound by the type signature for toHeap :: Ord a => [a] -> IO [a] at /var/folders/fk/339860r16j759wmsfmjkyr4h0000gn/T/flycheck797T5s/Heapsort.hs:9:11-32 ?a? is a rigid type variable bound by the type signature for toHeap :: Ord a => [a] -> IO [a] at /var/folders/fk/339860r16j759wmsfmjkyr4h0000gn/T/flycheck797T5s/Heapsort.hs:9:11 ?a1? is a rigid type variable bound by an expression type signature: IO (IOArray Int a1) at /var/folders/fk/339860r16j759wmsfmjkyr4h0000gn/T/flycheck797T5s/Heapsort.hs:14:10 Expected type: [a1] Actual type: [a] Relevant bindings include xs :: [a] (bound at /var/folders/fk/339860r16j759wmsfmjkyr4h0000gn/T/flycheck797T5s/Heapsort.hs:12:8) toHeap :: [a] -> IO [a] (bound at /var/folders/fk/339860r16j759wmsfmjkyr4h0000gn/T/flycheck797T5s/Heapsort.hs:10:1) In the second argument of ?newListArray?, namely ?xs? In a stmt of a 'do' block: arr <- newListArray (1, length xs) xs :: IO (IOArray Int a) But with the code below, all work: toHeap :: Ord a => [a] -> IO [a] toHeap [] = return [] toHeap [x] = return [x] toHeap xs = do arr <- buildArray xs getElems arr buildArray :: [a] -> IO (IOArray Int a) buildArray xs = newListArray (1, length xs) xs What do I miss ? Thanks. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From allbery.b at gmail.com Sun Apr 12 16:55:05 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Sun, 12 Apr 2015 12:55:05 -0400 Subject: [Haskell-beginners] Type declaration In-Reply-To: References: Message-ID: On Sun, Apr 12, 2015 at 12:41 PM, Christian Sperandio < christian.sperandio at gmail.com> wrote: > I?m currently playing with the mutable array to implement an heap sort > sort (from The Art of Computer Programming) and I?m puzzled with an error. > > When I code: > > toHeap :: Ord a => [a] -> IO [a] > toHeap [] = return [] > toHeap [x] = return [x] > toHeap xs = do > arr <- newListArray (1, length xs) xs :: IO (IOArray Int a) > getElems arr > Note that the "a" in the signature "IO (IOArray Int a)" is *not* the same as the one in the signature of toHeap; the scope of that type variable is the signature itself, not the following equation(s). You have in effect done the opposite of what you intended --- instead of asserting it is the same, you asserted that it is a *different* one, by handing the compiler an unexpected `a` which must be assumed to represent a distinct type. If you need to extend the scope of a type variable like this, you need the ScopedTypeVariables extension, and to declare the type variable as having extended scope with an explicit `forall`: {-# LANGUAGE ScopedTypeVariables #-} toHeap :: forall a. Ord a => [a] -> IO [a] toHeap [] = return [] toHeap [x] = return [x] toHeap xs = do arr <- newListArray (1, length xs) xs :: IO (IOArray Int a) getElems arr -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From dot_wangyushi at yeah.net Mon Apr 13 06:56:47 2015 From: dot_wangyushi at yeah.net (m00nlight) Date: Mon, 13 Apr 2015 14:56:47 +0800 (CST) Subject: [Haskell-beginners] Operator orders affect parse result Message-ID: <5b3df2b7.189.14cb190ecaa.Coremail.dot_wangyushi@yeah.net> Dear Haskellers, I have tried the "while language parser" tutorial on haskellwiki, but I encounter an problem I can not understand here, The following is the code: http://pastebin.com/saC9vwCn The problem is, with the code, the parse result of "fact := a / b * c" is *Main> parseString "fact := a / b * c" Assign "fact" (ABinary Multiply (ABinary Divide (Var "a") (Var "b")) (Var "c")) *Main> But if I swap the order of "/" and "*" operators in aOperators(make "*" appear before "/" operator), then the result is *Main> parseString "fact := a / b * c" Assign "fact" (ABinary Divide (Var "a") (ABinary Multiply (Var "b") (Var "c"))) *Main> So it seems that the order of the operator will affect the parse result. What's the problem with my code? How can I make my program to produce consistent parse result. Best Regards, --m00nlight -------------- next part -------------- An HTML attachment was scrubbed... URL: From fa-ml at ariis.it Mon Apr 13 07:21:19 2015 From: fa-ml at ariis.it (Francesco Ariis) Date: Mon, 13 Apr 2015 09:21:19 +0200 Subject: [Haskell-beginners] Operator orders affect parse result In-Reply-To: <5b3df2b7.189.14cb190ecaa.Coremail.dot_wangyushi@yeah.net> References: <5b3df2b7.189.14cb190ecaa.Coremail.dot_wangyushi@yeah.net> Message-ID: <20150413072119.GA4854@x60s.casa> On Mon, Apr 13, 2015 at 02:56:47PM +0800, m00nlight wrote: > Dear Haskellers, > > I have tried the "while language parser" tutorial on haskellwiki, but I > encounter an problem I can not understand here, > The following is the code: > > http://pastebin.com/saC9vwCn > > > So it seems that the order of the operator will affect the parse result. > What's the problem with my code? How can I make my program to produce > consistent parse result. Checking the documentation for OperatorTable [1] (the first argument to buildExpressionParser), it seems it is working as expected: An OperatorTable s u m a is a list of Operator s u m a lists. The list is ordered in descending precedence. All operators in one list have the same precedence (but may have a different associativity). I think you can take advantage of the fact that OperatorTable is /a list of lists/, hence aOperators = [ [Prefix (reservedOp "-" >> return (Neg ))] , [Infix (reservedOp "/" >> return (ABinary Divide )) AssocLeft, Infix (reservedOp "*" >> return (ABinary Multiply )) AssocLeft] , [Infix (reservedOp "+" >> return (ABinary Add )) AssocLeft] , [Infix (reservedOp "-" >> return (ABinary Subtract )) AssocLeft] ] should do the trick (try swapping the elements in the second list. Will this do? [1] http://hackage.haskell.org/package/parsec-3.0.0/docs/Text-Parsec-Expr.html#t:OperatorTable From dot_wangyushi at yeah.net Mon Apr 13 07:49:43 2015 From: dot_wangyushi at yeah.net (m00nlight) Date: Mon, 13 Apr 2015 15:49:43 +0800 (CST) Subject: [Haskell-beginners] Operator orders affect parse result In-Reply-To: <20150413072119.GA4854@x60s.casa> References: <5b3df2b7.189.14cb190ecaa.Coremail.dot_wangyushi@yeah.net> <20150413072119.GA4854@x60s.casa> Message-ID: <72e984f1.1e6.14cb1c16359.Coremail.dot_wangyushi@yeah.net> Hi Francesco, Thanks for your reply. But after I change the aOperators like the following, it still produce non-correct parse result. aOperators = [ [Prefix (reservedOp "-" >> return (Neg ))] , [ Infix (reservedOp "*" >> return (ABinary Divide )) AssocLeft, Infix (reservedOp "/" >> return (ABinary Multiply )) AssocLeft] , [Infix (reservedOp "+" >> return (ABinary Add )) AssocLeft, Infix (reservedOp "-" >> return (ABinary Subtract )) AssocLeft] ] parse result: *Main> parseString "res := a / b * c" Assign "res" (ABinary Divide (ABinary Multiply (Var "a") (Var "b")) (Var "c")) *Main> --m00nlight ?2015?04?13 15?21?, "Francesco Ariis"??: On Mon, Apr 13, 2015 at 02:56:47PM +0800, m00nlight wrote: > Dear Haskellers, > > I have tried the "while language parser" tutorial on haskellwiki, but I > encounter an problem I can not understand here, > The following is the code: > > http://pastebin.com/saC9vwCn > > > So it seems that the order of the operator will affect the parse result. > What's the problem with my code? How can I make my program to produce > consistent parse result. Checking the documentation for OperatorTable [1] (the first argument to buildExpressionParser), it seems it is working as expected: An OperatorTable s u m a is a list of Operator s u m a lists. The list is ordered in descending precedence. All operators in one list have the same precedence (but may have a different associativity). I think you can take advantage of the fact that OperatorTable is /a list of lists/, hence aOperators = [ [Prefix (reservedOp "-" >> return (Neg ))] , [Infix (reservedOp "/" >> return (ABinary Divide )) AssocLeft, Infix (reservedOp "*" >> return (ABinary Multiply )) AssocLeft] , [Infix (reservedOp "+" >> return (ABinary Add )) AssocLeft] , [Infix (reservedOp "-" >> return (ABinary Subtract )) AssocLeft] ] should do the trick (try swapping the elements in the second list. Will this do? [1] http://hackage.haskell.org/package/parsec-3.0.0/docs/Text-Parsec-Expr.html#t:OperatorTable _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From fa-ml at ariis.it Mon Apr 13 08:12:20 2015 From: fa-ml at ariis.it (Francesco Ariis) Date: Mon, 13 Apr 2015 10:12:20 +0200 Subject: [Haskell-beginners] Operator orders affect parse result In-Reply-To: <72e984f1.1e6.14cb1c16359.Coremail.dot_wangyushi@yeah.net> References: <5b3df2b7.189.14cb190ecaa.Coremail.dot_wangyushi@yeah.net> <20150413072119.GA4854@x60s.casa> <72e984f1.1e6.14cb1c16359.Coremail.dot_wangyushi@yeah.net> Message-ID: <20150413081220.GA7614@x60s.casa> On Mon, Apr 13, 2015 at 03:49:43PM +0800, m00nlight wrote: > Hi Francesco, > > Thanks for your reply. But after I change the aOperators like the following, it still produce non-correct parse result. > > aOperators = [ [Prefix (reservedOp "-" >> return (Neg ))] > , [ Infix (reservedOp "*" >> return (ABinary Divide )) AssocLeft, > Infix (reservedOp "/" >> return (ABinary Multiply )) AssocLeft] > , [Infix (reservedOp "+" >> return (ABinary Add )) AssocLeft, > Infix (reservedOp "-" >> return (ABinary Subtract )) AssocLeft] > ] Check those lines: , [ Infix (reservedOp "*" >> return (ABinary Divide )) AssocLeft, Infix (reservedOp "/" >> return (ABinary Multiply )) AssocLeft] Divide should go on the same line of "/", not "*"! Similar fix for Multiply! From timmelzer at gmail.com Mon Apr 13 08:29:12 2015 From: timmelzer at gmail.com (Norbert Melzer) Date: Mon, 13 Apr 2015 10:29:12 +0200 Subject: [Haskell-beginners] Operator orders affect parse result In-Reply-To: <72e984f1.1e6.14cb1c16359.Coremail.dot_wangyushi@yeah.net> References: <5b3df2b7.189.14cb190ecaa.Coremail.dot_wangyushi@yeah.net> <20150413072119.GA4854@x60s.casa> <72e984f1.1e6.14cb1c16359.Coremail.dot_wangyushi@yeah.net> Message-ID: According to the given code, that result seems to be fine... Apply / to a and be and that result is applied to * together with c. Only odd thing is that you named the / Multiply and the * Divide. Am 13.04.2015 09:50 schrieb "m00nlight" : > Hi Francesco, > > Thanks for your reply. But after I change the aOperators like the > following, it still produce non-correct parse result. > > aOperators = [ [Prefix (reservedOp "-" >> return (Neg ))] > , [ Infix (reservedOp "*" >> return (ABinary Divide )) > AssocLeft, > Infix (reservedOp "/" >> return (ABinary Multiply )) > AssocLeft] > , [Infix (reservedOp "+" >> return (ABinary Add )) AssocLeft, > Infix (reservedOp "-" >> return (ABinary Subtract )) > AssocLeft] > ] > > > parse result: > > *Main> parseString "res := a / b * c" > Assign "res" (ABinary Divide (ABinary Multiply (Var "a") (Var "b")) (Var > "c")) > *Main> > > > > --m00nlight > > ?2015?04?13 15?21?, "Francesco Ariis"??: > > > On Mon, Apr 13, 2015 at 02:56:47PM +0800, m00nlight wrote: > > Dear Haskellers, > > > > I have tried the "while language parser" tutorial on haskellwiki, but I > > encounter an problem I can not understand here, > > The following is the code: > > > > http://pastebin.com/saC9vwCn > > > > > > So it seems that the order of the operator will affect the parse result. > > What's the problem with my code? How can I make my program to produce > > consistent parse result. > > Checking the documentation for OperatorTable [1] (the first argument to > buildExpressionParser), it seems it is working as expected: > > An OperatorTable s u m a is a list of Operator s u m a lists. The list > is ordered in descending precedence. All operators in one list have > the same precedence (but may have a different associativity). > > I think you can take advantage of the fact that OperatorTable is /a list > of lists/, hence > > aOperators = [ [Prefix (reservedOp "-" >> return (Neg ))] > , [Infix (reservedOp "/" >> return (ABinary Divide )) > AssocLeft, > Infix (reservedOp "*" >> return (ABinary Multiply )) > AssocLeft] > , [Infix (reservedOp "+" >> return (ABinary Add )) > AssocLeft] > , [Infix (reservedOp "-" >> return (ABinary Subtract )) > AssocLeft] > ] > > should do the trick (try swapping the elements in the second list. > Will this do? > > > [1] > http://hackage.haskell.org/package/parsec-3.0.0/docs/Text-Parsec-Expr.html#t:OperatorTable > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > <#14cb1c225ea1e3ea_> > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dot_wangyushi at yeah.net Mon Apr 13 08:40:42 2015 From: dot_wangyushi at yeah.net (m00nlight) Date: Mon, 13 Apr 2015 16:40:42 +0800 (CST) Subject: [Haskell-beginners] Operator orders affect parse result In-Reply-To: References: <5b3df2b7.189.14cb190ecaa.Coremail.dot_wangyushi@yeah.net> <20150413072119.GA4854@x60s.casa> <72e984f1.1e6.14cb1c16359.Coremail.dot_wangyushi@yeah.net> Message-ID: <7613ed0e.253.14cb1f01032.Coremail.dot_wangyushi@yeah.net> Hi Norbert, Francesco, Thanks. Just an stupid mistake when I change the code. It is actually correct. Thanks for all your help. --m00nlight ?2015?04?13 16?29?, "Norbert Melzer"??: According to the given code, that result seems to be fine... Apply / to a and be and that result is applied to * together with c. Only odd thing is that you named the / Multiply and the * Divide. Am 13.04.2015 09:50 schrieb "m00nlight" : Hi Francesco, Thanks for your reply. But after I change the aOperators like the following, it still produce non-correct parse result. aOperators = [ [Prefix (reservedOp "-" >> return (Neg ))] , [ Infix (reservedOp "*" >> return (ABinary Divide )) AssocLeft, Infix (reservedOp "/" >> return (ABinary Multiply )) AssocLeft] , [Infix (reservedOp "+" >> return (ABinary Add )) AssocLeft, Infix (reservedOp "-" >> return (ABinary Subtract )) AssocLeft] ] parse result: *Main> parseString "res := a / b * c" Assign "res" (ABinary Divide (ABinary Multiply (Var "a") (Var "b")) (Var "c")) *Main> --m00nlight ?2015?04?13 15?21?, "Francesco Ariis"??: On Mon, Apr 13, 2015 at 02:56:47PM +0800, m00nlight wrote: > Dear Haskellers, > > I have tried the "while language parser" tutorial on haskellwiki, but I > encounter an problem I can not understand here, > The following is the code: > > http://pastebin.com/saC9vwCn > > > So it seems that the order of the operator will affect the parse result. > What's the problem with my code? How can I make my program to produce > consistent parse result. Checking the documentation for OperatorTable [1] (the first argument to buildExpressionParser), it seems it is working as expected: An OperatorTable s u m a is a list of Operator s u m a lists. The list is ordered in descending precedence. All operators in one list have the same precedence (but may have a different associativity). I think you can take advantage of the fact that OperatorTable is /a list of lists/, hence aOperators = [ [Prefix (reservedOp "-" >> return (Neg ))] , [Infix (reservedOp "/" >> return (ABinary Divide )) AssocLeft, Infix (reservedOp "*" >> return (ABinary Multiply )) AssocLeft] , [Infix (reservedOp "+" >> return (ABinary Add )) AssocLeft] , [Infix (reservedOp "-" >> return (ABinary Subtract )) AssocLeft] ] should do the trick (try swapping the elements in the second list. Will this do? [1] http://hackage.haskell.org/package/parsec-3.0.0/docs/Text-Parsec-Expr.html#t:OperatorTable _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Tue Apr 14 16:47:33 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Tue, 14 Apr 2015 17:47:33 +0100 Subject: [Haskell-beginners] Left vs Right Message-ID: Hi, Can someone please explain the difference in outputs of the following two expressions - -------------- ghci> fmap (replicate 3) (Right "blah") Right ["blah","blah","blah"] ghci> fmap (replicate 3) (Left "foo") Left "foo" --------------- Why does 'Right' return a list of Strings whereas 'Left' returns just a String. Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From bob at redivi.com Tue Apr 14 16:56:48 2015 From: bob at redivi.com (Bob Ippolito) Date: Tue, 14 Apr 2015 09:56:48 -0700 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: The Functor instance is defined for `Either a`, so Left is fixed. fmap only maps over Right. You'll find the same behavior for `(,) a`, e.g. `fmap (*2) (1,2) == (1,4)`. On Tue, Apr 14, 2015 at 9:47 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > Hi, > > Can someone please explain the difference in outputs of the following two > expressions - > > -------------- > > ghci> fmap (replicate 3) (Right "blah") > Right ["blah","blah","blah"] > > ghci> fmap (replicate 3) (Left "foo") > Left "foo" > > --------------- > > Why does 'Right' return a list of Strings whereas 'Left' returns just a > String. > > Thanks, > Shishir > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwm at mired.org Tue Apr 14 16:57:20 2015 From: mwm at mired.org (Mike Meyer) Date: Tue, 14 Apr 2015 11:57:20 -0500 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: On Tue, Apr 14, 2015 at 11:47 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > Hi, > > Can someone please explain the difference in outputs of the following two > expressions - > > -------------- > > ghci> fmap (replicate 3) (Right "blah") > Right ["blah","blah","blah"] > > ghci> fmap (replicate 3) (Left "foo") > Left "foo" > > --------------- > > Why does 'Right' return a list of Strings whereas 'Left' returns just a > String. > Because that's the way Either was made an instance of fmap. It's defined so that fmap _ (Left x) = Left x, but fmap f (Right y) = Right (f y). The docs say: The 'Either' type is sometimes used to represent a value which is either correct or an error; by convention, the 'Left' constructor is used to hold an error value and the 'Right' constructor is used to hold a correct value (mnemonic: \"right\" also means \"correct\"). -------------- next part -------------- An HTML attachment was scrubbed... URL: From chas at chas.io Tue Apr 14 16:58:16 2015 From: chas at chas.io (Chas Leichner) Date: Tue, 14 Apr 2015 09:58:16 -0700 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: This is meant to model errors. You want your computation to continue if everything is going all-Right, but if there is an error, you want it to stop there are report the error. This error is represented by Left constructor. On Tue, Apr 14, 2015 at 9:56 AM, Bob Ippolito wrote: > The Functor instance is defined for `Either a`, so Left is fixed. fmap > only maps over Right. You'll find the same behavior for `(,) a`, e.g. `fmap > (*2) (1,2) == (1,4)`. > > On Tue, Apr 14, 2015 at 9:47 AM, Shishir Srivastava < > shishir.srivastava at gmail.com> wrote: > >> Hi, >> >> Can someone please explain the difference in outputs of the following two >> expressions - >> >> -------------- >> >> ghci> fmap (replicate 3) (Right "blah") >> Right ["blah","blah","blah"] >> >> ghci> fmap (replicate 3) (Left "foo") >> Left "foo" >> >> --------------- >> >> Why does 'Right' return a list of Strings whereas 'Left' returns just a >> String. >> >> Thanks, >> Shishir >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ahammel87 at gmail.com Tue Apr 14 17:29:07 2015 From: ahammel87 at gmail.com (Alex Hammel) Date: Tue, 14 Apr 2015 10:29:07 -0700 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: If you really do want to apply a function over data in a Left, there's always `Control.Arrow.left`, which is the complement of `fmap` in this case: ? left (replicate 3) (Left "blah") Left ["blah","blah","blah"] ? left (replicate 3) (Right "blah") Right "blah" Or you can use Either's Bifunctor instance: ? import qualified Data.Bifunctor as Bi ? Bi.first reverse (Left "foo") Left "oof" ? Bi.first reverse (Right "bar") Right "bar" ? Bi.second (intersperse '!') (Left "papaya") Left "papaya" ? Bi.second (intersperse '!') (Right "banana") Right "b!a!n!a!n!a" ? Bi.bimap sort reverse (Left "hello") Left "ehllo" ? Bi.bimap sort reverse (Right "goodbye") Right "eybdoog" On Tue, Apr 14, 2015 at 9:58 AM, Chas Leichner wrote: > This is meant to model errors. You want your computation to continue if > everything is going all-Right, but if there is an error, you want it to > stop there are report the error. This error is represented by Left > constructor. > > On Tue, Apr 14, 2015 at 9:56 AM, Bob Ippolito wrote: > >> The Functor instance is defined for `Either a`, so Left is fixed. fmap >> only maps over Right. You'll find the same behavior for `(,) a`, e.g. `fmap >> (*2) (1,2) == (1,4)`. >> >> On Tue, Apr 14, 2015 at 9:47 AM, Shishir Srivastava < >> shishir.srivastava at gmail.com> wrote: >> >>> Hi, >>> >>> Can someone please explain the difference in outputs of the following >>> two expressions - >>> >>> -------------- >>> >>> ghci> fmap (replicate 3) (Right "blah") >>> Right ["blah","blah","blah"] >>> >>> ghci> fmap (replicate 3) (Left "foo") >>> Left "foo" >>> >>> --------------- >>> >>> Why does 'Right' return a list of Strings whereas 'Left' returns just a >>> String. >>> >>> Thanks, >>> Shishir >>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >>> >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Wed Apr 15 12:47:49 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Wed, 15 Apr 2015 13:47:49 +0100 Subject: [Haskell-beginners] Using Show Message-ID: hi, I am trying to naively print an applicative functor using 'show' like this - show (pure (+) <*> [1, 2, 3]) I know there is something fundamentally wrong with that expression but not sure what. Can anyone please point it out. Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From k-bx at k-bx.com Wed Apr 15 12:50:01 2015 From: k-bx at k-bx.com (Kostiantyn Rybnikov) Date: Wed, 15 Apr 2015 15:50:01 +0300 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: Adding to others, For fmapping left value I suggest using fmapLeft from errors package, for fmapping both you can use either (Left . replicate 3) (Right . replicate 3) 14 ????. 2015 19:48 "Shishir Srivastava" ????: > Hi, > > Can someone please explain the difference in outputs of the following two > expressions - > > -------------- > > ghci> fmap (replicate 3) (Right "blah") > Right ["blah","blah","blah"] > > ghci> fmap (replicate 3) (Left "foo") > Left "foo" > > --------------- > > Why does 'Right' return a list of Strings whereas 'Left' returns just a > String. > > Thanks, > Shishir > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mukeshtiwari.iiitm at gmail.com Wed Apr 15 13:13:19 2015 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Wed, 15 Apr 2015 18:43:19 +0530 Subject: [Haskell-beginners] Using Show In-Reply-To: References: Message-ID: I modified your code little bit and I got this error. ?> :t (pure (+) <*> ([1, 2, 3] :: [Int])) (pure (+) <*> ([1, 2, 3] :: [Int])) :: [Int -> Int] ?> show (pure (+) <*> ([1, 2, 3] :: [Int])) :13:1: No instance for (Show (Int -> Int)) arising from a use of ?show? In the expression: show (pure (+) <*> ([1, 2, 3] :: [Int])) In an equation for ?it?: it = show (pure (+) <*> ([1, 2, 3] :: [Int])) You have list of functions ( [Int -> Int] ) and functions are not instance of Show class so error is pointing towards this fact. ?> :i Show class Show a where showsPrec :: Int -> a -> ShowS show :: a -> String showList :: [a] -> ShowS -- Defined in ?GHC.Show? instance Show a => Show [a] -- Defined in ?GHC.Show? instance Show Ordering -- Defined in ?GHC.Show? instance Show a => Show (Maybe a) -- Defined in ?GHC.Show? instance Show Integer -- Defined in ?GHC.Show? instance Show Int -- Defined in ?GHC.Show? instance Show Char -- Defined in ?GHC.Show? instance Show Bool -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m, Show n, Show o) => Show (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m, Show n) => Show (a, b, c, d, e, f, g, h, i, j, k, l, m, n) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m) => Show (a, b, c, d, e, f, g, h, i, j, k, l, m) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l) => Show (a, b, c, d, e, f, g, h, i, j, k, l) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k) => Show (a, b, c, d, e, f, g, h, i, j, k) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j) => Show (a, b, c, d, e, f, g, h, i, j) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i) => Show (a, b, c, d, e, f, g, h, i) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h) => Show (a, b, c, d, e, f, g, h) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g) => Show (a, b, c, d, e, f, g) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e, Show f) => Show (a, b, c, d, e, f) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c, Show d) => Show (a, b, c, d) -- Defined in ?GHC.Show? instance (Show a, Show b, Show c) => Show (a, b, c) -- Defined in ?GHC.Show? instance (Show a, Show b) => Show (a, b) -- Defined in ?GHC.Show? instance Show () -- Defined in ?GHC.Show? instance (Show a, Show b) => Show (Either a b) -- Defined in ?Data.Either? instance Show a => Show (ZipList a) -- Defined in ?Control.Applicative? instance Show Float -- Defined in ?GHC.Float? instance Show Double -- Defined in ?GHC.Float? See the [1] [2]. [1] https://wiki.haskell.org/Show_instance_for_functions [2] http://stackoverflow.com/questions/15823732/why-is-there-no-show-instance-for-functions On Wed, Apr 15, 2015 at 6:17 PM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > hi, > > I am trying to naively print an applicative functor using 'show' like this > - > > show (pure (+) <*> [1, 2, 3]) > > I know there is something fundamentally wrong with that expression but not > sure what. > > Can anyone please point it out. > > Thanks, > Shishir > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Wed Apr 15 16:21:20 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Wed, 15 Apr 2015 17:21:20 +0100 Subject: [Haskell-beginners] Parse error Message-ID: Hi, I am trying to run the following from the GHCi command prompt which results in parse error. -------------- Prelude> :{ Prelude| foo :: Maybe String Prelude| foo = do Prelude| x <- Just 3 Prelude| y <- Just "!" Prelude| Just (show x ++ y) Prelude| :} :145:5: parse error on input `=' --------------- Any help would be appreciated. Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From allbery.b at gmail.com Wed Apr 15 16:23:28 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Wed, 15 Apr 2015 12:23:28 -0400 Subject: [Haskell-beginners] Parse error In-Reply-To: References: Message-ID: On Wed, Apr 15, 2015 at 12:21 PM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > I am trying to run the following from the GHCi command prompt which > results in parse error. > ghci is not ghc, and requires `let` > > -------------- > Prelude> :{ > Prelude| foo :: Maybe String > Prelude| foo = do > Prelude| x <- Just 3 > Prelude| y <- Just "!" > Prelude| Just (show x ++ y) > Prelude| :} > > :145:5: parse error on input `=' > --------------- > > Any help would be appreciated. > > Thanks, > Shishir > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From objitsu at gmail.com Wed Apr 15 16:24:23 2015 From: objitsu at gmail.com (emacstheviking) Date: Wed, 15 Apr 2015 17:24:23 +0100 Subject: [Haskell-beginners] Parse error In-Reply-To: References: Message-ID: Either(!) its TAB characters upsetting things or not possible form the command line. Maybe(!!) try saving to a file then using the load command to do it instead. On 15 April 2015 at 17:21, Shishir Srivastava wrote: > Hi, > > I am trying to run the following from the GHCi command prompt which > results in parse error. > > -------------- > Prelude> :{ > Prelude| foo :: Maybe String > Prelude| foo = do > Prelude| x <- Just 3 > Prelude| y <- Just "!" > Prelude| Just (show x ++ y) > Prelude| :} > > :145:5: parse error on input `=' > --------------- > > Any help would be appreciated. > > Thanks, > Shishir > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From allbery.b at gmail.com Wed Apr 15 16:26:14 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Wed, 15 Apr 2015 12:26:14 -0400 Subject: [Haskell-beginners] Parse error In-Reply-To: References: Message-ID: On Wed, Apr 15, 2015 at 12:21 PM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > I am trying to run the following from the GHCi command prompt which > results in parse error. > Urgh, sorry. ghci is not ghc, and requires `let` even in the multi-line mode. :{ let foo :: Maybe String foo = do x <- Just 3 y <- Just "!" Just (show x ++ y) :} In general, you are better off using files for definitions, and treat the prompt as a debugger or desk calculator. Multi-line mode doesn't really change this. -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From objitsu at gmail.com Wed Apr 15 16:26:05 2015 From: objitsu at gmail.com (emacstheviking) Date: Wed, 15 Apr 2015 17:26:05 +0100 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: I just love the way Haskell can blow something really simple into something truly mind blowingly obtuse looking at times! It's no wonder Haskell won't be "mainstream" for a while yet, but that's fine, it means the rest of us can charge better rates for now. :) On 15 April 2015 at 13:50, Kostiantyn Rybnikov wrote: > Adding to others, > > For fmapping left value I suggest using fmapLeft from errors package, for > fmapping both you can use > > either (Left . replicate 3) (Right . replicate 3) > 14 ????. 2015 19:48 "Shishir Srivastava" > ????: > >> Hi, >> >> Can someone please explain the difference in outputs of the following two >> expressions - >> >> -------------- >> >> ghci> fmap (replicate 3) (Right "blah") >> Right ["blah","blah","blah"] >> >> ghci> fmap (replicate 3) (Left "foo") >> Left "foo" >> >> --------------- >> >> Why does 'Right' return a list of Strings whereas 'Left' returns just a >> String. >> >> Thanks, >> Shishir >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From k-bx at k-bx.com Wed Apr 15 16:50:29 2015 From: k-bx at k-bx.com (Kostiantyn Rybnikov) Date: Wed, 15 Apr 2015 19:50:29 +0300 Subject: [Haskell-beginners] Using Show In-Reply-To: References: Message-ID: + is a function of two arguments, and applying via (*) against a list would apply each item as first argument of plus Doing pure (+) <*> [1,2,3] <*> [4,5,6] would work. What are you trying to achieve? 15 ????. 2015 15:48 "Shishir Srivastava" ????: > hi, > > I am trying to naively print an applicative functor using 'show' like this > - > > show (pure (+) <*> [1, 2, 3]) > > I know there is something fundamentally wrong with that expression but not > sure what. > > Can anyone please point it out. > > Thanks, > Shishir > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From k-bx at k-bx.com Wed Apr 15 17:13:54 2015 From: k-bx at k-bx.com (Kostiantyn Rybnikov) Date: Wed, 15 Apr 2015 20:13:54 +0300 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: You can still omit monads and keep pair of values in tuple and work with them easily, but I understand the point you are making. But I should note that migration from PHP to Python also takes first impression of complication of many things, where instead of having "just index.php" with everything inlined you would have some wsgi protocols, wsgi servers etc, but later you understand that this was "the right thing". Same with Haskell, it does pay off a lot in future :) 15 ????. 2015 19:27 "emacstheviking" ????: > I just love the way Haskell can blow something really simple into > something truly mind blowingly obtuse looking at times! > It's no wonder Haskell won't be "mainstream" for a while yet, but that's > fine, it means the rest of us can charge better rates for now. > :) > > > On 15 April 2015 at 13:50, Kostiantyn Rybnikov wrote: > >> Adding to others, >> >> For fmapping left value I suggest using fmapLeft from errors package, for >> fmapping both you can use >> >> either (Left . replicate 3) (Right . replicate 3) >> 14 ????. 2015 19:48 "Shishir Srivastava" >> ????: >> >>> Hi, >>> >>> Can someone please explain the difference in outputs of the following >>> two expressions - >>> >>> -------------- >>> >>> ghci> fmap (replicate 3) (Right "blah") >>> Right ["blah","blah","blah"] >>> >>> ghci> fmap (replicate 3) (Left "foo") >>> Left "foo" >>> >>> --------------- >>> >>> Why does 'Right' return a list of Strings whereas 'Left' returns just a >>> String. >>> >>> Thanks, >>> Shishir >>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >>> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From edwards.benj at gmail.com Wed Apr 15 18:13:18 2015 From: edwards.benj at gmail.com (Benjamin Edwards) Date: Wed, 15 Apr 2015 18:13:18 +0000 Subject: [Haskell-beginners] Are Arrows good for simulation purposes In-Reply-To: <551A31C4.3030002@web.de> References: <551A31C4.3030002@web.de> Message-ID: It might be worth your while to look at netwire or auto, which both use arrows to model networks. Ben On Tue, 31 Mar 2015 at 06:35 martin wrote: > Hello all, > > little do I know about arrows, but the "stream processor" metaphor > suggests, that they can be used to simulate a network > of things, services or data. Is this correct? > > I came across the following thought: When I simulate a billard game with a > DES, I would compute collisions of balls with > each other and with the banks, creatign a set of events, of which only the > earliest will be considered to compute the > next state. This is pure DES and does not seem to be a good candidate for > arrows. In this case I'd be more interested in > composing collision detectors than in stream processing. > > OTOH, when I move parcels around and process then in various stages, then > a "stream processor" would make perfect sense > to me. In that case, would I abandon the DES paradigm entirely (including > the notion of an event queue) and just model > the network and let it run? > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.drautzburg at web.de Wed Apr 15 19:31:27 2015 From: martin.drautzburg at web.de (martin) Date: Wed, 15 Apr 2015 21:31:27 +0200 Subject: [Haskell-beginners] Point free mystery Message-ID: <552EBC8F.6060502@web.de> Helly all for ad-hoc benchmarking I wrote bench x = (timeIt . print) x Hlint suggested Found: bench x = (timeIt . print) x Why not: bench = (timeIt . print) but when I do this, I get No instance for (Show a0) arising from a use of ?print? Why is that so? From chaddai.fouche at gmail.com Wed Apr 15 19:39:36 2015 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Wed, 15 Apr 2015 21:39:36 +0200 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: > > 15 ????. 2015 19:27 "emacstheviking" ????: > > I just love the way Haskell can blow something really simple into >> something truly mind blowingly obtuse looking at times! >> It's no wonder Haskell won't be "mainstream" for a while yet, but that's >> fine, it means the rest of us can charge better rates for now. >> :) >> >> This is simple. More precisely, it couldn't be otherwise. data Either l r = Left l | Right r See how this definition has two type parameters ? The problem was obscured in the first question by the fact that "replicate 3" can be applied to any type. But if you take a less polymorphic function like length, it soon become obvious that this is the way fmap should work : fmap length (Right "stuff") = length "stuff" fmap length (Left 5) = length 5 ???? What does that even means ? Since the type contained by Left and Right are different, you can't in general apply the same function to both possibilities. Now the right type is the last one to occur in "Either left right" so it's the one that's abstracted over in the Functor instance, there is no Functor instance for Either, the instance is for "Either left" with the left type fixed, fmap don't touch the left type, so it can't do anything to a "Left x" value. Semantically, "Either left right" can be seen as a container of one or zero "right" that contains out-of-band information of type "left" when it's empty. So when you fmap over it, you only touch the content, not the out-of-band information. -- Jeda? -------------- next part -------------- An HTML attachment was scrubbed... URL: From allbery.b at gmail.com Wed Apr 15 19:42:37 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Wed, 15 Apr 2015 15:42:37 -0400 Subject: [Haskell-beginners] Point free mystery In-Reply-To: <552EBC8F.6060502@web.de> References: <552EBC8F.6060502@web.de> Message-ID: On Wed, Apr 15, 2015 at 3:31 PM, martin wrote: > Hlint suggested > > Found: > bench x = (timeIt . print) x > Why not: > bench = (timeIt . print) > hlint is kinda dumb sometimes, like any heuristic analyzer. In particular, it recognizes patterns of code, but knows nothing about types. Or, in this case, the monomorphism restriction, which is likely messing with the inferred type (since the inferred type is correct when it has a parameter). -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From objitsu at gmail.com Thu Apr 16 08:41:29 2015 From: objitsu at gmail.com (emacstheviking) Date: Thu, 16 Apr 2015 09:41:29 +0100 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: "Semantically, "Either left right" can be seen as a container of one or zero "right" that contains out-of-band information of type "left" when it's empty. So when you fmap over it, you only touch the content, not the out-of-band information." Yup. Whatever he said. ;) ...that's bordering on monadic comparison tutorials if you ask me... LOL. A lot of people may not even know what "in band" and "out-of-band" even means. I grew up with X25, RS232, HDLC etc so that's ok by me. You have to be very very careful about how you explain things to people. One of my favourite videos on YouTube is some guy asking Richard Feynman how magnets work...well, he did ask! https://www.youtube.com/watch?v=wMFPe-DwULM On 15 April 2015 at 20:39, Chadda? Fouch? wrote: > 15 ????. 2015 19:27 "emacstheviking" ????: >> >> I just love the way Haskell can blow something really simple into >>> something truly mind blowingly obtuse looking at times! >>> It's no wonder Haskell won't be "mainstream" for a while yet, but that's >>> fine, it means the rest of us can charge better rates for now. >>> :) >>> >>> > This is simple. More precisely, it couldn't be otherwise. > > data Either l r = Left l | Right r > > See how this definition has two type parameters ? The problem was obscured > in the first question by the fact that "replicate 3" can be applied to any > type. But if you take a less polymorphic function like length, it soon > become obvious that this is the way fmap should work : > > fmap length (Right "stuff") = length "stuff" > fmap length (Left 5) = length 5 ???? What does that even means ? > > Since the type contained by Left and Right are different, you can't in > general apply the same function to both possibilities. Now the right type > is the last one to occur in "Either left right" so it's the one that's > abstracted over in the Functor instance, there is no Functor instance for > Either, the instance is for "Either left" with the left type fixed, fmap > don't touch the left type, so it can't do anything to a "Left x" value. > > Semantically, "Either left right" can be seen as a container of one or > zero "right" that contains out-of-band information of type "left" when it's > empty. So when you fmap over it, you only touch the content, not the > out-of-band information. > > -- > Jeda? > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dserban01 at gmail.com Thu Apr 16 10:08:21 2015 From: dserban01 at gmail.com (Dan Serban) Date: Thu, 16 Apr 2015 13:08:21 +0300 Subject: [Haskell-beginners] Inventing QuickCheck properties Message-ID: Hi, I'm writing QuickCheck properties for the swipeLeft function in a game of 2048. I could think of 3 very basic properties so far and I'm wondering if you guys can think of any other interesting ones. Here are mine: - Verify That It Makes The Number Of Zeroes Go Up (applies "length . (filter (==0))" to both input and output and then does a <= comparison) - Verify That It Cleanly Separates Zeroes To The Right-Hand Side (applies "all (==0) . snd . break (==0)" to the output) - Verify that It Preserves The SumTotal (assert that the sum of all integers is left unchanged) -Dan From marcin.jan.mrotek at gmail.com Thu Apr 16 19:48:52 2015 From: marcin.jan.mrotek at gmail.com (Marcin Mrotek) Date: Thu, 16 Apr 2015 21:48:52 +0200 Subject: [Haskell-beginners] Point free mystery In-Reply-To: References: <552EBC8F.6060502@web.de> Message-ID: Hello, Well, writing out all top-level types is generally considered good style amongst Haskell community, as far as I know. But whenever you get weird type errors on unannotated toplevel functions, try {-# LANGUAGE NoMonomorphismRestriction #-} at the beginning of the soruce file, just as Brandon Allbery (sort of) said, and see https://wiki.haskell.org/Monomorphism_restriction for the explanation. Best regards, Marcin Mrotek From greg at grahamtx.net Thu Apr 16 21:22:39 2015 From: greg at grahamtx.net (Greg Graham) Date: Thu, 16 Apr 2015 21:22:39 +0000 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: On Thu, Apr 16, 2015 at 3:42 AM emacstheviking wrote: > "Semantically, "Either left right" can be seen as a container of one or > zero "right" that contains out-of-band information of type "left" when it's > empty. So when you fmap over it, you only touch the content, not the > out-of-band information." > > Yup. Whatever he said. ;) ...that's bordering on monadic comparison > tutorials if you ask me... LOL. A lot of people may not even know what "in > band" and "out-of-band" even means. I grew up with X25, RS232, HDLC etc so > that's ok by me. You have to be very very careful about how you explain > things to people. One of my favourite videos on YouTube is some guy asking > Richard Feynman how magnets work...well, he did ask! > https://www.youtube.com/watch?v=wMFPe-DwULM > I am just learning Haskell, having just finished working through _Learn You a Haskell_, so I am no expert. However, the learning curve I am experience reminds me of when I went from Applesoft BASIC to Pascal, and when I went from C to C++. There was a lot of new terminology to learn such as single-entry/single exit, procedures, formal and actual parameters, encapsulation, polymorphism, early and late binding, and overloading.There were plenty of nay-sayers that claimed that these paradigms introduced unnecessary difficulties, but today you have to search far and wide for someone who advocates GOTOs, and although O-O is not universally loved, it is easily the dominant paradigm. So, although I am still finding Haskell to be awkward for me, I am able to wrestle with it until it clicks into place, and then it's really beautiful. I feel like the benefits of the language will outweigh the effort it is taking me to learn it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From objitsu at gmail.com Fri Apr 17 07:10:39 2015 From: objitsu at gmail.com (emacstheviking) Date: Fri, 17 Apr 2015 08:10:39 +0100 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: Yeah. Learning Lisp did it for me....Haskell is super-strength Kiil-Aid baby! Drink it and be changed forever. On 16 April 2015 at 22:22, Greg Graham wrote: > On Thu, Apr 16, 2015 at 3:42 AM emacstheviking wrote: > >> "Semantically, "Either left right" can be seen as a container of one or >> zero "right" that contains out-of-band information of type "left" when it's >> empty. So when you fmap over it, you only touch the content, not the >> out-of-band information." >> >> Yup. Whatever he said. ;) ...that's bordering on monadic comparison >> tutorials if you ask me... LOL. A lot of people may not even know what "in >> band" and "out-of-band" even means. I grew up with X25, RS232, HDLC etc so >> that's ok by me. You have to be very very careful about how you explain >> things to people. One of my favourite videos on YouTube is some guy asking >> Richard Feynman how magnets work...well, he did ask! >> https://www.youtube.com/watch?v=wMFPe-DwULM >> > > I am just learning Haskell, having just finished working through _Learn > You a Haskell_, so I am no expert. However, the learning curve I am > experience reminds me of when I went from Applesoft BASIC to Pascal, and > when I went from C to C++. There was a lot of new terminology to learn such > as single-entry/single exit, procedures, formal and actual parameters, > encapsulation, polymorphism, early and late binding, and overloading.There > were plenty of nay-sayers that claimed that these paradigms introduced > unnecessary difficulties, but today you have to search far and wide for > someone who advocates GOTOs, and although O-O is not universally loved, it > is easily the dominant paradigm. > > So, although I am still finding Haskell to be awkward for me, I am able to > wrestle with it until it clicks into place, and then it's really beautiful. > I feel like the benefits of the language will outweigh the effort it is > taking me to learn it. > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From objitsu at gmail.com Fri Apr 17 07:10:55 2015 From: objitsu at gmail.com (emacstheviking) Date: Fri, 17 Apr 2015 08:10:55 +0100 Subject: [Haskell-beginners] Left vs Right In-Reply-To: References: Message-ID: Kool-Aid! It affects ones spelling too! LMAO On 17 April 2015 at 08:10, emacstheviking wrote: > Yeah. Learning Lisp did it for me....Haskell is super-strength Kiil-Aid > baby! Drink it and be changed forever. > > > On 16 April 2015 at 22:22, Greg Graham wrote: > >> On Thu, Apr 16, 2015 at 3:42 AM emacstheviking wrote: >> >>> "Semantically, "Either left right" can be seen as a container of one or >>> zero "right" that contains out-of-band information of type "left" when it's >>> empty. So when you fmap over it, you only touch the content, not the >>> out-of-band information." >>> >>> Yup. Whatever he said. ;) ...that's bordering on monadic comparison >>> tutorials if you ask me... LOL. A lot of people may not even know what "in >>> band" and "out-of-band" even means. I grew up with X25, RS232, HDLC etc so >>> that's ok by me. You have to be very very careful about how you explain >>> things to people. One of my favourite videos on YouTube is some guy asking >>> Richard Feynman how magnets work...well, he did ask! >>> https://www.youtube.com/watch?v=wMFPe-DwULM >>> >> >> I am just learning Haskell, having just finished working through _Learn >> You a Haskell_, so I am no expert. However, the learning curve I am >> experience reminds me of when I went from Applesoft BASIC to Pascal, and >> when I went from C to C++. There was a lot of new terminology to learn such >> as single-entry/single exit, procedures, formal and actual parameters, >> encapsulation, polymorphism, early and late binding, and overloading.There >> were plenty of nay-sayers that claimed that these paradigms introduced >> unnecessary difficulties, but today you have to search far and wide for >> someone who advocates GOTOs, and although O-O is not universally loved, it >> is easily the dominant paradigm. >> >> So, although I am still finding Haskell to be awkward for me, I am able >> to wrestle with it until it clicks into place, and then it's really >> beautiful. I feel like the benefits of the language will outweigh the >> effort it is taking me to learn it. >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From florian.gillard at gmail.com Fri Apr 17 13:09:49 2015 From: florian.gillard at gmail.com (Florian Gillard) Date: Fri, 17 Apr 2015 15:09:49 +0200 Subject: [Haskell-beginners] texture mapping with SDL Message-ID: Hi everyone, I am trying to make a basic raycaster (something like the first wolfenstein 3D) using haskell and SDL 1.2 So far I have it working using coloured lines and I would like to know if there is any way to apply transforms to textures loaded in memory using SDL, in order to achieve basic texture mapping on the walls. I looked at the SDL doc but I didn't find anything looking like what I need. The code is there: https://github.com/eniac314/maze-generator/blob/master/raycaster.hs (the last part is not done yet but has nothing to do with the raycaster) I would appreciate any suggestion :) -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: raycaster.png Type: image/png Size: 6078 bytes Desc: not available URL: From florian.gillard at gmail.com Fri Apr 17 13:58:14 2015 From: florian.gillard at gmail.com (Florian Gillard) Date: Fri, 17 Apr 2015 15:58:14 +0200 Subject: [Haskell-beginners] texture mapping with SDL Message-ID: Hi everyone, I am not sure my previous message went trough, if so, sorry for the double post. I am trying to make a basic raycaster (something like the first wolfenstein 3D) using haskell and SDL 1.2 So far I have it working using coloured lines and I would like to know if there is any way to apply transforms to textures loaded in memory using SDL, in order to achieve basic texture mapping on the walls. I looked at the SDL doc but I didn't find anything looking like what I need. The code is there: https://github.com/eniac314/maze-generator/blob/master/raycaster.hs sreenshot here: https://github.com/eniac314/maze-generator/blob/master/raycaster.png (the last part is not done yet but has nothing to do with the raycaster) I would appreciate any suggestion :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumit.sahrawat.apm13 at iitbhu.ac.in Fri Apr 17 16:24:01 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Fri, 17 Apr 2015 21:54:01 +0530 Subject: [Haskell-beginners] texture mapping with SDL In-Reply-To: References: Message-ID: On 17 April 2015 at 19:28, Florian Gillard wrote: > Hi everyone, > > I am not sure my previous message went trough, if so, sorry for the double > post. > > I am trying to make a basic raycaster (something like the first > wolfenstein 3D) using haskell and SDL 1.2 > > So far I have it working using coloured lines and I would like to know if > there is any way to apply transforms to textures loaded in memory using > SDL, in order to achieve basic texture mapping on the walls. > > I looked at the SDL doc but I didn't find anything looking like what I > need. > > The code is there: > > https://github.com/eniac314/maze-generator/blob/master/raycaster.hs > > sreenshot here: > https://github.com/eniac314/maze-generator/blob/master/raycaster.png > > (the last part is not done yet but has nothing to do with the raycaster) > > I would appreciate any suggestion :) > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > The message got through. It might be better answered on the haskell-cafe so I'm relaying it there. -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From florian.gillard at gmail.com Fri Apr 17 17:02:00 2015 From: florian.gillard at gmail.com (Florian Gillard) Date: Fri, 17 Apr 2015 19:02:00 +0200 Subject: [Haskell-beginners] texture mapping with SDL In-Reply-To: References: Message-ID: great thank you! On Fri, Apr 17, 2015 at 6:24 PM, Sumit Sahrawat, Maths & Computing, IIT (BHU) wrote: > On 17 April 2015 at 19:28, Florian Gillard > wrote: > >> Hi everyone, >> >> I am not sure my previous message went trough, if so, sorry for the >> double post. >> >> I am trying to make a basic raycaster (something like the first >> wolfenstein 3D) using haskell and SDL 1.2 >> >> So far I have it working using coloured lines and I would like to know if >> there is any way to apply transforms to textures loaded in memory using >> SDL, in order to achieve basic texture mapping on the walls. >> >> I looked at the SDL doc but I didn't find anything looking like what I >> need. >> >> The code is there: >> >> https://github.com/eniac314/maze-generator/blob/master/raycaster.hs >> >> sreenshot here: >> https://github.com/eniac314/maze-generator/blob/master/raycaster.png >> >> (the last part is not done yet but has nothing to do with the raycaster) >> >> I would appreciate any suggestion :) >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > The message got through. It might be better answered on the haskell-cafe > so I'm relaying it there. > > -- > Regards > > Sumit Sahrawat > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjakway at nyu.edu Fri Apr 17 19:25:52 2015 From: tjakway at nyu.edu (Thomas Jakway) Date: Fri, 17 Apr 2015 15:25:52 -0400 Subject: [Haskell-beginners] State Monad Message-ID: <55315E40.10805@nyu.edu> I'm having some trouble using the state monad with a random number generator. I'm trying to follow the LYAH example (http://learnyouahaskell.com/for-a-few-monads-more) but apparently the state monad API has changed, so I'm using Control.Monad.Trans.State.Lazy (state monad from the transformers package). Side question: is using transformers a good idea? I've heard some people complain about mtl's performance, others don't seem to care. I'm far too new to be able to judge anything (does it even make sense to compare transformers vs. mtl?) but if one has overtaken the other I'd rather use that. Here's what I currently have: import Control.Monad.Trans.State.Lazy type GeneratorState = State StdGen genThree :: Int -> GeneratorState Int genThree listMax = do --highest index in the list let listMin = 0 :: Int --lowest index in the list generator <- get let (generatedMin, state) = randomR (listMin, listMax) generator return generatedMin Although it typechecks it doesn't seem like an improvement over just using StdGen by itself. What I think I should have: genThree :: Int -> GeneratorState Int genThree listMax = do --highest index in the list let listMin = 0 :: Int --lowest index in the list generatedMin <- state randomR (listMin, listMax) return generatedMin * *I feel like I really botched this--what am I missing? * * -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.drautzburg at web.de Fri Apr 17 20:08:08 2015 From: martin.drautzburg at web.de (martin) Date: Fri, 17 Apr 2015 22:08:08 +0200 Subject: [Haskell-beginners] dropWhile returning last dropped element Message-ID: <55316828.7000405@web.de> Hello all Just curious: is there a library function like dropWhile, but which returns last dropped element along with the remainder of the list? If not, how can I write one - without explicit recursion - without traversing the list more than once - without traversing more of the list than necessary From fa-ml at ariis.it Fri Apr 17 20:20:31 2015 From: fa-ml at ariis.it (Francesco Ariis) Date: Fri, 17 Apr 2015 22:20:31 +0200 Subject: [Haskell-beginners] dropWhile returning last dropped element In-Reply-To: <55316828.7000405@web.de> References: <55316828.7000405@web.de> Message-ID: <20150417202031.GA20481@x60s.casa> On Fri, Apr 17, 2015 at 10:08:08PM +0200, martin wrote: > Hello all > > Just curious: is there a library function like dropWhile, > but which returns last dropped element along with the remainder of the > list? None that I know of, but span from Data.List might be worth a look From michael at orlitzky.com Fri Apr 17 21:18:37 2015 From: michael at orlitzky.com (Michael Orlitzky) Date: Fri, 17 Apr 2015 17:18:37 -0400 Subject: [Haskell-beginners] dropWhile returning last dropped element In-Reply-To: <55316828.7000405@web.de> References: <55316828.7000405@web.de> Message-ID: <553178AD.3090407@orlitzky.com> On 04/17/2015 04:08 PM, martin wrote: > Hello all > > Just curious: is there a library function like dropWhile, but which returns last dropped element along with the > remainder of the list? > > If not, how can I write one > > - without explicit recursion > - without traversing the list more than once > - without traversing more of the list than necessary Here's a version that meets your last two criteria, complete with QuickCheck tests to make sure it works. Why do you want to avoid recursion? You could rewrite this to use list indices if you really wanted to, but anything you come up with is going to be essentially recursive, only less safe ---- module Main where import Test.QuickCheck -- | A version of dropWhile that returns the last element dropped as -- well as the remainder of the list. This is simply sugar over the -- 'dw' function, so you don't have to pass in a (Nothing,) tuple at -- first. -- dropWhile' :: (a -> Bool) -- ^ The predicate used to drop stuff -> [a] -- ^ The list of stuff -> (Maybe a, [a]) -- ^ (The last element dropped, list tail) dropWhile' p xs = dw p (Nothing, xs) -- | The \"real\" implementation of the dropWhile'. -- dw :: (a -> Bool) -- ^ The predicate used to drop stuff -> (Maybe a, [a]) -- ^ (Current last element dropped, current list) -> (Maybe a, [a]) -- ^ (New last element dropped, remaining list) -- This case is pretty easy. There's nothing left in the list, so just -- return what we've got. dw _ (lastdropped, []) = (lastdropped, []) dw predicate (lastdropped, xs@(x:tail_of_xs)) -- Drop the first element of the list, and "update" the return value -- before recursing. | predicate x = dw predicate (Just x, tail_of_xs) -- We're not dropping any more, just quit. | otherwise = (lastdropped, xs) -- | Make sure the tail of the list we get back is the same as it would -- be if we used dropWhile. -- prop_tailcorrect :: [Int] -> Bool prop_tailcorrect ints = actual == expected where (_, actual) = dropWhile' even ints expected = dropWhile even ints -- | Use a slower algorithm to make sure that we're getting the -- correct \"last item dropped\". -- prop_lastcorrect :: [Int] -> Bool prop_lastcorrect ints = actual == expected where (actual, _) = dropWhile' even ints expected = case (reverse $ takeWhile even ints) of [] -> Nothing (x:_) -> Just x From sumit.sahrawat.apm13 at iitbhu.ac.in Fri Apr 17 22:31:02 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Sat, 18 Apr 2015 04:01:02 +0530 Subject: [Haskell-beginners] State Monad In-Reply-To: <55315E40.10805@nyu.edu> References: <55315E40.10805@nyu.edu> Message-ID: A good exercise will be to re-implement State, and then use it. Take a look here: http://en.wikibooks.org/wiki/Haskell/Understanding_monads/State. This link will take you to a tutorial that takes you through the implementation of State, and then uses it for random number generation. Hope this helps. Enjoy ! On 18 April 2015 at 00:55, Thomas Jakway wrote: > I'm having some trouble using the state monad with a random number > generator. > > I'm trying to follow the LYAH example ( > http://learnyouahaskell.com/for-a-few-monads-more) but apparently the > state monad API has changed, so I'm using Control.Monad.Trans.State.Lazy > (state monad from the transformers package). Side question: is using > transformers a good idea? I've heard some people complain about mtl's > performance, others don't seem to care. I'm far too new to be able to > judge anything (does it even make sense to compare transformers vs. mtl?) > but if one has overtaken the other I'd rather use that. > > Here's what I currently have: > import Control.Monad.Trans.State.Lazy > type GeneratorState = State StdGen > > genThree :: Int -> GeneratorState Int > genThree listMax = do --highest index in the list > let listMin = 0 :: Int --lowest index in the list > generator <- get > let (generatedMin, state) = randomR (listMin, listMax) generator > return generatedMin > > Although it typechecks it doesn't seem like an improvement over just using > StdGen by itself. > > What I think I should have: > genThree :: Int -> GeneratorState Int > genThree listMax = do --highest index in the list > let listMin = 0 :: Int --lowest index in the list > generatedMin <- state randomR (listMin, listMax) > return generatedMin > > I feel like I really botched this--what am I missing? > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwm at mired.org Fri Apr 17 22:48:48 2015 From: mwm at mired.org (Mike Meyer) Date: Fri, 17 Apr 2015 17:48:48 -0500 Subject: [Haskell-beginners] State Monad In-Reply-To: <55315E40.10805@nyu.edu> References: <55315E40.10805@nyu.edu> Message-ID: On Fri, Apr 17, 2015 at 2:25 PM, Thomas Jakway wrote: > genThree listMax = do --highest index in the list > let listMin = 0 :: Int --lowest index in the list > generatedMin <- state randomR (listMin, listMax) > return generatedMin > What you're missing is a $: The only chagne to our genThree functions is making it "state $" instead of "state". #!/usr/bin/env runhaskell import System.Random import Control.Monad.State genThree listMax = do --highest index in the list let listMin = 0 :: Int --lowest index in the list generatedMin <- state $ randomR (listMin, listMax) return generatedMin main = do gen <- newStdGen print $ evalState (genThree 10) gen -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjakway at nyu.edu Fri Apr 17 23:19:36 2015 From: tjakway at nyu.edu (Thomas Jakway) Date: Fri, 17 Apr 2015 19:19:36 -0400 Subject: [Haskell-beginners] State Monad In-Reply-To: References: <55315E40.10805@nyu.edu> Message-ID: <55319508.9050709@nyu.edu> Thank you very much! On 4/17/15 6:48 PM, Mike Meyer wrote: > > On Fri, Apr 17, 2015 at 2:25 PM, Thomas Jakway > wrote: > > genThree listMax = do --highest index in the list > let listMin = 0 :: Int --lowest index in the list > generatedMin <- state randomR (listMin, listMax) > return generatedMin > > > What you're missing is a $: > > The only chagne to our genThree functions is making it "state $" > instead of "state". > > > #!/usr/bin/env runhaskell > > import System.Random > import Control.Monad.State > > genThree listMax = do --highest index in the list > let listMin = 0 :: Int --lowest index in the list > generatedMin <- state $ randomR (listMin, listMax) > return generatedMin > > main = do > gen <- newStdGen > print $ evalState (genThree 10) gen > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwm at mired.org Fri Apr 17 23:34:30 2015 From: mwm at mired.org (Mike Meyer) Date: Fri, 17 Apr 2015 18:34:30 -0500 Subject: [Haskell-beginners] State Monad In-Reply-To: <55319508.9050709@nyu.edu> References: <55315E40.10805@nyu.edu> <55319508.9050709@nyu.edu> Message-ID: Ok, now the analysis. Without the $, you get this error message (ghci 7.8.3): Couldn't match type ?g0 -> (a0, g0)? with ?(a, (a0, a0))? Expected type: (a0, a0) -> (a, (a0, a0)) Actual type: (a0, a0) -> g0 -> (a0, g0) Relevant bindings include genThree :: t -> a (bound at /tmp/test.hs:6:1) Probable cause: ?randomR? is applied to too few arguments In the first argument of ?state?, namely ?randomR? In a stmt of a 'do' block: state randomR (listMin, listMax) The key line is "Probable cause: 'randomR' is applied to too few arguments". Since it takes and apparently has one argument, the most likely cause is that the expression isn't parsed the way you expect.. So make the parse explicit, which would be "state (randomR (listMin, listMax))". Using the $ operator does the same thing, and reads a bit cleaner once you get used to it. On Fri, Apr 17, 2015 at 6:19 PM, Thomas Jakway wrote: > Thank you very much! > > On 4/17/15 6:48 PM, Mike Meyer wrote: > > > On Fri, Apr 17, 2015 at 2:25 PM, Thomas Jakway wrote: > >> genThree listMax = do --highest index in the list >> let listMin = 0 :: Int --lowest index in the list >> generatedMin <- state randomR (listMin, listMax) >> return generatedMin >> > > What you're missing is a $: > > The only chagne to our genThree functions is making it "state $" instead > of "state". > > > #!/usr/bin/env runhaskell > > import System.Random > import Control.Monad.State > > genThree listMax = do --highest index in the list > let listMin = 0 :: Int --lowest index in the list > generatedMin <- state $ randomR (listMin, listMax) > return generatedMin > > main = do > gen <- newStdGen > print $ evalState (genThree 10) gen > > > > _______________________________________________ > Beginners mailing listBeginners at haskell.orghttp://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sourabh.s.joshi at gmail.com Sat Apr 18 03:41:41 2015 From: sourabh.s.joshi at gmail.com (Sourabh) Date: Fri, 17 Apr 2015 20:41:41 -0700 Subject: [Haskell-beginners] GCJ 2015 - Round 1A Problem - Haircut Message-ID: So I decided to try the Google Code Jam this year, and decided to code in Haskell. I passed the qualifiers, and today was Round 1A. I managed to get the first problem right (both small and large input), and got the 2nd problem right (for the small input). However, for the large input, it ran out of stack space with the following error: Stack space overflow: current size 33632 bytes Use '+RTS -Ksize -RTS' to increase it. Can someone tell me how I could have avoided or fixed this? It is also very possible that I had an algorithmic issue (needed to optimize my code or have a different algorithm for the large input perhaps?). Here is the problem description: https://code.google.com/codejam/contest/4224486/dashboard#s=p1 And here is my code: https://github.com/cbrghostrider/Hacking/blob/master/codeJam/2015/haircut/haircut_try2.hs I made sure to use foldr, which is supposedly more stack efficient I believe. I don't know if the list append (++) was causing issues. If anyone can spot any problems, or provide suggestions, I would really appreciate it! Even though the round is done, I'd like to optimize this to make it run within 8 minutes, as intended. Thanks in advance! -- SSJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From konstantin.saveljev at gmail.com Sat Apr 18 09:04:30 2015 From: konstantin.saveljev at gmail.com (Konstantin Saveljev) Date: Sat, 18 Apr 2015 12:04:30 +0300 Subject: [Haskell-beginners] StateT MyState IO a vs ReaderT (IORef MyState) IO a Message-ID: Hello, I'm working on a project where I use StateT MyState IO a to keep track of the state. MyState is deeply nested and I use lens to help me more easily access and modify the state. Just about yesterday I found someone mentioning about using ReaderT (IORef MyState) IO a instead of StateT MyState IO a because we are already in IO. Can someone explain to me what are the benefits of these different approaches? What about Garbage Collection in both cases (if there is any difference at all)? Can you use lens package to access and update the state which is hidden behind IORef ? Thanks, Konstantin Saveljev -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumit.sahrawat.apm13 at iitbhu.ac.in Sat Apr 18 09:59:00 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Sat, 18 Apr 2015 15:29:00 +0530 Subject: [Haskell-beginners] GCJ 2015 - Round 1A Problem - Haircut In-Reply-To: References: Message-ID: Take a look here: https://www.haskell.org/haskellwiki/Foldr_Foldl_Foldl' Foldr is not recommended in most cases, the above article explains it all. On 18 April 2015 at 09:11, Sourabh wrote: > So I decided to try the Google Code Jam this year, and decided to code in > Haskell. > > I passed the qualifiers, and today was Round 1A. I managed to get the > first problem right (both small and large input), and got the 2nd problem > right (for the small input). However, for the large input, it ran out of > stack space with the following error: > Stack space overflow: current size 33632 bytes > Use '+RTS -Ksize -RTS' to increase it. > > Can someone tell me how I could have avoided or fixed this? > > It is also very possible that I had an algorithmic issue (needed to > optimize my code or have a different algorithm for the large input > perhaps?). > > Here is the problem description: > https://code.google.com/codejam/contest/4224486/dashboard#s=p1 > > And here is my code: > > https://github.com/cbrghostrider/Hacking/blob/master/codeJam/2015/haircut/haircut_try2.hs > > > I made sure to use foldr, which is supposedly more stack efficient I > believe. I don't know if the list append (++) was causing issues. > > If anyone can spot any problems, or provide suggestions, I would really > appreciate it! Even though the round is done, I'd like to optimize this to > make it run within 8 minutes, as intended. > > Thanks in advance! > -- > SSJ > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From doug at cs.dartmouth.edu Sat Apr 18 14:29:11 2015 From: doug at cs.dartmouth.edu (Doug McIlroy) Date: Sat, 18 Apr 2015 10:29:11 -0400 Subject: [Haskell-beginners] GCJ 2015 - Round 1A Problem - Haircut Message-ID: <201504181429.t3IETBfo025201@coolidge.cs.dartmouth.edu> > Can someone tell me how I could have avoided or fixed this? The trouble manifested as stack overflow on solving > https://code.google.com/codejam/contest/4224486/dashboard#s=p1 For efficiency, you'll probably need more cleverness in math than in Haskell. You can predict an approximate start time for the Nth customer's service from the average per-customer service time M, where 1/M = sum 1/M_k. Starting from that estimate, one can skip over almost the entire service simulation. Doug McIlroy From sourabh.s.joshi at gmail.com Sat Apr 18 15:34:42 2015 From: sourabh.s.joshi at gmail.com (Sourabh) Date: Sat, 18 Apr 2015 08:34:42 -0700 Subject: [Haskell-beginners] GCJ 2015 - Round 1A Problem - Haircut In-Reply-To: <201504181429.t3IETBfo025201@coolidge.cs.dartmouth.edu> References: <201504181429.t3IETBfo025201@coolidge.cs.dartmouth.edu> Message-ID: Thanks Sumit, I changed my folds to a strict foldl'. I'll check how long it runs now. Doug, I think you are absolutely correct. Taking the harmonic mean probably factored into the solution, in order to make it algorithmically feasible for the large input! Lesson learnt, next time I'll probably think harder about the problem than the code ;) On Sat, Apr 18, 2015 at 7:29 AM, Doug McIlroy wrote: > > Can someone tell me how I could have avoided or fixed this? > > The trouble manifested as stack overflow on solving > > > https://code.google.com/codejam/contest/4224486/dashboard#s=p1 > > For efficiency, you'll probably need more cleverness in math than > in Haskell. You can predict an approximate start time for the Nth > customer's service from the average per-customer service time M, > where 1/M = sum 1/M_k. > Starting from that estimate, one can skip over almost the entire > service simulation. > > Doug McIlroy > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumit.sahrawat.apm13 at iitbhu.ac.in Sat Apr 18 15:51:49 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Sat, 18 Apr 2015 21:21:49 +0530 Subject: [Haskell-beginners] GCJ 2015 - Round 1A Problem - Haircut In-Reply-To: References: <201504181429.t3IETBfo025201@coolidge.cs.dartmouth.edu> Message-ID: The link doesn't work because the hyperlink doesn't include the apostrophe at the end. Also, I'm sorry for having written off foldr as being worthless, I didn't think much about it when I replied. Foldl is the bad one here, whereas foldr and foldl' are both good and recommended options. Foldr can cause stack overflow as it also creates unevaluated thunks, but then you can use foldl' to get over that. How did it go with strict foldl? On 18 April 2015 at 21:04, Sourabh wrote: > Thanks Sumit, I changed my folds to a strict foldl'. I'll check how long > it runs now. > > Doug, I think you are absolutely correct. Taking the harmonic mean > probably factored into the solution, in order to make it algorithmically > feasible for the large input! Lesson learnt, next time I'll probably think > harder about the problem than the code ;) > > On Sat, Apr 18, 2015 at 7:29 AM, Doug McIlroy > wrote: > >> > Can someone tell me how I could have avoided or fixed this? >> >> The trouble manifested as stack overflow on solving >> >> > https://code.google.com/codejam/contest/4224486/dashboard#s=p1 >> >> For efficiency, you'll probably need more cleverness in math than >> in Haskell. You can predict an approximate start time for the Nth >> customer's service from the average per-customer service time M, >> where 1/M = sum 1/M_k. >> Starting from that estimate, one can skip over almost the entire >> service simulation. >> >> Doug McIlroy >> > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From sourabh.s.joshi at gmail.com Sat Apr 18 15:58:23 2015 From: sourabh.s.joshi at gmail.com (Sourabh) Date: Sat, 18 Apr 2015 08:58:23 -0700 Subject: [Haskell-beginners] GCJ 2015 - Round 1A Problem - Haircut In-Reply-To: References: <201504181429.t3IETBfo025201@coolidge.cs.dartmouth.edu> Message-ID: Strict foldl' solved the stack overflow issue, thanks for catching this Sumit. However it is still taking way too long to compute, which means this wasn't the intended solution for the problem. I'll need to compute the average service time w/ the harmonic mean as Doug suggested and then massage the code some more to get exactly what is asked. -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.drautzburg at web.de Sat Apr 18 17:10:35 2015 From: martin.drautzburg at web.de (martin) Date: Sat, 18 Apr 2015 19:10:35 +0200 Subject: [Haskell-beginners] dropWhile returning last dropped element In-Reply-To: <553178AD.3090407@orlitzky.com> References: <55316828.7000405@web.de> <553178AD.3090407@orlitzky.com> Message-ID: <5532900B.5000403@web.de> Am 04/17/2015 um 11:18 PM schrieb Michael Orlitzky: > Why do you want to avoid recursion? You could rewrite this to use list indices if you really wanted to, but anything > you come up with is going to be essentially recursive, only less safe Thanks for the code sample and pointing out that there may not be any last dropped element. I was wondering if there is to achive the desired behavior by plugging together higher-order functions. This was the only reason why I wanted to avoid explicit recursion. From grzegorzmilka at gmail.com Sat Apr 18 19:10:00 2015 From: grzegorzmilka at gmail.com (Grzegorz Milka) Date: Sat, 18 Apr 2015 21:10:00 +0200 Subject: [Haskell-beginners] StateT MyState IO a vs ReaderT (IORef MyState) IO a Message-ID: <5532AC08.4030707@gmail.com> ReaderT (IORef MyState) IO a is introducing a global mutable state into your IO actions. This style is discouraged, because you have less guarantees about what can happen with your state. For example IORef is not protected from multi-threaded access. If you try to use this state in multiple threads you may run into bugs. StateT MyState IO a doesn't have that problem. For a typical use-case, that is an action that: reads state, performs action, modifies state, both are similar and neither should be significantly more comfortable. I would recommend to use StateT version unless you find that either it does not fit your model of computation or that it is underperforming. As for the performance it is hard to say. StateT allows the compiler to reason more about your code, so it might optimize better. However that's only one factor. You would need to test it to find out which one is better. From michael at snoyman.com Sat Apr 18 19:12:22 2015 From: michael at snoyman.com (Michael Snoyman) Date: Sat, 18 Apr 2015 19:12:22 +0000 Subject: [Haskell-beginners] StateT MyState IO a vs ReaderT (IORef MyState) IO a In-Reply-To: References: Message-ID: I actually released a library a week or two back that uses this trick: https://github.com/fpco/monad-unlift#reference-transformers The main advantage in my mind is that the state survives exceptions. On Sat, Apr 18, 2015 at 12:09 PM Konstantin Saveljev < konstantin.saveljev at gmail.com> wrote: > Hello, > > I'm working on a project where I use StateT MyState IO a to keep track of > the state. MyState is deeply nested and I use lens to help me more easily > access and modify the state. > > Just about yesterday I found someone mentioning about using ReaderT (IORef > MyState) IO a instead of StateT MyState IO a because we are already in IO. > > Can someone explain to me what are the benefits of these different > approaches? What about Garbage Collection in both cases (if there is any > difference at all)? Can you use lens package to access and update the state > which is hidden behind IORef ? > > Thanks, > Konstantin Saveljev > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at orlitzky.com Sat Apr 18 23:21:24 2015 From: michael at orlitzky.com (Michael Orlitzky) Date: Sat, 18 Apr 2015 19:21:24 -0400 Subject: [Haskell-beginners] dropWhile returning last dropped element In-Reply-To: <5532900B.5000403@web.de> References: <55316828.7000405@web.de> <553178AD.3090407@orlitzky.com> <5532900B.5000403@web.de> Message-ID: <5532E6F4.5050401@orlitzky.com> On 04/18/2015 01:10 PM, martin wrote: > Am 04/17/2015 um 11:18 PM schrieb Michael Orlitzky: > >> Why do you want to avoid recursion? You could rewrite this to use list indices if you really wanted to, but anything >> you come up with is going to be essentially recursive, only less safe > > Thanks for the code sample and pointing out that there may not be any last dropped element. > > I was wondering if there is to achive the desired behavior by plugging together higher-order functions. This was the > only reason why I wanted to avoid explicit recursion. > Sure. Whenever you're processing a list and building up a return value, it's probably a (left) fold. But a fold would pointlessly process the rest of the list after it had stopped dropping elements, violating one of your criteria. And foldl is of course implemented recursively =) A "short-circuiting" version of foldl might exist in some library, but there are a few ways I can think of to implement it, so it might be hard to find. From bob at redivi.com Sat Apr 18 23:48:08 2015 From: bob at redivi.com (Bob Ippolito) Date: Sat, 18 Apr 2015 16:48:08 -0700 Subject: [Haskell-beginners] dropWhile returning last dropped element In-Reply-To: <5532E6F4.5050401@orlitzky.com> References: <55316828.7000405@web.de> <553178AD.3090407@orlitzky.com> <5532900B.5000403@web.de> <5532E6F4.5050401@orlitzky.com> Message-ID: On Sat, Apr 18, 2015 at 4:21 PM, Michael Orlitzky wrote: > On 04/18/2015 01:10 PM, martin wrote: > > Am 04/17/2015 um 11:18 PM schrieb Michael Orlitzky: > > > >> Why do you want to avoid recursion? You could rewrite this to use list > indices if you really wanted to, but anything > >> you come up with is going to be essentially recursive, only less safe > > > > Thanks for the code sample and pointing out that there may not be any > last dropped element. > > > > I was wondering if there is to achive the desired behavior by plugging > together higher-order functions. This was the > > only reason why I wanted to avoid explicit recursion. > > > > Sure. Whenever you're processing a list and building up a return value, > it's probably a (left) fold. But a fold would pointlessly process the > rest of the list after it had stopped dropping elements, violating one > of your criteria. And foldl is of course implemented recursively =) > > A "short-circuiting" version of foldl might exist in some library, but > there are a few ways I can think of to implement it, so it might be hard > to find. You don't need a left fold for this. It's a bit awkward but you can indeed just combine functions. Here's one way to write it that should not suffer from any sort of pointless list processing. import Data.List (tails) import Data.Maybe (listToMaybe) dropWhileWithLast :: (a -> Bool) -> [a] -> (Maybe a, [a]) dropWhileWithLast f xs = -- Not partial. The last element of tails is [] and -- maybe False will guarantee a non-empty list. head . dropWhile (maybe False f . listToMaybe . snd) $ zip (Nothing : map Just xs) (tails xs) -------------- next part -------------- An HTML attachment was scrubbed... URL: From mike_k_houghton at yahoo.co.uk Sun Apr 19 09:46:11 2015 From: mike_k_houghton at yahoo.co.uk (Mike Houghton) Date: Sun, 19 Apr 2015 10:46:11 +0100 Subject: [Haskell-beginners] IO and ghci Message-ID: Hi, I have this in a .hs file and it works fine. That is I see lines printed to the screen when the .hs file is loaded and run from ghci. main = do file <- readFile "poem.txt" mapM_ putStrLn (lines file) Experimenting at the ghci command line with let f = readFile ?poem.txt? the above is fine. But doing lines f gives :52:7: Couldn't match type ?IO String? with ?[Char]? Expected type: String Actual type: IO String In the first argument of ?lines?, namely ?f? In the expression: lines f In my simplistic beginners way I think this is because when I run main = do ? everything is or is within an ?impure? area but at ghci command line it is not and I?m mixing pure/impure functions. So my questions are 1. Is this simplistic view any where near correct? 2. How can I progress at the command line in ghci? Many thanks Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From friedrichwiemer at gmail.com Sun Apr 19 10:03:03 2015 From: friedrichwiemer at gmail.com (Friedrich Wiemer) Date: Sun, 19 Apr 2015 12:03:03 +0200 Subject: [Haskell-beginners] IO and ghci In-Reply-To: References: Message-ID: <55337D57.9080203@gmail.com> Hi Mike as you perhaps have noticed, you use slightly different notations here: > file <- readFile "poem.txt" > let f = readFile ?poem.txt? You can run both versions in ghci, and if you take a look at the type signatures: ?> file <- readFile "poem.txt" ?> :t file file :: String ?> let f = readFile "poem.txt" ?> :t f f :: IO String You'll notice that f has type "IO String", whereas file only has type "String". So, to answer your second question: you can progress by using the "<-" notation, as in your haskell source code. To answer the first one: I'm not sure about ghci command prompt, but I would expect, that it is equivalent to "main = do ...". That is, the type error you got, is not due to ghci and main = do are different, but because you used to different types. To understand the "<-" notation, the example from Learn you a Haskell was quite good for me: Try to see types like "IO String" as an action or box, which can result in a string. You can take the inner type out of the box, by using "<-". Hope that helps, cheers, Friedrich -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 473 bytes Desc: OpenPGP digital signature URL: From mike_k_houghton at yahoo.co.uk Sun Apr 19 12:28:36 2015 From: mike_k_houghton at yahoo.co.uk (Mike Houghton) Date: Sun, 19 Apr 2015 13:28:36 +0100 Subject: [Haskell-beginners] IO and ghci In-Reply-To: <55337D57.9080203@gmail.com> References: <55337D57.9080203@gmail.com> Message-ID: <4C0A3698-A7E4-4609-8E2F-A82ED7FCF3F4@yahoo.co.uk> Thank you Friedrich, that really does help. At some point I became confused as I?m *sure* that I tried file <- readFile ?poem.txt? in ghci and it didn?t work! Clearly it does. :) Thanks again. Mike > On 19 Apr 2015, at 11:03, Friedrich Wiemer wrote: > > Hi Mike > as you perhaps have noticed, you use slightly different notations here: > >> file <- readFile "poem.txt" > >> let f = readFile ?poem.txt? > > You can run both versions in ghci, and if you take a look at the type > signatures: > ?> file <- readFile "poem.txt" > ?> :t file > file :: String > > ?> let f = readFile "poem.txt" > ?> :t f > f :: IO String > > You'll notice that f has type "IO String", whereas file only has type > "String". > > So, to answer your second question: you can progress by using the "<-" > notation, as in your haskell source code. > > To answer the first one: I'm not sure about ghci command prompt, but I > would expect, that it is equivalent to "main = do ...". > That is, the type error you got, is not due to ghci and main = do are > different, but because you used to different types. > > To understand the "<-" notation, the example from Learn you a Haskell > was quite good for me: > Try to see types like "IO String" as an action or box, which can result > in a string. You can take the inner type out of the box, by using "<-". > > Hope that helps, > > cheers, > Friedrich > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From himskim at msn.com Sun Apr 19 23:33:08 2015 From: himskim at msn.com (=?ks_c_5601-1987?B?sei47b3F?=) Date: Sun, 19 Apr 2015 16:33:08 -0700 Subject: [Haskell-beginners] What's the mean of >>= Message-ID: It could be stupid question because i'm very beginner of haskell. I found strange literals when i read haskell code. Does anybody explan what the mean of >>= below ocode ? And additionally, What is mean of >> itself? putStrLn' [] = putChar '\n' putStrLn' xs - putStr' xs >>= \ x -> putChar '\n' putStr' [] = return () putStr' (x : xs) = putChar x >> putStr' n (because of i18n problem, back slash literal could be shown as '\') Thank you in advance Myung Shin Kim -------------- next part -------------- An HTML attachment was scrubbed... URL: From rasen.dubi at gmail.com Sun Apr 19 23:51:33 2015 From: rasen.dubi at gmail.com (Alexey Shmalko) Date: Mon, 20 Apr 2015 02:51:33 +0300 Subject: [Haskell-beginners] What's the mean of >>= In-Reply-To: References: Message-ID: Hello! >>= and >> are methods of Monad typeclass. Their meaning may be very different depending on the actual type. For IO >>= composes a new IO action which is, when executed, executes left action first and then passes its result to the right function. So you can read putStr' xs >>= \ x -> putChar '\n' as "Execute action putStr' xs, then pass its result to \x -> putChar '\n'". Many times the result of previous action is not used (as in above example), so there is >> which is like >>= but ignores the result of first action. It's something like x >> y = x >>= (\_ -> y) So putStr' xs >> putChar '\n' is the same as putStr' xs >>= \ x -> putChar '\n' This code can be rewritten in the do-notation as: do putStr' xs putChar '\n' To summarize, for IO, >>= and >> are used to sequence actions. Best regards, Alexey Shmalko On Mon, Apr 20, 2015 at 2:33 AM, ??? wrote: > It could be stupid question because i'm very beginner of haskell. > > I found strange literals when i read haskell code. > Does anybody explan what the mean of >>= below ocode ? And additionally, > What is mean of >> itself? > > putStrLn' [] = putChar '\n' > putStrLn' xs - putStr' xs >>= \ x -> putChar '\n' > > putStr' [] = return () > putStr' (x : xs) = putChar x >> putStr' n > > (because of i18n problem, back slash literal could be shown as '\') > > Thank you in advance > Myung Shin Kim > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > From himskim at msn.com Mon Apr 20 00:13:48 2015 From: himskim at msn.com (=?ks_c_5601-1987?B?sei47b3F?=) Date: Sun, 19 Apr 2015 17:13:48 -0700 Subject: [Haskell-beginners] What's the mean of >>= In-Reply-To: References: , Message-ID: I really appeciate your answer. Thanks Again, Myung > Date: Mon, 20 Apr 2015 02:51:33 +0300 > From: rasen.dubi at gmail.com > To: beginners at haskell.org > Subject: Re: [Haskell-beginners] What's the mean of >>= > > Hello! > > >>= and >> are methods of Monad typeclass. Their meaning may be very different depending on the actual type. For IO >>= composes a new IO action which is, when executed, executes left action first and then passes its result to the right function. > > So you can read > putStr' xs >>= \ x -> putChar '\n' > as "Execute action putStr' xs, then pass its result to \x -> putChar '\n'". > > Many times the result of previous action is not used (as in above > example), so there is >> which is like >>= but ignores the result of > first action. > It's something like > x >> y = x >>= (\_ -> y) > > So putStr' xs >> putChar '\n' is the same as putStr' xs >>= \ x -> putChar '\n' > > This code can be rewritten in the do-notation as: > do > putStr' xs > putChar '\n' > > To summarize, for IO, >>= and >> are used to sequence actions. > > Best regards, > Alexey Shmalko > > On Mon, Apr 20, 2015 at 2:33 AM, ??? wrote: > > It could be stupid question because i'm very beginner of haskell. > > > > I found strange literals when i read haskell code. > > Does anybody explan what the mean of >>= below ocode ? And additionally, > > What is mean of >> itself? > > > > putStrLn' [] = putChar '\n' > > putStrLn' xs - putStr' xs >>= \ x -> putChar '\n' > > > > putStr' [] = return () > > putStr' (x : xs) = putChar x >> putStr' n > > > > (because of i18n problem, back slash literal could be shown as '\') > > > > Thank you in advance > > Myung Shin Kim > > > > > > _______________________________________________ > > Beginners mailing list > > Beginners at haskell.org > > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Tue Apr 21 11:16:47 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Tue, 21 Apr 2015 12:16:47 +0100 Subject: [Haskell-beginners] Return function Message-ID: Hi, Looking at the definition of return function for a Monad, it is described as - return :: a -> m a However when I do - return (Just 3) The result is Just 3 and not Just (Just 3) If I understand the definition correctly (which doesn't seem to be the case) the return function should wrap the parameter (which in my case is 'Just 3') into the Maybe Monad and therefore should return me 'Just (Just 3)' Please can someone help explain. Thanks, Shishir Srivastava +44 (0) 750 127 5019 -------------- next part -------------- An HTML attachment was scrubbed... URL: From josh at inv.alid.pw Tue Apr 21 11:21:30 2015 From: josh at inv.alid.pw (Josh Holland) Date: Tue, 21 Apr 2015 12:21:30 +0100 Subject: [Haskell-beginners] Return function In-Reply-To: References: Message-ID: <1429615290.585133.256554753.1C062C67@webmail.messagingengine.com> Hi, On Tue, 21 Apr 2015, at 12:16 PM, Shishir Srivastava wrote: > Hi, > > Looking at the definition of return function for a Monad, it is described > as - > > return :: a -> m a > > However when I do - > > return (Just 3) > > The result is > > Just 3 > > and not > > Just (Just 3) > > If I understand the definition correctly (which doesn't seem to be the > case) the return function should wrap the parameter (which in my case is > 'Just 3') into the Maybe Monad and therefore should return me 'Just (Just > 3)' > You haven't been clear about what environment you are "doing" `return (Just 3)`. My guess is that you are running it in GHCi, which means that it gets coerced to the IO monad. If you add an explicit type declaration, you get the wrapping as expected: Prelude> :t return (Just 3) return (Just 3) :: (Num a, Monad m) => m (Maybe a) Prelude> return (Just 3) :: Maybe (Maybe Int) Just (Just 3) Thanks, Josh From shishir.srivastava at gmail.com Tue Apr 21 14:56:50 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Tue, 21 Apr 2015 15:56:50 +0100 Subject: [Haskell-beginners] Powerset function Message-ID: Hi, In the 'learnyouahaskell' online book the powerset function is described like this - ---- powerset :: [a] -> [[a]] powerset xs = filterM (\x -> [True, False]) xs ---- And the filterM function is defined like this filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a] -- The filterM function is said to be an extension of 'filter' function which maps the monadic predicate over the given list. Now in powerset function the predicate returns a monad [True,False] for every element of the given list. So for e.g. if the input list was only [1] the output of filterM will understandably be the cartesian product of [True, False] x [1] = [[1], []]. Extending this if the given input list contains two elements [1,2] the predicate would be mapped one by one on each of the elements and the result combined which means the output should be [[1], [], [2], []] But the powerset of [1,2] is definitely not that. Please could someone help me in getting my head around with how filterM is working in this case. Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From rasen.dubi at gmail.com Tue Apr 21 15:23:59 2015 From: rasen.dubi at gmail.com (Alexey Shmalko) Date: Tue, 21 Apr 2015 18:23:59 +0300 Subject: [Haskell-beginners] Powerset function In-Reply-To: References: Message-ID: >From base-4.6.0.1 [1] the filterM is implemented like this: filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a] filterM _ [] = return [] filterM p (x:xs) = do flg <- p x ys <- filterM p xs return (if flg then x:ys else ys) So filterM (\x -> [True, False]) [1,2] is filterM (\x -> [True, False]) (1:[2]) do flg <- (\x -> [True, False]) 1 ys <- filterM (\x -> [True, False]) [2] return (if flg then x:ys else ys) do flg <- [True, False] ys <- [[2], []] return (if flg then 1:ys else ys) You get the idea. You'll end up with [[1,2],[1],[2],[]] Hope this helps, Alexey Shmalko [1] https://hackage.haskell.org/package/base-4.6.0.1/docs/src/Control-Monad.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From chaddai.fouche at gmail.com Tue Apr 21 16:41:05 2015 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Tue, 21 Apr 2015 18:41:05 +0200 Subject: [Haskell-beginners] Powerset function In-Reply-To: References: Message-ID: On Tue, Apr 21, 2015 at 4:56 PM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > Hi, > > In the 'learnyouahaskell' online book the powerset function is described > like this - > > ---- > powerset :: [a] -> [[a]] > powerset xs = filterM (\x -> [True, False]) xs > ---- > > And the filterM function is defined like this > > filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a] > > -- > > The filterM function is said to be an extension of 'filter' function which > maps the monadic predicate over the given list. > > Now in powerset function the predicate returns a monad [True,False] for > every element of the given list. > > So for e.g. if the input list was only [1] the output of filterM will > understandably be the cartesian product of [True, False] x [1] = [[1], []]. > No, this is not a single cartesian product. In a powerset, there's 2^N elements, not 2*N. A better way to imagine it is to come back to the sens of the list monad : it is often said that it encodes computations that may have several results. So here, for each element, either you keep the element (True) or you filter it out (False) and you branch out from that : if you keep it, you'll have this element followed by the filterM applied to the rest of the list (except there will be several result there too), if you filter it, you will only have the result of filterM applied to the tail. A way to visualize that is to do : sequence . map (\x -> [[x],[]]) $ [1..3] you'll get [[1],[]] x [[2],[]] x [[3],[]] just apply "map concat" to get the powerset back. -- Jeda? -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Wed Apr 22 08:31:01 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Wed, 22 Apr 2015 09:31:01 +0100 Subject: [Haskell-beginners] filterM function Message-ID: Hi, Continuing on from my previous question about powerset using filterM - Thanks to Alexey and Chadda?. filterM is implemented as below - ---- filterM _ [] = return [] filterM p (x:xs) = do flg <- p x ys <- filterM p xs return (if flg then x:ys else ys) --- I still don't quite understand how 'flg' being a boolean [] is used in the last 'if statement' of implementation because when I try to do the same thing outside in GHCi it fails miserably even though I am casting it to [Int] - -- return (if [True, False] then "4" else "3")::[Int] -- Offtopic : Also if someone can explain how do I reply to individual mails/responses to my queries because I only get a digest on my gmail and there is no way to isolate and reply to individual mails either this list's page or from digest. Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From magnus at therning.org Wed Apr 22 08:41:11 2015 From: magnus at therning.org (Magnus Therning) Date: Wed, 22 Apr 2015 10:41:11 +0200 Subject: [Haskell-beginners] filterM function In-Reply-To: References: Message-ID: On 22 April 2015 at 10:31, Shishir Srivastava wrote: > Hi, > > Continuing on from my previous question about powerset using filterM - > Thanks to Alexey and Chadda?. > > filterM is implemented as below - > > ---- > > filterM _ [] = return [] > filterM p (x:xs) = do > flg <- p x > ys <- filterM p xs > return (if flg then x:ys else ys) > > --- > > I still don't quite understand how 'flg' being a boolean [] is used in the > last 'if statement' of implementation because when I try to do the same > thing outside in GHCi it fails miserably even though I am casting it to > [Int] - > > -- > return (if [True, False] then "4" else "3")::[Int] > -- `flg` has type `Bool`, not `[Bool]`. > Offtopic : Also if someone can explain how do I reply to individual > mails/responses to my queries because I only get a digest on my gmail and > there is no way to isolate and reply to individual mails either this list's > page or from digest. I suspect you'll have to go to the list server and modify your settings there; it sounds like you have instructed it to send digests, so you need to change it to send every individual email. Alternatively you switch to a more capable mail reader, e.g. mutt, which handles digests better than gmail does. /M -- Magnus Therning OpenPGP: 0xAB4DFBA4 email: magnus at therning.org jabber: magnus at therning.org twitter: magthe http://therning.org/magnus From mwm at mired.org Wed Apr 22 09:15:31 2015 From: mwm at mired.org (Mike Meyer) Date: Wed, 22 Apr 2015 04:15:31 -0500 Subject: [Haskell-beginners] filterM function In-Reply-To: References: Message-ID: On Wed, Apr 22, 2015 at 3:31 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > I still don't quite understand how 'flg' being a boolean [] is used in > the last 'if statement' of implementation because when I try to do the > same thing outside in GHCi it fails miserably even though I am casting it > to [Int] - > > -- > return (if [True, False] then "4" else "3")::[Int] > "cast" is a misnomer in Haskell. When you add a type to an expression, you aren't changing the type of the expression like a C-style cast, but picking out a type from the set of possible types for that expression. Ignoring the if part and and focusing on return, which has a type Monad m => a -> m a. [Int] is equivalent to [] Int, so [] would be the Monad, and a is Int. While 3 can be an Int, "3", can't. So you could do return 3 :: [Int] or equivalently return 3 :: [] Int to get [3], you can't do return "3" :: [Int], because "3" can't be an Int. You can do return "3" :: [String], since "3" is a string. Just to show the range of possibilities, you can do return 3 :: IO Float, and get back 3.0 as an IO action. The monad in the type is IO, and 3 can be interpreted as a Float. -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Wed Apr 22 09:22:11 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Wed, 22 Apr 2015 10:22:11 +0100 Subject: [Haskell-beginners] filterM function Message-ID: Hi Mike, Thanks for your response. I was aware that 'casting' doesn't really fit in Haskell vocab but for the lack of better word used it. My question was however more towards the usage of [Bool] in the 'if' statement of the filterM function. More precisely - How does 'if [True, False] then x else y' work , because when I do this in GHCi it throws up the following error ? *>>Couldn't match expected type `Bool' with actual type `[Bool]'* Clearly the 'if' construct does not take a list of Boolean but a single Boolean value so how does filterM use it in it's implementation. Hope have made myself clear this time. Thanks, Shishir > From: Mike Meyer > To: The Haskell-Beginners Mailing List - Discussion of primarily > beginner-level topics related to Haskell > Cc: > Date: Wed, 22 Apr 2015 04:15:31 -0500 > Subject: Re: [Haskell-beginners] filterM function > On Wed, Apr 22, 2015 at 3:31 AM, Shishir Srivastava < > shishir.srivastava at gmail.com> wrote: > >> I still don't quite understand how 'flg' being a boolean [] is used in >> the last 'if statement' of implementation because when I try to do the >> same thing outside in GHCi it fails miserably even though I am casting it >> to [Int] - >> >> -- >> return (if [True, False] then "4" else "3")::[Int] >> > > "cast" is a misnomer in Haskell. When you add a type to an expression, you > aren't changing the type of the expression like a C-style cast, but picking > out a type from the set of possible types for that expression. > > Ignoring the if part and and focusing on return, which has a type Monad m > => a -> m a. [Int] is equivalent to [] Int, so [] would be the Monad, and a > is Int. While 3 can be an Int, "3", can't. So you could do return 3 :: > [Int] or equivalently return 3 :: [] Int to get [3], you can't do return > "3" :: [Int], because "3" can't be an Int. You can do return "3" :: > [String], since "3" is a string. Just to show the range of possibilities, > you can do return 3 :: IO Float, and get back 3.0 as an IO action. The > monad in the type is IO, and 3 can be interpreted as a Float. > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hsyl20 at gmail.com Wed Apr 22 12:08:45 2015 From: hsyl20 at gmail.com (Sylvain Henry) Date: Wed, 22 Apr 2015 14:08:45 +0200 Subject: [Haskell-beginners] filterM function In-Reply-To: References: Message-ID: You need to understand: 1) do-notation 2) Monad instance for List 1) do-notation is just syntactic sugar around (>>=) Monad operator. So: filterM p (x:xs) = p x >>= \flg -> filterM p xs >>= \ys -> if flg then x:ys else ys 2) Monad instance for List: http://hackage.haskell.org/package/base-4.8.0.0/docs/src/GHC-Base.html#line-726 In particular: xs >>= f = [y | x <- xs, y <- f x] or the equivalent: xs >>= f = concatMap f xs -- filterM specialized for [] filterM :: (a -> [Bool]) -> [a] -> [[a]] filterM _ [] = [[]] filterM p (x:xs) = concatMap (\flg -> concatMap (\ys -> [if flg then x:ys else ys]) (filterM p xs)) (p x) powerset :: [a] -> [[a]] powerset xs = filterM (\x -> [True, False]) xs i.e. powerset [] = [[]] powerset (x:xs) = concatMap (\flg -> concatMap (\ys -> [if flg then x:ys else ys]) (powerset xs)) [True,False] i.e. powerset [] = [[]] powerset (x:xs) = concatMap (\flg -> fmap (\ys -> if flg then x:ys else ys) (powerset xs)) [True,False] i.e. powerset [] = [[]] powerset (x:xs) = let ys = powerset xs in fmap (x:) ys ++ ys I would directly use the latter form instead of using filterM to implement powerset. Sylvain 2015-04-22 11:22 GMT+02:00 Shishir Srivastava : > Hi Mike, > > Thanks for your response. I was aware that 'casting' doesn't really fit in > Haskell vocab but for the lack of better word used it. > > My question was however more towards the usage of [Bool] in the 'if' > statement of the filterM function. > > More precisely - How does 'if [True, False] then x else y' work , because > when I do this in GHCi it throws up the following error ? > >>>Couldn't match expected type `Bool' with actual type `[Bool]' > > Clearly the 'if' construct does not take a list of Boolean but a single > Boolean value so how does filterM use it in it's implementation. > > Hope have made myself clear this time. > > Thanks, > Shishir > > >> >> From: Mike Meyer >> To: The Haskell-Beginners Mailing List - Discussion of primarily >> beginner-level topics related to Haskell >> Cc: >> Date: Wed, 22 Apr 2015 04:15:31 -0500 >> Subject: Re: [Haskell-beginners] filterM function >> >> On Wed, Apr 22, 2015 at 3:31 AM, Shishir Srivastava >> wrote: >>> >>> I still don't quite understand how 'flg' being a boolean [] is used in >>> the last 'if statement' of implementation because when I try to do the same >>> thing outside in GHCi it fails miserably even though I am casting it to >>> [Int] - >>> >>> -- >>> return (if [True, False] then "4" else "3")::[Int] >> >> >> "cast" is a misnomer in Haskell. When you add a type to an expression, you >> aren't changing the type of the expression like a C-style cast, but picking >> out a type from the set of possible types for that expression. >> >> Ignoring the if part and and focusing on return, which has a type Monad m >> => a -> m a. [Int] is equivalent to [] Int, so [] would be the Monad, and a >> is Int. While 3 can be an Int, "3", can't. So you could do return 3 :: [Int] >> or equivalently return 3 :: [] Int to get [3], you can't do return "3" :: >> [Int], because "3" can't be an Int. You can do return "3" :: [String], since >> "3" is a string. Just to show the range of possibilities, you can do return >> 3 :: IO Float, and get back 3.0 as an IO action. The monad in the type is >> IO, and 3 can be interpreted as a Float. >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > From rasen.dubi at gmail.com Wed Apr 22 12:22:35 2015 From: rasen.dubi at gmail.com (Alexey Shmalko) Date: Wed, 22 Apr 2015 15:22:35 +0300 Subject: [Haskell-beginners] filterM function In-Reply-To: References: Message-ID: I see misunderstand comes from flg <- p x In fact in the following code flg has type Bool: flg <- [True, False] For lists, >>= (and therefore <-) assigns every value out of list to flg and tries to proceed. The final `return` returns only a single element out of result, and all the results are concatenated together. On Wed, Apr 22, 2015 at 12:22 PM, Shishir Srivastava wrote: > Hi Mike, > > Thanks for your response. I was aware that 'casting' doesn't really fit in > Haskell vocab but for the lack of better word used it. > > My question was however more towards the usage of [Bool] in the 'if' > statement of the filterM function. > > More precisely - How does 'if [True, False] then x else y' work , because > when I do this in GHCi it throws up the following error ? > >>>Couldn't match expected type `Bool' with actual type `[Bool]' > > Clearly the 'if' construct does not take a list of Boolean but a single > Boolean value so how does filterM use it in it's implementation. > > Hope have made myself clear this time. > > Thanks, > Shishir > > >> >> From: Mike Meyer >> To: The Haskell-Beginners Mailing List - Discussion of primarily >> beginner-level topics related to Haskell >> Cc: >> Date: Wed, 22 Apr 2015 04:15:31 -0500 >> Subject: Re: [Haskell-beginners] filterM function >> >> On Wed, Apr 22, 2015 at 3:31 AM, Shishir Srivastava >> wrote: >>> >>> I still don't quite understand how 'flg' being a boolean [] is used in >>> the last 'if statement' of implementation because when I try to do the same >>> thing outside in GHCi it fails miserably even though I am casting it to >>> [Int] - >>> >>> -- >>> return (if [True, False] then "4" else "3")::[Int] >> >> >> "cast" is a misnomer in Haskell. When you add a type to an expression, you >> aren't changing the type of the expression like a C-style cast, but picking >> out a type from the set of possible types for that expression. >> >> Ignoring the if part and and focusing on return, which has a type Monad m >> => a -> m a. [Int] is equivalent to [] Int, so [] would be the Monad, and a >> is Int. While 3 can be an Int, "3", can't. So you could do return 3 :: [Int] >> or equivalently return 3 :: [] Int to get [3], you can't do return "3" :: >> [Int], because "3" can't be an Int. You can do return "3" :: [String], since >> "3" is a string. Just to show the range of possibilities, you can do return >> 3 :: IO Float, and get back 3.0 as an IO action. The monad in the type is >> IO, and 3 can be interpreted as a Float. >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > From florian.gillard at gmail.com Wed Apr 22 13:39:47 2015 From: florian.gillard at gmail.com (Florian Gillard) Date: Wed, 22 Apr 2015 15:39:47 +0200 Subject: [Haskell-beginners] integer to noise function in Haskell Message-ID: I am trying to implement a basic pelin noise function, but I have some problem with the integer to noise function used to generate deterministic noise from integer inputs. the function I am trying to implement is defined there: http://libnoise.sourceforge.net/noisegen/index.html#continuousnoise and my code so far look like this: noise2d :: (Int32, Int32) -> Double noise2d (x, y) = let m = x + y * 57 n = (shiftR m 13) ^ m j = (n * (n * n * 15731 + 789221) + 1376312589) .&. 0x7fffffff in 1.0 - (fromIntegral j / 1073741824.0) the code compile but I get the same result for any input, due to the fact that n is evaluated to 0. Is there a better way to do that? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ky3 at atamo.com Wed Apr 22 14:00:39 2015 From: ky3 at atamo.com (Kim-Ee Yeoh) Date: Wed, 22 Apr 2015 21:00:39 +0700 Subject: [Haskell-beginners] Return function In-Reply-To: <1429615290.585133.256554753.1C062C67@webmail.messagingengine.com> References: <1429615290.585133.256554753.1C062C67@webmail.messagingengine.com> Message-ID: > My guess is that you are running it in GHCi, which means that > it gets coerced to the IO monad. > "Coercion" doesn't quite capture it. Also it happens that the haskell research literature uses it in a technically specific context that doesn't apply here. What's going on in return (Just 3) being _executed_ in ghci to produce Just 3 is the REPL's defaulting to IO kicking in. p.s. In the above, I've made distinct execution from evaluation. This helps folks navigate the beginner-hazardous terrain of overloaded English. -- Kim-Ee -------------- next part -------------- An HTML attachment was scrubbed... URL: From florian.gillard at gmail.com Wed Apr 22 14:07:30 2015 From: florian.gillard at gmail.com (Florian Gillard) Date: Wed, 22 Apr 2015 16:07:30 +0200 Subject: [Haskell-beginners] integer to noise function in Haskell In-Reply-To: References: Message-ID: Got it, the error was coming from me thinking of the C "^" operator as exponent, instead of bitwise xoring. On Wed, Apr 22, 2015 at 3:39 PM, Florian Gillard wrote: > I am trying to implement a basic pelin noise function, but I have some > problem with the integer to noise function used to generate deterministic > noise from integer inputs. > > the function I am trying to implement is defined there: > http://libnoise.sourceforge.net/noisegen/index.html#continuousnoise > > and my code so far look like this: > > noise2d :: (Int32, Int32) -> Double > noise2d (x, y) = > let m = x + y * 57 > n = (shiftR m 13) ^ m > j = (n * (n * n * 15731 + 789221) + 1376312589) .&. 0x7fffffff > in 1.0 - (fromIntegral j / 1073741824.0) > > the code compile but I get the same result for any input, due to the fact > that n is evaluated to 0. > > Is there a better way to do that? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ky3 at atamo.com Wed Apr 22 14:13:05 2015 From: ky3 at atamo.com (Kim-Ee Yeoh) Date: Wed, 22 Apr 2015 21:13:05 +0700 Subject: [Haskell-beginners] integer to noise function in Haskell In-Reply-To: References: Message-ID: On Wed, Apr 22, 2015 at 8:39 PM, Florian Gillard wrote: > I am trying to implement a basic pelin noise function, but I have some > problem with the integer to noise function used to generate deterministic > noise from integer inputs. > > the function I am trying to implement is defined there: > http://libnoise.sourceforge.net/noisegen/index.html#continuousnoise I understand you're trying to transcribe an algorithm given in C into Haskell. That's a great way to learn. In fact, if you zoom out a bit, there's more to explore in the various prng libraries on hackage. For it so happens that the exact function you cited is a prng, one of many. -- Kim-Ee -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Wed Apr 22 15:24:23 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Wed, 22 Apr 2015 16:24:23 +0100 Subject: [Haskell-beginners] Value from Monad Message-ID: Hi, Going through the '<-' description in 'learnouahaskell' it says - *" If we have a Maybe String and we bind it with <- to a variable, that variable will be a String"* so if you write do str <- Just "3" str should be of type 'String'. My question is how do I return "34" by concatenating it to "4" because the following line of code fails - --- do str <- Just "3" return str++"4"::Maybe String --- or for that matter how can I return/print just the value of str from this do block ? Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumit.sahrawat.apm13 at iitbhu.ac.in Wed Apr 22 15:25:45 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Wed, 22 Apr 2015 20:55:45 +0530 Subject: [Haskell-beginners] Value from Monad In-Reply-To: References: Message-ID: return (str++"4") should work On 22 April 2015 at 20:54, Shishir Srivastava wrote: > Hi, > > Going through the '<-' description in 'learnouahaskell' it says - > > *" If we have a Maybe String and we bind it with <- to a variable, that > variable will be a String"* > > so if you write > > do > str <- Just "3" > > str should be of type 'String'. My question is how do I return "34" > by concatenating it to "4" because the following line of code fails - > > --- > do > str <- Just "3" > return str++"4"::Maybe String > --- > > or for that matter how can I return/print just the value of str from this > do block ? > > Thanks, > Shishir > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From allbery.b at gmail.com Wed Apr 22 15:28:16 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Wed, 22 Apr 2015 11:28:16 -0400 Subject: [Haskell-beginners] Value from Monad In-Reply-To: References: Message-ID: On Wed, Apr 22, 2015 at 11:24 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > return str++"4"::Maybe String > This is parsed as "(return str) ++ "4". Function application is always higher precedence than operators. -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Wed Apr 22 15:38:34 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Wed, 22 Apr 2015 16:38:34 +0100 Subject: [Haskell-beginners] Value from Monad Message-ID: Thanks ! that does work now. My next question was how do i only get "34" or "3" i.e. the Maybe value without wrapped in to a 'Maybe' ? Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwm at mired.org Wed Apr 22 15:41:15 2015 From: mwm at mired.org (Mike Meyer) Date: Wed, 22 Apr 2015 10:41:15 -0500 Subject: [Haskell-beginners] Value from Monad In-Reply-To: References: Message-ID: You should use something like the maybe function to extract it after you've returned the Just value. On Wed, Apr 22, 2015 at 10:38 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > Thanks ! that does work now. > > My next question was how do i only get "34" or "3" i.e. the Maybe value > without wrapped in to a 'Maybe' ? > > Shishir > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From allbery.b at gmail.com Wed Apr 22 15:43:38 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Wed, 22 Apr 2015 11:43:38 -0400 Subject: [Haskell-beginners] Value from Monad In-Reply-To: References: Message-ID: On Wed, Apr 22, 2015 at 11:38 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > My next question was how do i only get "34" or "3" i.e. the Maybe value > without wrapped in to a 'Maybe' ? "do" syntax lets you temporarily "unwrap" the value, but it must be rewrapped later. And if the specific monad in question is not IO, you cannot do I/O (e.g. "print" the value as in your initial message). This reflects the mapping of "do" to uses of (>>=) Prelude> :t (>>=) (>>=) :: Monad m => m a -> (a -> m b) -> m b In this example, `m` is Maybe. As it turns out, Maybe is one of the monads that lets you use pattern matching to extract values. Not all monads do; you cannot do this with IO, for example. The `maybe` function is often used instead of explicit pattern matching. -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcin.jan.mrotek at gmail.com Wed Apr 22 20:23:36 2015 From: marcin.jan.mrotek at gmail.com (Marcin Mrotek) Date: Wed, 22 Apr 2015 22:23:36 +0200 Subject: [Haskell-beginners] Value from Monad In-Reply-To: References: Message-ID: Hello, Well, you CAN use fromJust, but bear in mind that you should only use it if you are absolutely, positively, 100% sure the Maybe value you are calling fromJust on is of the form (Just something), because your program will error out if you call fromJust on a Nothing. Even if you're sure it's not a Nothing, it might be better to use maybe (error "Impossible, because (...)") id instead, so that you at the very least get a meaningful error message in case "impossible" happens ;) Other than that, it's recomennded to either use the maybe function, or pattern matching: case foo of Just x -> ... Nothing -> ... instead. Best regards, Marcin Mrotek From ahammel87 at gmail.com Wed Apr 22 20:37:39 2015 From: ahammel87 at gmail.com (Alex Hammel) Date: Wed, 22 Apr 2015 13:37:39 -0700 Subject: [Haskell-beginners] Value from Monad In-Reply-To: References: Message-ID: > Even if you're sure it's not a Nothing, it might be better to use > > maybe (error "Impossible, because (...)") id Which is the same thing as: fromMaybe (error "Impossible, because (...)") On Wed, Apr 22, 2015 at 1:23 PM, Marcin Mrotek wrote: > Hello, > > Well, you CAN use fromJust, but bear in mind that you should only use > it if you are absolutely, positively, 100% sure the Maybe value you > are calling fromJust on is of the form (Just something), because your > program will error out if you call fromJust on a Nothing. Even if > you're sure it's not a Nothing, it might be better to use > > maybe (error "Impossible, because (...)") id > > instead, so that you at the very least get a meaningful error message > in case "impossible" happens ;) Other than that, it's recomennded to > either use the maybe function, or pattern matching: > > case foo of > Just x -> ... > Nothing -> ... > > instead. > > Best regards, > Marcin Mrotek > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pengyu.ut at gmail.com Thu Apr 23 19:39:50 2015 From: pengyu.ut at gmail.com (Peng Yu) Date: Thu, 23 Apr 2015 14:39:50 -0500 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` Message-ID: ~$ cabal --version cabal-install version 1.18.0.5 using version 1.18.1.4 of the Cabal library ~$ ghc --version The Glorious Glasgow Haskell Compilation System, version 7.8.3 I got the following error. Does anybody know how to resolve it? Thanks. ~$ cabal install cabal-install Resolving dependencies... Configuring Cabal-1.22.3.0... Failed to install Cabal-1.22.3.0 Last 10 lines of the build log ( /Users/py/.cabal/logs/Cabal-1.22.3.0.log ): cabal: Error: some packages failed to install: Cabal-1.22.3.0 failed during the configure step. The exception was: user error (Undefined symbols for architecture x86_64: "_iconv", referenced from: _hs_iconv in libHSbase-4.7.0.1.a(iconv.o) (maybe you meant: _hs_iconv, _base_GHCziIOziEncodingziIconv_iconvEncodingzuloc1_info , _base_GHCziIOziEncodingziIconv_iconvEncoding9_info , _base_GHCziIOziEncodingziIconv_iconvEncoding9_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding8_info , _base_GHCziIOziEncodingziIconv_iconvEncodingzuloc_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding10_info , _base_GHCziIOziEncodingziIconv_iconvEncoding6_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding10_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding3_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding7_info , _hs_iconv_close , _base_GHCziIOziEncodingziIconv_iconvEncodingzuloc1_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding2_info , _base_GHCziIOziEncodingziIconv_iconvEncoding8_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding3_info , _base_GHCziIOziEncodingziIconv_iconvEncoding2_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding7_closure , _base_GHCziIOziEncodingziIconv_iconvEncodingzuloc_info , _base_GHCziIOziEncodingziIconv_iconvEncoding4_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding6_info , _hs_iconv_open ) "_iconv_close", referenced from: _hs_iconv_close in libHSbase-4.7.0.1.a(iconv.o) (maybe you meant: _hs_iconv_close) "_iconv_open", referenced from: _hs_iconv_open in libHSbase-4.7.0.1.a(iconv.o) (maybe you meant: _hs_iconv_open) "_locale_charset", referenced from: _localeEncoding in libHSbase-4.7.0.1.a(PrelIOUtils.o) ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) ) cabal-install-1.22.3.0 depends on Cabal-1.22.3.0 which failed to install. ~/ports$ gvim ~/.cabal/logs/ -- Regards, Peng From allbery.b at gmail.com Thu Apr 23 19:57:18 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Thu, 23 Apr 2015 15:57:18 -0400 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: References: Message-ID: On Thu, Apr 23, 2015 at 3:39 PM, Peng Yu wrote: > user error (Undefined symbols for architecture x86_64: > "_iconv", referenced from: > OS X? Do you have MacPorts or Homebrew installed? Where did you get your ghc from? (I've also seen this on FreeBSD due to a conflict between ports iconv and the base system, but its ld produces a slightly different error message.) -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From pengyu.ut at gmail.com Thu Apr 23 20:19:11 2015 From: pengyu.ut at gmail.com (Peng Yu) Date: Thu, 23 Apr 2015 15:19:11 -0500 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: References: Message-ID: It is installed from . The OS is Mac OS X. ~$ type -P ghc /usr/bin/ghc ~$ type -P cabal /usr/bin/cabal On Thu, Apr 23, 2015 at 2:57 PM, Brandon Allbery wrote: > On Thu, Apr 23, 2015 at 3:39 PM, Peng Yu wrote: >> >> user error (Undefined symbols for architecture x86_64: >> "_iconv", referenced from: > > > OS X? Do you have MacPorts or Homebrew installed? Where did you get your ghc > from? > > (I've also seen this on FreeBSD due to a conflict between ports iconv and > the base system, but its ld produces a slightly different error message.) > > -- > brandon s allbery kf8nh sine nomine associates > allbery.b at gmail.com ballbery at sinenomine.net > unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -- Regards, Peng From allbery.b at gmail.com Thu Apr 23 20:34:37 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Thu, 23 Apr 2015 16:34:37 -0400 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: References: Message-ID: On Thu, Apr 23, 2015 at 4:19 PM, Peng Yu wrote: > It is installed from > >. The OS is Mac OS X. > Yes, as I suspected. The problem is that Apple ships an old version of the iconv library; MacPorts and Homebrew generally install a newer, incompatible one with symbols renamed to trigger that link error (because otherwise you find out about the mismatch when the first iconv call dumps core at runtime). You will need to arrange for ghc not to see that other iconv, only Apple's, since it won't work with any but Apple's. Or use a ghc from whichever package manager you have installed, so that it works with that package manager's iconv library. (This is more likely to happen with Homebrew, since most things don't look /opt/local but just about everything looks under /usr/local.) -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From pengyu.ut at gmail.com Thu Apr 23 20:46:48 2015 From: pengyu.ut at gmail.com (Peng Yu) Date: Thu, 23 Apr 2015 15:46:48 -0500 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` Message-ID: Indeed, I uninstalled libiconv by running the following command. sudo port uninstall --follow-dependents libiconv Then, `cabal install cabal-install` runs without a problem. Hi MacPorts Users, Is there better solution to this problem? Please see the original question regarding the conflict of MacPorts and Haskell. (I don't what to use haskell from MacPorts as I want to keep updated with the latest version of Haskell.) https://mail.haskell.org/pipermail/beginners/2015-April/015214.html On Thu, Apr 23, 2015 at 3:34 PM, Brandon Allbery wrote: > On Thu, Apr 23, 2015 at 4:19 PM, Peng Yu wrote: >> >> It is installed from > >> >. The OS is Mac OS X. > > > Yes, as I suspected. The problem is that Apple ships an old version of the > iconv library; MacPorts and Homebrew generally install a newer, incompatible > one with symbols renamed to trigger that link error (because otherwise you > find out about the mismatch when the first iconv call dumps core at > runtime). You will need to arrange for ghc not to see that other iconv, only > Apple's, since it won't work with any but Apple's. Or use a ghc from > whichever package manager you have installed, so that it works with that > package manager's iconv library. > > (This is more likely to happen with Homebrew, since most things don't look > /opt/local but just about everything looks under /usr/local.) > > -- > brandon s allbery kf8nh sine nomine associates > allbery.b at gmail.com ballbery at sinenomine.net > unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -- Regards, Peng From allbery.b at gmail.com Thu Apr 23 21:08:20 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Thu, 23 Apr 2015 17:08:20 -0400 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: References: Message-ID: On Thu, Apr 23, 2015 at 4:46 PM, Peng Yu wrote: > Hi MacPorts Users, Is there better solution to this problem? Please > see the original question regarding the conflict of MacPorts and > Haskell. (I don't what to use haskell from MacPorts as I want to keep > updated with the latest version of Haskell.) > I personally would not --- and do not --- chase the latest ghc, because a fair amount of stuff still doesn't build with ghc 7.10.1 and we in #haskell on Freenode keep having to advise people to switch back to 7.8 until the library situation settles down. Wait for the first Platform release with 7.10 (hopefully within a month), after which MacPorts will be updated to it (developer time permitting). -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From pengyu.ut at gmail.com Thu Apr 23 21:12:59 2015 From: pengyu.ut at gmail.com (Peng Yu) Date: Thu, 23 Apr 2015 16:12:59 -0500 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: References: Message-ID: On Thu, Apr 23, 2015 at 4:08 PM, Brandon Allbery wrote: > On Thu, Apr 23, 2015 at 4:46 PM, Peng Yu wrote: >> >> Hi MacPorts Users, Is there better solution to this problem? Please >> see the original question regarding the conflict of MacPorts and >> Haskell. (I don't what to use haskell from MacPorts as I want to keep >> updated with the latest version of Haskell.) > > > I personally would not --- and do not --- chase the latest ghc, because a > fair amount of stuff still doesn't build with ghc 7.10.1 and we in #haskell > on Freenode keep having to advise people to switch back to 7.8 until the I mean not "so old" instead of "latest". I am currently using this. ~$ ghc --version The Glorious Glasgow Haskell Compilation System, version 7.8.3 I had problems with MacPorts for Python and Perl. The general suggestion is to stay way from MacPorts for managing packages offered by other language platforms. As if I use MacPorts for managing packages from these languages, I am limited by what are available from MacPorts. > library situation settles down. Wait for the first Platform release with > 7.10 (hopefully within a month), after which MacPorts will be updated to it > (developer time permitting). -- Regards, Peng From allbery.b at gmail.com Thu Apr 23 21:39:34 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Thu, 23 Apr 2015 17:39:34 -0400 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: References: Message-ID: On Thu, Apr 23, 2015 at 5:12 PM, Peng Yu wrote: > I had problems with MacPorts for Python and Perl. The general > suggestion is to stay way from MacPorts for managing packages offered > by other language platforms. > Actually, the general suggestion there is stay away from *any* packaging system for those languages --- because installing modules from both the packaging system and the language's own package repository risks breaking things with incompatible versions. I have had to help someone try to fix their Debian install after they installed a Perl module that was incompatible with dpkg; it's not just MacPorts, or even just Macs. (You can screw up a Red Hat-ish system the same way by installing the wrong Python module(s).) This is why Perl has perlbrew, Python has virtualenv, and Ruby has rvm (and for ghc, both Cabal sandboxes and hsenv). That said, a batteries-included setup like the Platform is usually an exception because you want the compiler and the Platform packages to all match, and you'll break things anyway if they don't: overriding modules that comes with ghc or with the Platform (or Stackage if you use that) is pretty much guaranteed "Cabal hell"). So get those all from the same place, but other modules from wherever --- just don't try to upgrade or replace those packages. You can add a "constraint: installed" to ~/.cabal/config for each the packages in the global package database to tell cabal-install not to touch those libraries. Note that you will have to exclude the Cabal library itself from that to install a newer cabal-install. This is actually relatively safe, although there is the potential to break ghc-as-a-library in obscure ways. # # # I think MP did end up skipping the latest Platform because the build system changed in a way that's pretty much hostile to other package systems; they've all had to come up with their own ways to build it instead, and our Haskell maintainer did not have the time to work out how to adapt one of them to a ports-based system or design his own alternative. The next Platform release is backing off from that (it ended up being no easier than the old way), so should be easier to update. -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From allbery.b at gmail.com Thu Apr 23 21:59:36 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Thu, 23 Apr 2015 17:59:36 -0400 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: <1010645676.31627.1429826169594.JavaMail.zimbra@clang.name> References: <1010645676.31627.1429826169594.JavaMail.zimbra@clang.name> Message-ID: On Thu, Apr 23, 2015 at 5:56 PM, Clemens Lang wrote: > So if you get these link errors, the problem almost always is that you > adjusted your library search path, but not the corresponding header > search path and you're actually compiling against Apple's iconv.h but > MacPorts libiconv.dylib (or vice-versa). > Those are coming from a library already built against Apple's libiconv, but being linked against MacPorts' libiconv. -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From allbery.b at gmail.com Thu Apr 23 22:02:27 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Thu, 23 Apr 2015 18:02:27 -0400 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: <949238204.31635.1429826449443.JavaMail.zimbra@clang.name> References: <949238204.31635.1429826449443.JavaMail.zimbra@clang.name> Message-ID: On Thu, Apr 23, 2015 at 6:00 PM, Clemens Lang wrote: > From https://www.haskell.org/platform/ > > it sounds like the latest platform release > is 2014.2.0.0, and that's what's currently packaged in MacPorts. It took > me a > while to get it done, but it's there and all components of the platform > should be > included. I'd welcome a bug report if there's anything wrong with it. > Mrrr, I thought there was a 6.8.4-based release (with the bizarre new build system). We're packaging 6.8.3 still. -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From pengyu.ut at gmail.com Fri Apr 24 00:23:15 2015 From: pengyu.ut at gmail.com (Peng Yu) Date: Thu, 23 Apr 2015 19:23:15 -0500 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: <1010645676.31627.1429826169594.JavaMail.zimbra@clang.name> References: <1010645676.31627.1429826169594.JavaMail.zimbra@clang.name> Message-ID: > Long story short: Try > $> cabal install --extra-include-dirs=/opt/local/include --extra-lib-dirs=/opt/local/lib I tried it but it still shows the error messages. ~$ cabal install --extra-include-dirs=/opt/local/include --extra-lib-dirs=/opt/local/lib cabal-install Resolving dependencies... Configuring cabal-install-1.22.3.0... Failed to install cabal-install-1.22.3.0 Build log ( /Users/py/.cabal/logs/cabal-install-1.22.3.0.log ): cabal: Error: some packages failed to install: cabal-install-1.22.3.0 failed during the configure step. The exception was: user error ('/usr/bin/ghc' exited with an error: Undefined symbols for architecture x86_64: "_iconv", referenced from: _hs_iconv in libHSbase-4.7.0.1.a(iconv.o) (maybe you meant: _hs_iconv, _base_GHCziIOziEncodingziIconv_iconvEncodingzuloc_info , _base_GHCziIOziEncodingziIconv_iconvEncoding8_info , _base_GHCziIOziEncodingziIconv_iconvEncoding9_closure , _hs_iconv_open , _base_GHCziIOziEncodingziIconv_iconvEncodingzuloc1_closure , _hs_iconv_close , _base_GHCziIOziEncodingziIconv_iconvEncoding6_info , _base_GHCziIOziEncodingziIconv_iconvEncoding4_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding6_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding10_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding7_info , _base_GHCziIOziEncodingziIconv_iconvEncoding2_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding2_info , _base_GHCziIOziEncodingziIconv_iconvEncodingzuloc_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding3_info , _base_GHCziIOziEncodingziIconv_iconvEncoding10_info , _base_GHCziIOziEncodingziIconv_iconvEncoding9_info , _base_GHCziIOziEncodingziIconv_iconvEncoding8_closure , _base_GHCziIOziEncodingziIconv_iconvEncoding7_closure , _base_GHCziIOziEncodingziIconv_iconvEncodingzuloc1_info , _base_GHCziIOziEncodingziIconv_iconvEncoding3_closure ) "_iconv_close", referenced from: _hs_iconv_close in libHSbase-4.7.0.1.a(iconv.o) (maybe you meant: _hs_iconv_close) "_iconv_open", referenced from: _hs_iconv_open in libHSbase-4.7.0.1.a(iconv.o) (maybe you meant: _hs_iconv_open) "_locale_charset", referenced from: _localeEncoding in libHSbase-4.7.0.1.a(PrelIOUtils.o) ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) ) -- Regards, Peng From pengyu.ut at gmail.com Fri Apr 24 00:46:45 2015 From: pengyu.ut at gmail.com (Peng Yu) Date: Thu, 23 Apr 2015 19:46:45 -0500 Subject: [Haskell-beginners] Error when running `cabal install cabal-install` In-Reply-To: <63666E90-A404-4ADC-87CF-7994ACE4B876@macports.org> References: <1010645676.31627.1429826169594.JavaMail.zimbra@clang.name> <63666E90-A404-4ADC-87CF-7994ACE4B876@macports.org> Message-ID: On Thu, Apr 23, 2015 at 7:39 PM, Ryan Schmidt wrote: > >> On Apr 23, 2015, at 7:23 PM, Peng Yu wrote: >> >>> Long story short: Try >>> $> cabal install --extra-include-dirs=/opt/local/include --extra-lib-dirs=/opt/local/lib >> >> I tried it but it still shows the error messages. >> >> ~$ cabal install --extra-include-dirs=/opt/local/include >> --extra-lib-dirs=/opt/local/lib cabal-install >> >> Resolving dependencies... >> Configuring cabal-install-1.22.3.0... >> Failed to install cabal-install-1.22.3.0 >> Build log ( /Users/py/.cabal/logs/cabal-install-1.22.3.0.log ): >> cabal: Error: some packages failed to install: >> cabal-install-1.22.3.0 failed during the configure step. The exception was: >> user error ('/usr/bin/ghc' exited with an error: > > You've installed ghc into /usr/bin? That's probably not a good idea. Prefix /usr is only for the OS vendor to install software into. This is what installed from the haskell installer. I agree this might not be a good idea. But I have no control over it. -- Regards, Peng From mrz.vtl at gmail.com Fri Apr 24 12:21:12 2015 From: mrz.vtl at gmail.com (Maurizio Vitale) Date: Fri, 24 Apr 2015 08:21:12 -0400 Subject: [Haskell-beginners] missing parallelism Message-ID: G'day, I have a test code that I compile with ghc -threaded -eventlog -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on a laptop with 4 physical cores. I would expect activities in two threads, but threadscope shows only one active thread. Can somebody explain me the program's behaviour? Thanks a lot Maurizio {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE TupleSections #-} import Control.Applicative import Control.Concurrent.Async (async, waitAny, Async) import Data.List (delete, sortBy) import Data.Ord (comparing) import System.CPUTime import System.Environment import GHC.Conc (numCapabilities) concurrentlyLimited :: Int -> [IO a] -> IO [a] concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] [] concurrentlyLimited' ? Int -- ^ number of concurrent evaluations ? [(Int, IO b)] -- ^ still to run (ordered by first element) ? [Async (Int,b)] -- ^ currently running ? [(Int,b)] -- ^ partial results (ordered by first element) ? IO [b] concurrentlyLimited' _ [] [] results = return . map snd $ sortBy (comparing fst) results concurrentlyLimited' 0 todo ongoing results = do (task, newResult) <- waitAny ongoing concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] ongoing results concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do t <- async $ (i,) <$> task concurrentlyLimited' (n-1) otherTasks (t:ongoing) results euler :: Int ? Int euler n = length (filter (relprime n) [1..n-1]) where relprime x y = gcd x y == 1 sumEuler :: Int ? Int sumEuler = sum . (map euler) . mkList where mkList n = [1..n-1] p ? IO Int p = return $ sumEuler 3000 numThreads ? [String] ? IO Int numThreads [] = return numCapabilities numThreads [cores] = return $ read cores main ? IO() main = do threads ? getArgs >>= numThreads putStrLn $ "Running up to " ++ show threads ++ " threads in parallel (on " ++ show numCapabilities ++ " cores)" startTime ? getCPUTime f ? concurrentlyLimited threads $ replicate 10 p endTime ? getCPUTime putStrLn $ foldr ((++) . show ) "" f putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - startTime) / 1000000000000?Double) From matthewmoppett at gmail.com Fri Apr 24 16:49:15 2015 From: matthewmoppett at gmail.com (Matthew Moppett) Date: Fri, 24 Apr 2015 23:49:15 +0700 Subject: [Haskell-beginners] Strange "Not in scope" error message Message-ID: I have a file with the following relevant lines: import qualified Control.Concurrent as C ... isCancelled = C.isEmptyMvar . stopConcurrentProcess Trying to compile this or run it in ghci yields a puzzling error message: Not in scope: `C.isEmptyMvar' Perhaps you meant one of these: `C.isEmptyMVar' (imported from Control.Concurrent), `C.isEmptyChan' (imported from Control.Concurrent) Any idea what could be going wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ahammel87 at gmail.com Fri Apr 24 16:51:30 2015 From: ahammel87 at gmail.com (Alex Hammel) Date: Fri, 24 Apr 2015 16:51:30 +0000 Subject: [Haskell-beginners] Strange "Not in scope" error message In-Reply-To: References: Message-ID: You forgot to capitalize the 'V' in 'isEmptyMVar' :) On Fri, 24 Apr 2015 at 09:49 Matthew Moppett wrote: > I have a file with the following relevant lines: > > import qualified Control.Concurrent as C > > ... > > isCancelled = C.isEmptyMvar . stopConcurrentProcess > > Trying to compile this or run it in ghci yields a puzzling error message: > > Not in scope: `C.isEmptyMvar' > Perhaps you meant one of these: > `C.isEmptyMVar' (imported from Control.Concurrent), > `C.isEmptyChan' (imported from Control.Concurrent) > > Any idea what could be going wrong? > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fa-ml at ariis.it Fri Apr 24 17:14:26 2015 From: fa-ml at ariis.it (Francesco Ariis) Date: Fri, 24 Apr 2015 19:14:26 +0200 Subject: [Haskell-beginners] Strange "Not in scope" error message In-Reply-To: References: Message-ID: <20150424171426.GA4096@x60s.casa> On Fri, Apr 24, 2015 at 11:49:15PM +0700, Matthew Moppett wrote: > Perhaps you meant one of these: > `C.isEmptyMVar' (imported from Control.Concurrent), Haskell is case sensitive, isEmptyMVar is different from isEmptyMvar (lowercase v) From haskell at erebe.eu Fri Apr 24 17:44:22 2015 From: haskell at erebe.eu (haskell at erebe.eu) Date: Fri, 24 Apr 2015 19:44:22 +0200 Subject: [Haskell-beginners] missing parallelism In-Reply-To: References: Message-ID: <553A80F6.1020200@erebe.eu> On 24/04/2015 14:21, Maurizio Vitale wrote: > G'day, > I have a test code that I compile with ghc -threaded -eventlog > -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on > a laptop with 4 physical cores. I would expect activities in two > threads, but threadscope shows only one active thread. > Can somebody explain me the program's behaviour? > > Thanks a lot > > Maurizio > > {-# LANGUAGE UnicodeSyntax #-} > {-# LANGUAGE TupleSections #-} > > import Control.Applicative > import Control.Concurrent.Async (async, waitAny, Async) > import Data.List (delete, sortBy) > import Data.Ord (comparing) > import System.CPUTime > import System.Environment > import GHC.Conc (numCapabilities) > > concurrentlyLimited :: Int -> [IO a] -> IO [a] > concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] [] > > concurrentlyLimited' ? Int -- ^ number of concurrent evaluations > ? [(Int, IO b)] -- ^ still to run (ordered by > first element) > ? [Async (Int,b)] -- ^ currently running > ? [(Int,b)] -- ^ partial results (ordered > by first element) > ? IO [b] > concurrentlyLimited' _ [] [] results = return . map snd $ sortBy > (comparing fst) results > concurrentlyLimited' 0 todo ongoing results = do > (task, newResult) <- waitAny ongoing > concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) > > concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] > ongoing results > concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do > t <- async $ (i,) <$> task > concurrentlyLimited' (n-1) otherTasks (t:ongoing) results > > euler :: Int ? Int > euler n = length (filter (relprime n) [1..n-1]) > where > relprime x y = gcd x y == 1 > > sumEuler :: Int ? Int > sumEuler = sum . (map euler) . mkList > where > mkList n = [1..n-1] > > p ? IO Int > p = return $ sumEuler 3000 > > numThreads ? [String] ? IO Int > numThreads [] = return numCapabilities > numThreads [cores] = return $ read cores > > main ? IO() > main = do > threads ? getArgs >>= numThreads > putStrLn $ "Running up to " ++ show threads ++ " threads in parallel > (on " ++ show numCapabilities ++ " cores)" > startTime ? getCPUTime > f ? concurrentlyLimited threads $ replicate 10 p > endTime ? getCPUTime > putStrLn $ foldr ((++) . show ) "" f > putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - > startTime) / 1000000000000?Double) > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners Hello, I don't have an Haskell environnement at hand, but my advice is to search for when your Async/eulerSum calls are evaluated. For example try to remove this line -- putStrLn $ foldr ((++) . show ) "" f Does your program still compute something ? If no that's because your sum is evaluated due to the show and not due to your async. t <- async $ (i,) <$> task Your async will try to compute (i,eulerSum) but you never force the computation of the eulersum inside the async, so the async take no time and return quickly. Instead of this type [Async (Int, b)] you should aim for this one [(Int, Async b)] Let me know if that helps you. Regards, Romain From mrz.vtl at gmail.com Fri Apr 24 23:06:08 2015 From: mrz.vtl at gmail.com (Maurizio Vitale) Date: Fri, 24 Apr 2015 19:06:08 -0400 Subject: [Haskell-beginners] missing parallelism In-Reply-To: <553A80F6.1020200@erebe.eu> References: <553A80F6.1020200@erebe.eu> Message-ID: You're right, without the show, no work is done. But I'm puzzled. I thought waitAny would have caused one task to be executed. If that doesn't wait for the async to compute a value (and not some thunk) I don't see how to use asyncs, so I'm obviously missing something. How can I force deeper evaluation? [in the end p would be a full parser, so whatever it is needed to cause the parsing needs to be done outside of it] On Fri, Apr 24, 2015 at 10:44 AM, wrote: > On 24/04/2015 14:21, Maurizio Vitale wrote: >> >> G'day, >> I have a test code that I compile with ghc -threaded -eventlog >> -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on >> a laptop with 4 physical cores. I would expect activities in two >> threads, but threadscope shows only one active thread. >> Can somebody explain me the program's behaviour? >> >> Thanks a lot >> >> Maurizio >> >> {-# LANGUAGE UnicodeSyntax #-} >> {-# LANGUAGE TupleSections #-} >> >> import Control.Applicative >> import Control.Concurrent.Async (async, waitAny, Async) >> import Data.List (delete, sortBy) >> import Data.Ord (comparing) >> import System.CPUTime >> import System.Environment >> import GHC.Conc (numCapabilities) >> >> concurrentlyLimited :: Int -> [IO a] -> IO [a] >> concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] >> [] >> >> concurrentlyLimited' ? Int -- ^ number of concurrent >> evaluations >> ? [(Int, IO b)] -- ^ still to run (ordered by >> first element) >> ? [Async (Int,b)] -- ^ currently running >> ? [(Int,b)] -- ^ partial results (ordered >> by first element) >> ? IO [b] >> concurrentlyLimited' _ [] [] results = return . map snd $ sortBy >> (comparing fst) results >> concurrentlyLimited' 0 todo ongoing results = do >> (task, newResult) <- waitAny ongoing >> concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) >> >> concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] >> ongoing results >> concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do >> t <- async $ (i,) <$> task >> concurrentlyLimited' (n-1) otherTasks (t:ongoing) results >> >> euler :: Int ? Int >> euler n = length (filter (relprime n) [1..n-1]) >> where >> relprime x y = gcd x y == 1 >> >> sumEuler :: Int ? Int >> sumEuler = sum . (map euler) . mkList >> where >> mkList n = [1..n-1] >> >> p ? IO Int >> p = return $ sumEuler 3000 >> >> numThreads ? [String] ? IO Int >> numThreads [] = return numCapabilities >> numThreads [cores] = return $ read cores >> >> main ? IO() >> main = do >> threads ? getArgs >>= numThreads >> putStrLn $ "Running up to " ++ show threads ++ " threads in parallel >> (on " ++ show numCapabilities ++ " cores)" >> startTime ? getCPUTime >> f ? concurrentlyLimited threads $ replicate 10 p >> endTime ? getCPUTime >> putStrLn $ foldr ((++) . show ) "" f >> putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - >> startTime) / 1000000000000?Double) >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > Hello, > > I don't have an Haskell environnement at hand, but my advice is to search > for when your Async/eulerSum calls are evaluated. > For example try to remove this line -- putStrLn $ foldr ((++) . show ) "" > f > Does your program still compute something ? If no that's because your sum is > evaluated due to the show and not due to your async. > > t <- async $ (i,) <$> task > > Your async will try to compute (i,eulerSum) but you never force the > computation of the eulersum inside the async, so the async take no time and > return quickly. > Instead of this type [Async (Int, b)] you should aim for this one [(Int, > Async b)] > > Let me know if that helps you. > > Regards, > Romain > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners On Fri, Apr 24, 2015 at 1:44 PM, wrote: > On 24/04/2015 14:21, Maurizio Vitale wrote: >> >> G'day, >> I have a test code that I compile with ghc -threaded -eventlog >> -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on >> a laptop with 4 physical cores. I would expect activities in two >> threads, but threadscope shows only one active thread. >> Can somebody explain me the program's behaviour? >> >> Thanks a lot >> >> Maurizio >> >> {-# LANGUAGE UnicodeSyntax #-} >> {-# LANGUAGE TupleSections #-} >> >> import Control.Applicative >> import Control.Concurrent.Async (async, waitAny, Async) >> import Data.List (delete, sortBy) >> import Data.Ord (comparing) >> import System.CPUTime >> import System.Environment >> import GHC.Conc (numCapabilities) >> >> concurrentlyLimited :: Int -> [IO a] -> IO [a] >> concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] >> [] >> >> concurrentlyLimited' ? Int -- ^ number of concurrent >> evaluations >> ? [(Int, IO b)] -- ^ still to run (ordered by >> first element) >> ? [Async (Int,b)] -- ^ currently running >> ? [(Int,b)] -- ^ partial results (ordered >> by first element) >> ? IO [b] >> concurrentlyLimited' _ [] [] results = return . map snd $ sortBy >> (comparing fst) results >> concurrentlyLimited' 0 todo ongoing results = do >> (task, newResult) <- waitAny ongoing >> concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) >> >> concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] >> ongoing results >> concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do >> t <- async $ (i,) <$> task >> concurrentlyLimited' (n-1) otherTasks (t:ongoing) results >> >> euler :: Int ? Int >> euler n = length (filter (relprime n) [1..n-1]) >> where >> relprime x y = gcd x y == 1 >> >> sumEuler :: Int ? Int >> sumEuler = sum . (map euler) . mkList >> where >> mkList n = [1..n-1] >> >> p ? IO Int >> p = return $ sumEuler 3000 >> >> numThreads ? [String] ? IO Int >> numThreads [] = return numCapabilities >> numThreads [cores] = return $ read cores >> >> main ? IO() >> main = do >> threads ? getArgs >>= numThreads >> putStrLn $ "Running up to " ++ show threads ++ " threads in parallel >> (on " ++ show numCapabilities ++ " cores)" >> startTime ? getCPUTime >> f ? concurrentlyLimited threads $ replicate 10 p >> endTime ? getCPUTime >> putStrLn $ foldr ((++) . show ) "" f >> putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - >> startTime) / 1000000000000?Double) >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > Hello, > > I don't have an Haskell environnement at hand, but my advice is to search > for when your Async/eulerSum calls are evaluated. > For example try to remove this line -- putStrLn $ foldr ((++) . show ) "" > f > Does your program still compute something ? If no that's because your sum is > evaluated due to the show and not due to your async. > > t <- async $ (i,) <$> task > > Your async will try to compute (i,eulerSum) but you never force the > computation of the eulersum inside the async, so the async take no time and > return quickly. > Instead of this type [Async (Int, b)] you should aim for this one [(Int, > Async b)] > > Let me know if that helps you. > > Regards, > Romain > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From matthewmoppett at gmail.com Sat Apr 25 01:27:22 2015 From: matthewmoppett at gmail.com (Matthew Moppett) Date: Sat, 25 Apr 2015 08:27:22 +0700 Subject: [Haskell-beginners] Strange "Not in scope" error message In-Reply-To: <20150424171426.GA4096@x60s.casa> References: <20150424171426.GA4096@x60s.casa> Message-ID: So I did. That's kind of embarrassing -- I could swear I stared at that error message for ages trying to work out if there were any typos like that and never saw it. Thanks for pointing it out. On Sat, Apr 25, 2015 at 12:14 AM, Francesco Ariis wrote: > On Fri, Apr 24, 2015 at 11:49:15PM +0700, Matthew Moppett wrote: > > Perhaps you meant one of these: > > `C.isEmptyMVar' (imported from Control.Concurrent), > > Haskell is case sensitive, isEmptyMVar is different from isEmptyMvar > (lowercase v) > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrz.vtl at gmail.com Sat Apr 25 01:40:55 2015 From: mrz.vtl at gmail.com (Maurizio Vitale) Date: Fri, 24 Apr 2015 21:40:55 -0400 Subject: [Haskell-beginners] missing parallelism In-Reply-To: References: <553A80F6.1020200@erebe.eu> Message-ID: Not even with this simplified version, I can get two async running on separate threads. I must be missing something really basic: {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE TupleSections #-} import Control.Concurrent.Async (async, waitBoth) sumEuler :: Int ? Int sumEuler = sum . map euler . mkList where mkList n = [1..n-1] euler n = length (filter (relprime n) [1..n-1]) where relprime x y = gcd x y == 1 p ? IO Int p = return $ sumEuler 5000 main ? IO() main = do a ? async p b ? async p (av, bv) ? waitBoth a b print (av,bv) On Fri, Apr 24, 2015 at 7:06 PM, Maurizio Vitale wrote: > You're right, without the show, no work is done. > But I'm puzzled. I thought waitAny would have caused one task to be executed. > If that doesn't wait for the async to compute a value (and not some > thunk) I don't see how to use asyncs, so I'm obviously missing > something. > How can I force deeper evaluation? > [in the end p would be a full parser, so whatever it is needed to > cause the parsing needs to be done outside of it] > > On Fri, Apr 24, 2015 at 10:44 AM, wrote: >> On 24/04/2015 14:21, Maurizio Vitale wrote: >>> >>> G'day, >>> I have a test code that I compile with ghc -threaded -eventlog >>> -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on >>> a laptop with 4 physical cores. I would expect activities in two >>> threads, but threadscope shows only one active thread. >>> Can somebody explain me the program's behaviour? >>> >>> Thanks a lot >>> >>> Maurizio >>> >>> {-# LANGUAGE UnicodeSyntax #-} >>> {-# LANGUAGE TupleSections #-} >>> >>> import Control.Applicative >>> import Control.Concurrent.Async (async, waitAny, Async) >>> import Data.List (delete, sortBy) >>> import Data.Ord (comparing) >>> import System.CPUTime >>> import System.Environment >>> import GHC.Conc (numCapabilities) >>> >>> concurrentlyLimited :: Int -> [IO a] -> IO [a] >>> concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] >>> [] >>> >>> concurrentlyLimited' ? Int -- ^ number of concurrent >>> evaluations >>> ? [(Int, IO b)] -- ^ still to run (ordered by >>> first element) >>> ? [Async (Int,b)] -- ^ currently running >>> ? [(Int,b)] -- ^ partial results (ordered >>> by first element) >>> ? IO [b] >>> concurrentlyLimited' _ [] [] results = return . map snd $ sortBy >>> (comparing fst) results >>> concurrentlyLimited' 0 todo ongoing results = do >>> (task, newResult) <- waitAny ongoing >>> concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) >>> >>> concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] >>> ongoing results >>> concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do >>> t <- async $ (i,) <$> task >>> concurrentlyLimited' (n-1) otherTasks (t:ongoing) results >>> >>> euler :: Int ? Int >>> euler n = length (filter (relprime n) [1..n-1]) >>> where >>> relprime x y = gcd x y == 1 >>> >>> sumEuler :: Int ? Int >>> sumEuler = sum . (map euler) . mkList >>> where >>> mkList n = [1..n-1] >>> >>> p ? IO Int >>> p = return $ sumEuler 3000 >>> >>> numThreads ? [String] ? IO Int >>> numThreads [] = return numCapabilities >>> numThreads [cores] = return $ read cores >>> >>> main ? IO() >>> main = do >>> threads ? getArgs >>= numThreads >>> putStrLn $ "Running up to " ++ show threads ++ " threads in parallel >>> (on " ++ show numCapabilities ++ " cores)" >>> startTime ? getCPUTime >>> f ? concurrentlyLimited threads $ replicate 10 p >>> endTime ? getCPUTime >>> putStrLn $ foldr ((++) . show ) "" f >>> putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - >>> startTime) / 1000000000000?Double) >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> >> Hello, >> >> I don't have an Haskell environnement at hand, but my advice is to search >> for when your Async/eulerSum calls are evaluated. >> For example try to remove this line -- putStrLn $ foldr ((++) . show ) "" >> f >> Does your program still compute something ? If no that's because your sum is >> evaluated due to the show and not due to your async. >> >> t <- async $ (i,) <$> task >> >> Your async will try to compute (i,eulerSum) but you never force the >> computation of the eulersum inside the async, so the async take no time and >> return quickly. >> Instead of this type [Async (Int, b)] you should aim for this one [(Int, >> Async b)] >> >> Let me know if that helps you. >> >> Regards, >> Romain >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > On Fri, Apr 24, 2015 at 1:44 PM, wrote: >> On 24/04/2015 14:21, Maurizio Vitale wrote: >>> >>> G'day, >>> I have a test code that I compile with ghc -threaded -eventlog >>> -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on >>> a laptop with 4 physical cores. I would expect activities in two >>> threads, but threadscope shows only one active thread. >>> Can somebody explain me the program's behaviour? >>> >>> Thanks a lot >>> >>> Maurizio >>> >>> {-# LANGUAGE UnicodeSyntax #-} >>> {-# LANGUAGE TupleSections #-} >>> >>> import Control.Applicative >>> import Control.Concurrent.Async (async, waitAny, Async) >>> import Data.List (delete, sortBy) >>> import Data.Ord (comparing) >>> import System.CPUTime >>> import System.Environment >>> import GHC.Conc (numCapabilities) >>> >>> concurrentlyLimited :: Int -> [IO a] -> IO [a] >>> concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] >>> [] >>> >>> concurrentlyLimited' ? Int -- ^ number of concurrent >>> evaluations >>> ? [(Int, IO b)] -- ^ still to run (ordered by >>> first element) >>> ? [Async (Int,b)] -- ^ currently running >>> ? [(Int,b)] -- ^ partial results (ordered >>> by first element) >>> ? IO [b] >>> concurrentlyLimited' _ [] [] results = return . map snd $ sortBy >>> (comparing fst) results >>> concurrentlyLimited' 0 todo ongoing results = do >>> (task, newResult) <- waitAny ongoing >>> concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) >>> >>> concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] >>> ongoing results >>> concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do >>> t <- async $ (i,) <$> task >>> concurrentlyLimited' (n-1) otherTasks (t:ongoing) results >>> >>> euler :: Int ? Int >>> euler n = length (filter (relprime n) [1..n-1]) >>> where >>> relprime x y = gcd x y == 1 >>> >>> sumEuler :: Int ? Int >>> sumEuler = sum . (map euler) . mkList >>> where >>> mkList n = [1..n-1] >>> >>> p ? IO Int >>> p = return $ sumEuler 3000 >>> >>> numThreads ? [String] ? IO Int >>> numThreads [] = return numCapabilities >>> numThreads [cores] = return $ read cores >>> >>> main ? IO() >>> main = do >>> threads ? getArgs >>= numThreads >>> putStrLn $ "Running up to " ++ show threads ++ " threads in parallel >>> (on " ++ show numCapabilities ++ " cores)" >>> startTime ? getCPUTime >>> f ? concurrentlyLimited threads $ replicate 10 p >>> endTime ? getCPUTime >>> putStrLn $ foldr ((++) . show ) "" f >>> putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - >>> startTime) / 1000000000000?Double) >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> >> Hello, >> >> I don't have an Haskell environnement at hand, but my advice is to search >> for when your Async/eulerSum calls are evaluated. >> For example try to remove this line -- putStrLn $ foldr ((++) . show ) "" >> f >> Does your program still compute something ? If no that's because your sum is >> evaluated due to the show and not due to your async. >> >> t <- async $ (i,) <$> task >> >> Your async will try to compute (i,eulerSum) but you never force the >> computation of the eulersum inside the async, so the async take no time and >> return quickly. >> Instead of this type [Async (Int, b)] you should aim for this one [(Int, >> Async b)] >> >> Let me know if that helps you. >> >> Regards, >> Romain >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From grzegorzmilka at gmail.com Sat Apr 25 08:25:29 2015 From: grzegorzmilka at gmail.com (Grzegorz Milka) Date: Sat, 25 Apr 2015 10:25:29 +0200 Subject: [Haskell-beginners] missing parallelism In-Reply-To: References: Message-ID: <553B4F79.5000002@gmail.com> As far as I can tell there's nothing wrong with your code. My hypothesis is that Haskell optimizes call to sumEuler 5000 by calling it only once in one thread. Here's why I think so: The program I used for debugging this is: import Control.Concurrent.Async (async, wait) import System.IO.Unsafe (unsafePerformIO) sumEuler :: Int -> Int sumEuler = sum . map euler . mkList where mkList n = seq (unsafePerformIO (putStrLn "Calculating")) [1..n-1] euler n = length (filter (relprime n) [1..n-1]) where relprime x y = gcd x y == 1 p :: Int -> IO Int p b = return $! sumEuler b p5000 :: IO Int p5000 = return $ sumEuler 5000 main :: IO () main = do a <- async $ p5000 b <- async $ p5000 av <- wait a bv <- wait b print (av,bv) The two main modification are adding a debugging message "Calculating" when a list [1..(n-1)] is evaluated. The second one is making p into a function. Notice that it uses strict application ($! - check how it works with simple $). I will use that function in further examples. Running this program with "time ./Test 2 +RTS -ls -N2" gives me: Calculating (7598457,7598457) real 0m3.752s user 0m3.833s sys 0m0.211s Just to be sure I have almost the same time when doing only one computation with: main :: IO () main = do a <- async $ p5000 av <- wait a print av So it seems like the value returned by p5000 is computed only once. GHC might be noticing that p5000 will always return the same value and might try cache it or memoize it. If this hypothesis is right then calling sumEuler with two different values should run in two different threads. And indeed it is so: main :: IO () main = do a <- async $ p 5000 b <- async $ p 4999 av <- wait a bv <- wait b print (av,bv) Gives: Calculating Calculating (7598457,7593459) real 0m3.758s user 0m7.414s sys 0m0.064s So it runs in two threads just as expected. The strict application ($!) here is important. Otherwise it seems that the async thread returns a thunk and the evaluation happens in print (av, bv) which is evaluated in a single thread. Also the fact that p5000 is a top level binding is important. When I do: main :: IO () main = do a <- async $ p 5000 b <- async $ p 5000 av <- wait a bv <- wait b print (av,bv) I get no optimization (GHC 7.6.3). Best, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: OpenPGP digital signature URL: From haskell at erebe.eu Sat Apr 25 10:25:25 2015 From: haskell at erebe.eu (haskell at erebe.eu) Date: Sat, 25 Apr 2015 12:25:25 +0200 Subject: [Haskell-beginners] missing parallelism In-Reply-To: References: <553A80F6.1020200@erebe.eu> Message-ID: <553B6B95.2050705@erebe.eu> Again, does you program compute something if you remove the print ? no ? So you have a stricness/laziness problem. Let's see together what does mean p :: IO Int By its signature *p* assure you that *when evaluate* it will return you an *IO Int*. By Its signature *IO Int* assure you that*when evaluated* it will return you an *Int*. By Its signature *Int* assure you that *when evaluated* it will return you an *Int* but this time, a *strict one* as there is *nothing left to evaluate* ok so now, what does mean *async p* ? Async will *force the evaluation* of the *IO* but that is all. so : async p = async $ return $ sumEuler 5000 :: IO Int so : a <- async p = a <- async $ return $ sumEuler 5000 :: IO Int -> Int so : a = sumEuler 5000 :: Int So *a* promise you an Int (but a lazy one) so where has it been evaluated ? Nowhere, the evaluation of *a *never happens anywhere. So you are missing a final step, the last evaluation of *a* (which does happen after, due to the print) How to solve that ? Force the evaluation of sumEuler 5000 inside the IO monad, so it will be evaluated at the same time that the async will evaluate the IO. (In order to evaluate something you have to force a data depedency) p :: IO int p = return $! sumEuler 5000 or p :: IO int p = let x = sumEuler in x `seq` return x This should solve your problem of everything running on a single thread/core, because now you force the evaluation of sumEuler inside p and not inside the print. Now, be aware that as sumEuler is pure and that 5000 is a static value (also pure), sumEuler 5000 needs to be computed only once. The program is free to optimize away further calls to sumEuler 5000 by caching the value. But at least you shoud see this evaluation happening on multiples cores. Regards, Romain On 25/04/2015 03:40, Maurizio Vitale wrote: > Not even with this simplified version, I can get two async running on > separate threads. > I must be missing something really basic: > > {-# LANGUAGE UnicodeSyntax #-} > {-# LANGUAGE TupleSections #-} > > import Control.Concurrent.Async (async, waitBoth) > > sumEuler :: Int ? Int > sumEuler = sum . map euler . mkList > where > mkList n = [1..n-1] > euler n = length (filter (relprime n) [1..n-1]) > where > relprime x y = gcd x y == 1 > > p ? IO Int > p = return $ sumEuler 5000 > > main ? IO() > main = do > a ? async p > b ? async p > (av, bv) ? waitBoth a b > print (av,bv) > > On Fri, Apr 24, 2015 at 7:06 PM, Maurizio Vitale wrote: >> You're right, without the show, no work is done. >> But I'm puzzled. I thought waitAny would have caused one task to be executed. >> If that doesn't wait for the async to compute a value (and not some >> thunk) I don't see how to use asyncs, so I'm obviously missing >> something. >> How can I force deeper evaluation? >> [in the end p would be a full parser, so whatever it is needed to >> cause the parsing needs to be done outside of it] >> >> On Fri, Apr 24, 2015 at 10:44 AM, wrote: >>> On 24/04/2015 14:21, Maurizio Vitale wrote: >>>> G'day, >>>> I have a test code that I compile with ghc -threaded -eventlog >>>> -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on >>>> a laptop with 4 physical cores. I would expect activities in two >>>> threads, but threadscope shows only one active thread. >>>> Can somebody explain me the program's behaviour? >>>> >>>> Thanks a lot >>>> >>>> Maurizio >>>> >>>> {-# LANGUAGE UnicodeSyntax #-} >>>> {-# LANGUAGE TupleSections #-} >>>> >>>> import Control.Applicative >>>> import Control.Concurrent.Async (async, waitAny, Async) >>>> import Data.List (delete, sortBy) >>>> import Data.Ord (comparing) >>>> import System.CPUTime >>>> import System.Environment >>>> import GHC.Conc (numCapabilities) >>>> >>>> concurrentlyLimited :: Int -> [IO a] -> IO [a] >>>> concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] >>>> [] >>>> >>>> concurrentlyLimited' ? Int -- ^ number of concurrent >>>> evaluations >>>> ? [(Int, IO b)] -- ^ still to run (ordered by >>>> first element) >>>> ? [Async (Int,b)] -- ^ currently running >>>> ? [(Int,b)] -- ^ partial results (ordered >>>> by first element) >>>> ? IO [b] >>>> concurrentlyLimited' _ [] [] results = return . map snd $ sortBy >>>> (comparing fst) results >>>> concurrentlyLimited' 0 todo ongoing results = do >>>> (task, newResult) <- waitAny ongoing >>>> concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) >>>> >>>> concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] >>>> ongoing results >>>> concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do >>>> t <- async $ (i,) <$> task >>>> concurrentlyLimited' (n-1) otherTasks (t:ongoing) results >>>> >>>> euler :: Int ? Int >>>> euler n = length (filter (relprime n) [1..n-1]) >>>> where >>>> relprime x y = gcd x y == 1 >>>> >>>> sumEuler :: Int ? Int >>>> sumEuler = sum . (map euler) . mkList >>>> where >>>> mkList n = [1..n-1] >>>> >>>> p ? IO Int >>>> p = return $ sumEuler 3000 >>>> >>>> numThreads ? [String] ? IO Int >>>> numThreads [] = return numCapabilities >>>> numThreads [cores] = return $ read cores >>>> >>>> main ? IO() >>>> main = do >>>> threads ? getArgs >>= numThreads >>>> putStrLn $ "Running up to " ++ show threads ++ " threads in parallel >>>> (on " ++ show numCapabilities ++ " cores)" >>>> startTime ? getCPUTime >>>> f ? concurrentlyLimited threads $ replicate 10 p >>>> endTime ? getCPUTime >>>> putStrLn $ foldr ((++) . show ) "" f >>>> putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - >>>> startTime) / 1000000000000?Double) >>>> _______________________________________________ >>>> Beginners mailing list >>>> Beginners at haskell.org >>>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >>> Hello, >>> >>> I don't have an Haskell environnement at hand, but my advice is to search >>> for when your Async/eulerSum calls are evaluated. >>> For example try to remove this line -- putStrLn $ foldr ((++) . show ) "" >>> f >>> Does your program still compute something ? If no that's because your sum is >>> evaluated due to the show and not due to your async. >>> >>> t <- async $ (i,) <$> task >>> >>> Your async will try to compute (i,eulerSum) but you never force the >>> computation of the eulersum inside the async, so the async take no time and >>> return quickly. >>> Instead of this type [Async (Int, b)] you should aim for this one [(Int, >>> Async b)] >>> >>> Let me know if that helps you. >>> >>> Regards, >>> Romain >>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> On Fri, Apr 24, 2015 at 1:44 PM, wrote: >>> On 24/04/2015 14:21, Maurizio Vitale wrote: >>>> G'day, >>>> I have a test code that I compile with ghc -threaded -eventlog >>>> -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on >>>> a laptop with 4 physical cores. I would expect activities in two >>>> threads, but threadscope shows only one active thread. >>>> Can somebody explain me the program's behaviour? >>>> >>>> Thanks a lot >>>> >>>> Maurizio >>>> >>>> {-# LANGUAGE UnicodeSyntax #-} >>>> {-# LANGUAGE TupleSections #-} >>>> >>>> import Control.Applicative >>>> import Control.Concurrent.Async (async, waitAny, Async) >>>> import Data.List (delete, sortBy) >>>> import Data.Ord (comparing) >>>> import System.CPUTime >>>> import System.Environment >>>> import GHC.Conc (numCapabilities) >>>> >>>> concurrentlyLimited :: Int -> [IO a] -> IO [a] >>>> concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] >>>> [] >>>> >>>> concurrentlyLimited' ? Int -- ^ number of concurrent >>>> evaluations >>>> ? [(Int, IO b)] -- ^ still to run (ordered by >>>> first element) >>>> ? [Async (Int,b)] -- ^ currently running >>>> ? [(Int,b)] -- ^ partial results (ordered >>>> by first element) >>>> ? IO [b] >>>> concurrentlyLimited' _ [] [] results = return . map snd $ sortBy >>>> (comparing fst) results >>>> concurrentlyLimited' 0 todo ongoing results = do >>>> (task, newResult) <- waitAny ongoing >>>> concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) >>>> >>>> concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] >>>> ongoing results >>>> concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do >>>> t <- async $ (i,) <$> task >>>> concurrentlyLimited' (n-1) otherTasks (t:ongoing) results >>>> >>>> euler :: Int ? Int >>>> euler n = length (filter (relprime n) [1..n-1]) >>>> where >>>> relprime x y = gcd x y == 1 >>>> >>>> sumEuler :: Int ? Int >>>> sumEuler = sum . (map euler) . mkList >>>> where >>>> mkList n = [1..n-1] >>>> >>>> p ? IO Int >>>> p = return $ sumEuler 3000 >>>> >>>> numThreads ? [String] ? IO Int >>>> numThreads [] = return numCapabilities >>>> numThreads [cores] = return $ read cores >>>> >>>> main ? IO() >>>> main = do >>>> threads ? getArgs >>= numThreads >>>> putStrLn $ "Running up to " ++ show threads ++ " threads in parallel >>>> (on " ++ show numCapabilities ++ " cores)" >>>> startTime ? getCPUTime >>>> f ? concurrentlyLimited threads $ replicate 10 p >>>> endTime ? getCPUTime >>>> putStrLn $ foldr ((++) . show ) "" f >>>> putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - >>>> startTime) / 1000000000000?Double) >>>> _______________________________________________ >>>> Beginners mailing list >>>> Beginners at haskell.org >>>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >>> Hello, >>> >>> I don't have an Haskell environnement at hand, but my advice is to search >>> for when your Async/eulerSum calls are evaluated. >>> For example try to remove this line -- putStrLn $ foldr ((++) . show ) "" >>> f >>> Does your program still compute something ? If no that's because your sum is >>> evaluated due to the show and not due to your async. >>> >>> t <- async $ (i,) <$> task >>> >>> Your async will try to compute (i,eulerSum) but you never force the >>> computation of the eulersum inside the async, so the async take no time and >>> return quickly. >>> Instead of this type [Async (Int, b)] you should aim for this one [(Int, >>> Async b)] >>> >>> Let me know if that helps you. >>> >>> Regards, >>> Romain >>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrz.vtl at gmail.com Sat Apr 25 14:45:44 2015 From: mrz.vtl at gmail.com (Maurizio Vitale) Date: Sat, 25 Apr 2015 10:45:44 -0400 Subject: [Haskell-beginners] missing parallelism In-Reply-To: <553B6B95.2050705@erebe.eu> References: <553A80F6.1020200@erebe.eu> <553B6B95.2050705@erebe.eu> Message-ID: Thanks to all. A combination of $! and evaluating sumEuler for different arguments in each async finally gave me the two threads. I'm still a bit worried about analyzing this type of issues in a larger program, but I love the fact that sumEuler 5000 was evaluated only once. On Sat, Apr 25, 2015 at 6:25 AM, wrote: > Again, does you program compute something if you remove the print ? no ? So > you have a stricness/laziness problem. > > Let's see together what does mean p :: IO Int > By its signature p assure you that when evaluate it will return you an IO > Int. > By Its signature IO Int assure you that when evaluated it will return you an > Int. > By Its signature Int assure you that when evaluated it will return you an > Int but this time, a strict one as there is nothing left to evaluate > > ok so now, what does mean async p ? Async will force the evaluation of the > IO but that is all. > so : async p = async $ return $ sumEuler 5000 :: IO Int > so : a <- async p = a <- async $ return $ sumEuler 5000 :: IO Int -> Int > so : a = sumEuler 5000 :: Int > > So a promise you an Int (but a lazy one) so where has it been evaluated ? > Nowhere, the evaluation of a never happens anywhere. So you are missing a > final step, the last evaluation of a (which does happen after, due to the > print) > > How to solve that ? Force the evaluation of sumEuler 5000 inside the IO > monad, so it will be evaluated at the same time that the async will evaluate > the IO. (In order to evaluate something you have to force a data depedency) > > p :: IO int > p = return $! sumEuler 5000 > > or > p :: IO int > p = let x = sumEuler in x `seq` return x > > This should solve your problem of everything running on a single > thread/core, because now you force the evaluation of sumEuler inside p and > not inside the print. > > Now, be aware that as sumEuler is pure and that 5000 is a static value (also > pure), sumEuler 5000 needs to be computed only once. The program is free to > optimize away further calls to sumEuler 5000 by caching the value. > But at least you shoud see this evaluation happening on multiples cores. > > > Regards, > Romain > > > On 25/04/2015 03:40, Maurizio Vitale wrote: > > Not even with this simplified version, I can get two async running on > separate threads. > I must be missing something really basic: > > {-# LANGUAGE UnicodeSyntax #-} > {-# LANGUAGE TupleSections #-} > > import Control.Concurrent.Async (async, waitBoth) > > sumEuler :: Int ? Int > sumEuler = sum . map euler . mkList > where > mkList n = [1..n-1] > euler n = length (filter (relprime n) [1..n-1]) > where > relprime x y = gcd x y == 1 > > p ? IO Int > p = return $ sumEuler 5000 > > main ? IO() > main = do > a ? async p > b ? async p > (av, bv) ? waitBoth a b > print (av,bv) > > On Fri, Apr 24, 2015 at 7:06 PM, Maurizio Vitale wrote: > > You're right, without the show, no work is done. > But I'm puzzled. I thought waitAny would have caused one task to be > executed. > If that doesn't wait for the async to compute a value (and not some > thunk) I don't see how to use asyncs, so I'm obviously missing > something. > How can I force deeper evaluation? > [in the end p would be a full parser, so whatever it is needed to > cause the parsing needs to be done outside of it] > > On Fri, Apr 24, 2015 at 10:44 AM, wrote: > > On 24/04/2015 14:21, Maurizio Vitale wrote: > > G'day, > I have a test code that I compile with ghc -threaded -eventlog > -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on > a laptop with 4 physical cores. I would expect activities in two > threads, but threadscope shows only one active thread. > Can somebody explain me the program's behaviour? > > Thanks a lot > > Maurizio > > {-# LANGUAGE UnicodeSyntax #-} > {-# LANGUAGE TupleSections #-} > > import Control.Applicative > import Control.Concurrent.Async (async, waitAny, Async) > import Data.List (delete, sortBy) > import Data.Ord (comparing) > import System.CPUTime > import System.Environment > import GHC.Conc (numCapabilities) > > concurrentlyLimited :: Int -> [IO a] -> IO [a] > concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] > [] > > concurrentlyLimited' ? Int -- ^ number of concurrent > evaluations > ? [(Int, IO b)] -- ^ still to run (ordered by > first element) > ? [Async (Int,b)] -- ^ currently running > ? [(Int,b)] -- ^ partial results (ordered > by first element) > ? IO [b] > concurrentlyLimited' _ [] [] results = return . map snd $ sortBy > (comparing fst) results > concurrentlyLimited' 0 todo ongoing results = do > (task, newResult) <- waitAny ongoing > concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) > > concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] > ongoing results > concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do > t <- async $ (i,) <$> task > concurrentlyLimited' (n-1) otherTasks (t:ongoing) results > > euler :: Int ? Int > euler n = length (filter (relprime n) [1..n-1]) > where > relprime x y = gcd x y == 1 > > sumEuler :: Int ? Int > sumEuler = sum . (map euler) . mkList > where > mkList n = [1..n-1] > > p ? IO Int > p = return $ sumEuler 3000 > > numThreads ? [String] ? IO Int > numThreads [] = return numCapabilities > numThreads [cores] = return $ read cores > > main ? IO() > main = do > threads ? getArgs >>= numThreads > putStrLn $ "Running up to " ++ show threads ++ " threads in parallel > (on " ++ show numCapabilities ++ " cores)" > startTime ? getCPUTime > f ? concurrentlyLimited threads $ replicate 10 p > endTime ? getCPUTime > putStrLn $ foldr ((++) . show ) "" f > putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - > startTime) / 1000000000000?Double) > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > Hello, > > I don't have an Haskell environnement at hand, but my advice is to search > for when your Async/eulerSum calls are evaluated. > For example try to remove this line -- putStrLn $ foldr ((++) . show ) "" > f > Does your program still compute something ? If no that's because your sum is > evaluated due to the show and not due to your async. > > t <- async $ (i,) <$> task > > Your async will try to compute (i,eulerSum) but you never force the > computation of the eulersum inside the async, so the async take no time and > return quickly. > Instead of this type [Async (Int, b)] you should aim for this one [(Int, > Async b)] > > Let me know if that helps you. > > Regards, > Romain > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > On Fri, Apr 24, 2015 at 1:44 PM, wrote: > > On 24/04/2015 14:21, Maurizio Vitale wrote: > > G'day, > I have a test code that I compile with ghc -threaded -eventlog > -rtsopts --make parallel.hs and run with ./parallel 2 +RTS -ls -N4 on > a laptop with 4 physical cores. I would expect activities in two > threads, but threadscope shows only one active thread. > Can somebody explain me the program's behaviour? > > Thanks a lot > > Maurizio > > {-# LANGUAGE UnicodeSyntax #-} > {-# LANGUAGE TupleSections #-} > > import Control.Applicative > import Control.Concurrent.Async (async, waitAny, Async) > import Data.List (delete, sortBy) > import Data.Ord (comparing) > import System.CPUTime > import System.Environment > import GHC.Conc (numCapabilities) > > concurrentlyLimited :: Int -> [IO a] -> IO [a] > concurrentlyLimited n tasks = concurrentlyLimited' n (zip [0..] tasks) [] > [] > > concurrentlyLimited' ? Int -- ^ number of concurrent > evaluations > ? [(Int, IO b)] -- ^ still to run (ordered by > first element) > ? [Async (Int,b)] -- ^ currently running > ? [(Int,b)] -- ^ partial results (ordered > by first element) > ? IO [b] > concurrentlyLimited' _ [] [] results = return . map snd $ sortBy > (comparing fst) results > concurrentlyLimited' 0 todo ongoing results = do > (task, newResult) <- waitAny ongoing > concurrentlyLimited' 1 todo (delete task ongoing) (newResult:results) > > concurrentlyLimited' _ [] ongoing results = concurrentlyLimited' 0 [] > ongoing results > concurrentlyLimited' n ((i, task):otherTasks) ongoing results = do > t <- async $ (i,) <$> task > concurrentlyLimited' (n-1) otherTasks (t:ongoing) results > > euler :: Int ? Int > euler n = length (filter (relprime n) [1..n-1]) > where > relprime x y = gcd x y == 1 > > sumEuler :: Int ? Int > sumEuler = sum . (map euler) . mkList > where > mkList n = [1..n-1] > > p ? IO Int > p = return $ sumEuler 3000 > > numThreads ? [String] ? IO Int > numThreads [] = return numCapabilities > numThreads [cores] = return $ read cores > > main ? IO() > main = do > threads ? getArgs >>= numThreads > putStrLn $ "Running up to " ++ show threads ++ " threads in parallel > (on " ++ show numCapabilities ++ " cores)" > startTime ? getCPUTime > f ? concurrentlyLimited threads $ replicate 10 p > endTime ? getCPUTime > putStrLn $ foldr ((++) . show ) "" f > putStrLn $ "Evaluation took " ++ show (fromIntegral (endTime - > startTime) / 1000000000000?Double) > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > Hello, > > I don't have an Haskell environnement at hand, but my advice is to search > for when your Async/eulerSum calls are evaluated. > For example try to remove this line -- putStrLn $ foldr ((++) . show ) "" > f > Does your program still compute something ? If no that's because your sum is > evaluated due to the show and not due to your async. > > t <- async $ (i,) <$> task > > Your async will try to compute (i,eulerSum) but you never force the > computation of the eulersum inside the async, so the async take no time and > return quickly. > Instead of this type [Async (Int, b)] you should aim for this one [(Int, > Async b)] > > Let me know if that helps you. > > Regards, > Romain > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > From shishir.srivastava at gmail.com Sun Apr 26 09:59:55 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Sun, 26 Apr 2015 10:59:55 +0100 Subject: [Haskell-beginners] IO and purity Message-ID: Hi, Can someone please explain how IO operations do not fit in the pure category of mathematical function in that they have to be implemented via Monads. For e.g. the getLine function has the type IOString and it reads the input from the user. Now as I see it the output of getLine will always be same if the input remain same (i.e. for input "X" getLine will always return "X" ) which is the constraint on mathematical functions. Therefore I don't see why monads are necessary for implementing IO in pure languages. I can understand why Date and Random functions have be implemented via monads because their output will always change. Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.drautzburg at web.de Sun Apr 26 10:13:35 2015 From: martin.drautzburg at web.de (martin) Date: Sun, 26 Apr 2015 12:13:35 +0200 Subject: [Haskell-beginners] How to "add column" to a Table? Message-ID: <553CBA4F.3090301@web.de> Hello all, I suppose the natural representation for a Table is a List of Tuples. Or more generally I'll probably end up with a type "Table a" where a stands for the Columns. I cannot figure out how to add a new Column to a Table. What would be the type of such an operation? If I just want to add an empty Column (which what an RDBMS would do), would I do something like this? addColumn :: ColumnDef -> Table a -> Table b But what is this ColumnDef? It would need to contain the name and type of the new column. To implement this operation I would have to somewehre add a column to something. But what is the type of this something. I don't see how I can add a component to a Tuple in a generic way, or can I? I browsed some code on Hackage and found code which uses Data.Proxy. It this the right direction? Or do I need to look at GADTs, or template haskell? Or am I overcomplicating things, and there is a true haskellish solution? From mailings at jakob.io Sun Apr 26 10:16:08 2015 From: mailings at jakob.io (Jakob Holderbaum) Date: Sun, 26 Apr 2015 12:16:08 +0200 Subject: [Haskell-beginners] IO and purity In-Reply-To: References: Message-ID: <553CBAE8.5050909@jakob.io> Hi Shishir, I explain it to myself as the nondeterministic behavior of the user which would lead to the impurity. >From the perspective of the programm, you just call a function without argument that returns a string. And every call has the potential to return something totally different depending on the users behavior. So what you called input is not the input in the sense of an functional argument which is the foundation of the definition of purity. I am myself an absolute beginner in Haskell and Functional Thinking so I hope to get some constructive feedback on my mental image of this situation. Cheers Jakob On 04/26/2015 11:59 AM, Shishir Srivastava wrote: > Hi, > > Can someone please explain how IO operations do not fit in the pure > category of mathematical function in that they have to be implemented via > Monads. > > For e.g. the getLine function has the type IOString and it reads the input > from the user. Now as I see it the output of getLine will always be same if > the input remain same (i.e. for input "X" getLine will always return "X" ) > which is the constraint on mathematical functions. > > Therefore I don't see why monads are necessary for implementing IO in pure > languages. > > I can understand why Date and Random functions have be implemented via > monads because their output will always change. > > Thanks, > Shishir > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -- Jakob Holderbaum, M.Sc. Embedded Software Engineer 0176 637 297 71 http://jakob.io/ http://jakob.io/mentoring/ hi at jakob.io @hldrbm From sumit.sahrawat.apm13 at iitbhu.ac.in Sun Apr 26 10:50:30 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Sun, 26 Apr 2015 16:20:30 +0530 Subject: [Haskell-beginners] IO and purity In-Reply-To: <553CBAE8.5050909@jakob.io> References: <553CBAE8.5050909@jakob.io> Message-ID: The IO Monad provides a way to construct imperative programs in a pure manner. For example, print x = putStrLn (show x) The function 'print' can be thought of as returning the same 'IO computation' for same values of x. Using the Monad interface, these instructions can be combined, like main = getLine >>= print which is equivalent to main = do x <- getLine print x Just like this, many IO values can be stitched together to create larger IO values, which are descriptions of imperative programs as above. It is pure, as the same 'computation' is returned for the same arguments. On 26 April 2015 at 15:46, Jakob Holderbaum wrote: > Hi Shishir, > > I explain it to myself as the nondeterministic behavior of the user which > would lead to the impurity. > > From the perspective of the programm, you just call a function without > argument that returns a string. > And every call has the potential to return something totally different > depending on the users behavior. > > So what you called input is not the input in the sense of an functional > argument which is the foundation of the definition of purity. > > I am myself an absolute beginner in Haskell and Functional Thinking so I > hope to get some constructive feedback on my mental image of this situation. > > Cheers > Jakob > > On 04/26/2015 11:59 AM, Shishir Srivastava wrote: > > Hi, > > > > Can someone please explain how IO operations do not fit in the pure > > category of mathematical function in that they have to be implemented via > > Monads. > > > > For e.g. the getLine function has the type IOString and it reads the > input > > from the user. Now as I see it the output of getLine will always be same > if > > the input remain same (i.e. for input "X" getLine will always return "X" > ) > > which is the constraint on mathematical functions. > > > > Therefore I don't see why monads are necessary for implementing IO in > pure > > languages. > > > > I can understand why Date and Random functions have be implemented via > > monads because their output will always change. > > > > Thanks, > > Shishir > > > > > > > > _______________________________________________ > > Beginners mailing list > > Beginners at haskell.org > > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > -- > Jakob Holderbaum, M.Sc. > Embedded Software Engineer > > 0176 637 297 71 > http://jakob.io/ > http://jakob.io/mentoring/ > hi at jakob.io > @hldrbm > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From ky3 at atamo.com Sun Apr 26 11:52:09 2015 From: ky3 at atamo.com (Kim-Ee Yeoh) Date: Sun, 26 Apr 2015 18:52:09 +0700 Subject: [Haskell-beginners] IO and purity In-Reply-To: References: Message-ID: On Sun, Apr 26, 2015 at 4:59 PM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > For e.g. the getLine function has the type IOString and it reads the > input from the user. Now as I see it the output of getLine will always be > same if the input remain same (i.e. for input "X" getLine will always > return "X" ) which is the constraint on mathematical functions. > Notice that getLine is not a function. It is a value of type IO String. In the misty dawn of Haskell, how you'd achieve the same thing as getLine is to actually use Dialogue functions. And yes, a value of type Dialogue is a bona fide function because Dialogue is a type synonym for [Response] -> [Request]. You can read a bit about Haskell 1.2 and IO here: http://r6.ca/blog/20110520T220201Z.html Now Haskell 1.2 dates from 1992. Certainly it would be an experience playing with it. Unfortunately, I know of no way to get hold of a compiler or interpreter that old. You might want to query haskell-cafe. Returning to getLine and monadic I/O, a question to contemplate is: how is getLine different from an ordinary String, say "hello world"? -- Kim-Ee -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcin.jan.mrotek at gmail.com Sun Apr 26 11:58:14 2015 From: marcin.jan.mrotek at gmail.com (Marcin Mrotek) Date: Sun, 26 Apr 2015 13:58:14 +0200 Subject: [Haskell-beginners] How to "add column" to a Table? In-Reply-To: <553CBA4F.3090301@web.de> References: <553CBA4F.3090301@web.de> Message-ID: Hello, Have a look at vinyl (https://hackage.haskell.org/package/vinyl) and HList (https://hackage.haskell.org/package/HList), packages that provide extensible records. I haven't used HList, but I can attest vinyl is quite easy to use. You can also have a look at http://www.reddit.com/r/haskell/comments/32tdt6/functions_for_type_level_lists/ for some discussion regarding implementation of relational databases in Haskell; I've linked to my (very) unfinished code there: http://hub.darcs.net/mjm/relational/browse/src/Data/Relational feel free to steal ideas :-P Best regards, Marcin Mrotek From ky3 at atamo.com Sun Apr 26 12:04:05 2015 From: ky3 at atamo.com (Kim-Ee Yeoh) Date: Sun, 26 Apr 2015 19:04:05 +0700 Subject: [Haskell-beginners] IO and purity In-Reply-To: <553CBAE8.5050909@jakob.io> References: <553CBAE8.5050909@jakob.io> Message-ID: On Sun, Apr 26, 2015 at 5:16 PM, Jakob Holderbaum wrote: > I am myself an absolute beginner in Haskell and Functional Thinking so I > hope to get some constructive feedback on my mental image of this situation. When you write: "From the perspective of the programm, you just call a function without argument that returns a string" you veer close to the lousy thinking that Everything is a Function. Conal Elliott did the delousing here: http://conal.net/blog/posts/everything-is-a-function-in-haskell Have a read, and if you're not convinced, come back here and ask for more help. -- Kim-Ee -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumit.sahrawat.apm13 at iitbhu.ac.in Sun Apr 26 12:20:59 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Sun, 26 Apr 2015 17:50:59 +0530 Subject: [Haskell-beginners] IO and purity In-Reply-To: References: <553CBAE8.5050909@jakob.io> Message-ID: Thanks for removing a misconception about everything being a function. My original example used writeFile, which is why I used the term 'function'. Refactoring text is more difficult as compared to haskell code :) On 26 April 2015 at 17:34, Kim-Ee Yeoh wrote: > > On Sun, Apr 26, 2015 at 5:16 PM, Jakob Holderbaum > wrote: > >> I am myself an absolute beginner in Haskell and Functional Thinking so I >> hope to get some constructive feedback on my mental image of this situation. > > > When you write: "From the perspective of the programm, you just call a > function without argument that returns a string" > > you veer close to the lousy thinking that Everything is a Function. Conal > Elliott did the delousing here: > > http://conal.net/blog/posts/everything-is-a-function-in-haskell > > Have a read, and if you're not convinced, come back here and ask for more > help. > > -- Kim-Ee > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.neely at gmail.com Sun Apr 26 12:22:29 2015 From: joel.neely at gmail.com (Joel Neely) Date: Sun, 26 Apr 2015 07:22:29 -0500 Subject: [Haskell-beginners] IO and purity In-Reply-To: References: Message-ID: Shishir, I'll reply as an humble programmer, not a category theorist. For me the clarifying example was to contrast putStrLn (getLine ++ getLine) with s = square 3 + square 4 where square x = x * x There is absolutely nothing that "leaks" between the two sub-expressions involving square, so I'm free to rewrite as: a = square 3 b = square 4 s = a + b or b = square 4 a = square 3 s = a + b or x = square 7 b = square 4 a = square 3 s = a + b y = square 8 or hh m n = square m + square n x = square 7 s = hh 3 4 y = square 8 without altering the value of s or any surrounding computation. In that last case, I can now freely intermingle uses of hh and square without risk. But if I were to attempt the same gymnastics with putStrLn and getLine, I wouldn't have those freedoms. The order of evaluation/performance now becomes critical. So the monad provides a way to manage the composition, and the type system ensures visibility to the fact that something more is going on when a defined function includes IO behavior. Hope that helps, -jn- On Sun, Apr 26, 2015 at 4:59 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > Hi, > > Can someone please explain how IO operations do not fit in the pure > category of mathematical function in that they have to be implemented via > Monads. > > For e.g. the getLine function has the type IOString and it reads the > input from the user. Now as I see it the output of getLine will always be > same if the input remain same (i.e. for input "X" getLine will always > return "X" ) which is the constraint on mathematical functions. > > Therefore I don't see why monads are necessary for implementing IO in pure > languages. > > I can understand why Date and Random functions have be implemented via > monads because their output will always change. > > Thanks, > Shishir > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Beauty of style and harmony and grace and good rhythm depend on simplicity. - Plato -------------- next part -------------- An HTML attachment was scrubbed... URL: From rasen.dubi at gmail.com Sun Apr 26 12:44:25 2015 From: rasen.dubi at gmail.com (Alexey Shmalko) Date: Sun, 26 Apr 2015 12:44:25 +0000 Subject: [Haskell-beginners] IO and purity In-Reply-To: References: Message-ID: You can't do putStrLn (getLine ++ getLine) so of course you can't do such transformations. I would suggest you rewrite your IO action without any syntactic sugar (with plain >> and >>=) first and then try to do transformations. I general, I find it useful to think of IO actions in two ways: - as a value of IO type that your main is (kind of instructions that Haskell runtime should perform). - the effects execution of this value causes. You can think that the sole purpose of your program is to construct this IO value, while its execution is performed kind of outside of your program. If you think that way, IO is again pure, obeys all monad rules and categorically valid monad. Regards, Alexey Shmalko On Sun, Apr 26, 2015 at 3:22 PM Joel Neely wrote: > Shishir, > > I'll reply as an humble programmer, not a category theorist. For me the > clarifying example was to contrast > > putStrLn (getLine ++ getLine) > > > with > > s = square 3 + square 4 > > > where > > square x = x * x > > > There is absolutely nothing that "leaks" between the two sub-expressions > involving square, so I'm free to rewrite as: > > a = square 3 > b = square 4 > s = a + b > > > or > > b = square 4 > a = square 3 > s = a + b > > > or > > x = square 7 > b = square 4 > a = square 3 > s = a + b > y = square 8 > > > or > > hh m n = square m + square n > x = square 7 > s = hh 3 4 > y = square 8 > > > without altering the value of s or any surrounding computation. In that > last case, I can now freely intermingle uses of hh and square without > risk. > > But if I were to attempt the same gymnastics with putStrLn and getLine, I > wouldn't have those freedoms. The order of evaluation/performance now > becomes critical. > > So the monad provides a way to manage the composition, and the type system > ensures visibility to the fact that something more is going on when a > defined function includes IO behavior. > > Hope that helps, > -jn- > > > > > > > On Sun, Apr 26, 2015 at 4:59 AM, Shishir Srivastava < > shishir.srivastava at gmail.com> wrote: > >> Hi, >> >> Can someone please explain how IO operations do not fit in the pure >> category of mathematical function in that they have to be implemented via >> Monads. >> >> For e.g. the getLine function has the type IOString and it reads the >> input from the user. Now as I see it the output of getLine will always be >> same if the input remain same (i.e. for input "X" getLine will always >> return "X" ) which is the constraint on mathematical functions. >> >> Therefore I don't see why monads are necessary for implementing IO in >> pure languages. >> >> I can understand why Date and Random functions have be implemented via >> monads because their output will always change. >> >> Thanks, >> Shishir >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > > > -- > Beauty of style and harmony and grace and good rhythm depend on > simplicity. - Plato > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at orlitzky.com Sun Apr 26 19:46:23 2015 From: michael at orlitzky.com (Michael Orlitzky) Date: Sun, 26 Apr 2015 15:46:23 -0400 Subject: [Haskell-beginners] How to "add column" to a Table? In-Reply-To: <553CBA4F.3090301@web.de> References: <553CBA4F.3090301@web.de> Message-ID: <553D408F.1070105@orlitzky.com> On 04/26/2015 06:13 AM, martin wrote: > Hello all, > > I suppose the natural representation for a Table is a List of Tuples. Or more generally I'll probably end up with a type > "Table a" where a stands for the Columns. > > I cannot figure out how to add a new Column to a Table. What would be the type of such an operation? If I just want to > add an empty Column (which what an RDBMS would do), would I do something like this? > > addColumn :: ColumnDef -> Table a -> Table b > > But what is this ColumnDef? It would need to contain the name and type of the new column. To implement this operation I > would have to somewehre add a column to something. But what is the type of this something. I don't see how I can add a > component to a Tuple in a generic way, or can I? > type Person = ( Int, -- ID String, -- Name Int, -- Age Bool -- Evil bit ) type Place = ( Int, -- ID String, -- Name Double, -- Longitude Double, -- Latitude Double -- Elevation ) data Column = Person | Place type Table = [Column] addColumn :: Table -> Column -> Table addColumn table col = table ++ [col] From ertesx at gmx.de Mon Apr 27 01:25:36 2015 From: ertesx at gmx.de (Ertugrul =?utf-8?Q?S=C3=B6ylemez?=) Date: Mon, 27 Apr 2015 03:25:36 +0200 Subject: [Haskell-beginners] IO and purity In-Reply-To: References: Message-ID: > Can someone please explain how IO operations do not fit in the pure > category of mathematical function in that they have to be implemented > via Monads. Let's not talk about monads at all. Instead allow me to eliminate a major misconception right away: I/O does in fact fit into the model of purity. The first major insight occurs when you stop thinking about getLine as a function or an "impure value". What it really is is just a program. Every value of type `IO A` is in fact a program that produces a value of type `A`. The second major insight happens when you realise that the equal sign in Haskell introduces an actual equation: line = getLine Here `line` is not a string either. You have just expressed that `line` is the exact same thing as `getLine`, so it is a program that, when run, produces a string. Now realise that `main` is also a program, the one that is the actual program you are writing. When putStrLn "Hello!" is a program that prints a string and results in the dummy value `()` and you say that main = putStrLn "Hello!" then the program you are writing is that same program, because you have just defined it to be (remember: equation, not assignment!). Now you have a bunch of programs. The final ingredient to writing side-effecting programs in Haskell is a way to combine those programs. If `p1` and `p2` are two programs, then `p1 >> p2` is the program that first executes `p1` and then executes `p2`. Its result is the result of `p2`, the latter argument of `(>>)`: main = putStrLn "Hello" >> putStrLn "world!" You have just defined `main` (i.e. your program) to be the program that first prints the "Hello" line, then prints the "world!" line. A more powerful operator is `(>>=)`, which is best explained in terms of an example: putStrLn :: String -> IO () Now this is an actual function. It takes a string and returns a program, the one that prints that string. Remember that functions are the things that can be applied. Not everything is a function, and in particular programs are *not* functions, a common and dangerous misconception. You could just pass it a string, but what if you want to print whatever `getLine` resulted in? (>>=) :: IO a -> (a -> IO b) -> IO b Verify that the first argument fits the type of `getLine`, the second one fits the type of `putStrLn`. Here is the specialised version, where `a = String` and `b = ()`: (>>=) :: IO String -> (String -> IO ()) -> IO () Simply apply it to the desired program (`getLine`) and the desired program-producing function (`putStrLn`) to get a composite program: main = getLine >>= putStrLn Now let's talk about monads. It is a nice incident that the `(>>=)` operator follows a nice algebraic structure (monads), just like addition follows a nice algebraic structure (monoids). And it is not the only operator that follows this structure. What we can do now is to write extremely generic functions that work for all monads with a single implementation. Welcome to the world of composable polymorphism. This is the main reason why Haskell code tends to be much shorter than code in other languages. Functions like `mapM` and `forever` are not IO-specific. They work for all monads, yet they have only a single implementation. So yes, you are right. Monads are not at all necessary. But they are useful, because we get so much for free. Basically when you implement a control functions, chances are that you can actually apply it to a wide variety of structures, including `IO`. Exercise: Can you think of an operation that would work for all monoids? If you can, you can implement it *in its general form* in Haskell. In other words, once you have established that some type denotes a monoid, that operation will be available for it for free. Same thing with monads. > For e.g. the getLine function has the type IOString and it reads the input > from the user. Now as I see it the output of getLine will always be same if > the input remain same (i.e. for input "X" getLine will always return "X" ) > which is the constraint on mathematical functions. > > Therefore I don't see why monads are necessary for implementing IO in pure > languages. > > I can understand why Date and Random functions have be implemented via > monads because their output will always change. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 472 bytes Desc: not available URL: From guthrie at mum.edu Mon Apr 27 02:38:37 2015 From: guthrie at mum.edu (Gregory Guthrie) Date: Sun, 26 Apr 2015 21:38:37 -0500 Subject: [Haskell-beginners] : GCJ 2015 - Round 1A Problem - Haircut Message-ID: <08EF9DA445C4B5439C4733E1F35705BA04F834A3C7D7@MAIL.cs.mum.edu> Seems to me that an estimate won't help, one has to know exactly how much to skip over. I did this: Find the lowest common multiple (lcm), and then from that the shortest cycle of services, And then skip any multiple of those from the customer queue. sim :: Problem -> [Result] sim (n, ts) = serve tSkip (servers ts) -- optimize; skip ahead over server cycles... where tsLcm = (foldl lcm $ head ts) $ tail ts tCycle = sum $ map (div tsLcm) ts tSkip = n - (div n tCycle)*tCycle (Some fixup is needed for tSkip=0, one easy one is to force an extra cycle.) > ---------------------------------------------------------------------- > Message: 1 > Date: Sat, 18 Apr 2015 10:29:11 -0400 > From: Doug McIlroy > To: sourabh.s.joshi at gmail.com > Cc: beginners at haskell.org > Subject: Re: [Haskell-beginners] GCJ 2015 - Round 1A Problem - Haircut > Message-ID: <201504181429.t3IETBfo025201 at coolidge.cs.dartmouth.edu> > Content-Type: text/plain; charset=us-ascii > > > Can someone tell me how I could have avoided or fixed this? > > The trouble manifested as stack overflow on solving > > > https://code.google.com/codejam/contest/4224486/dashboard#s=p1 > > For efficiency, you'll probably need more cleverness in math than in Haskell. You can predict > an approximate start time for the Nth customer's service from the average per-customer > service time M, where 1/M = sum 1/M_k. > Starting from that estimate, one can skip over almost the entire service simulation. > > Doug McIlroy > > From animeshsaxena at icloud.com Mon Apr 27 05:18:34 2015 From: animeshsaxena at icloud.com (Animesh Saxena) Date: Mon, 27 Apr 2015 13:18:34 +0800 Subject: [Haskell-beginners] Partition a number or optimize Message-ID: <58055B45-9513-461A-BD99-8AEE32405199@icloud.com> I have the following function to optimize myfunction = max(p `div` c + p `mod` c) Here p is an array of numbers and c is also an array of numbers I need to find c?s which minimize the value of my function. for example if p = [1,10000]. c = 2,8 or c = 1,9 or c=5,5 number of c is length of p which is 2 (in this case). Sum of c is given as a constraint, so for example if sum is 10, then c?s can be 2,8 or 1,9 or 5,5 or 4,6 or?..etc etc. Length of c will be equal to length of p array. Hope the problem statement is clear In haskell terms it will be, let my_min p c = foldl1 max $ zipWith (\p c -> (p `div` c) + (p `mod` c)) p c One way is to use various combinations of c using integer partitioning. Now i wrote a crude parts function to do this nparts 0 = [] nparts n = [n] : [x:xs | x <- [1..n`div`2], xs <- nparts(n - x)] which is a bad bad example of recursion coz it?s slow! *Main> nparts 5 [[5],[1,4],[1,1,3],[1,1,1,2],[1,1,1,1,1],[1,2,2],[1,2,1,1],[2,3],[2,1,2],[2,1,1,1]] I can then filter this with length of p and get the required options of c I can then call the function ? my_min? with this list (simple map application) Problem is if i do *Main> filter (\x->length x == 2) $ nparts 100 [[1,99] and it hangs?for a lot of time?.so time constraint? Any other approaches to this problem to make the partitions speedier. I know it?s an optimization problem?but all non linear optizers will use floats?and fail to converge?this is an integer optimizing problem. Any ideas?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.drautzburg at web.de Mon Apr 27 06:46:56 2015 From: martin.drautzburg at web.de (martin) Date: Mon, 27 Apr 2015 08:46:56 +0200 Subject: [Haskell-beginners] How to "add column" to a Table? In-Reply-To: <553D408F.1070105@orlitzky.com> References: <553CBA4F.3090301@web.de> <553D408F.1070105@orlitzky.com> Message-ID: <553DDB60.50106@web.de> Am 04/26/2015 um 09:46 PM schrieb Michael Orlitzky: > On 04/26/2015 06:13 AM, martin wrote: >> Hello all, >> >> I suppose the natural representation for a Table is a List of Tuples. Or more generally I'll probably end up with a type >> "Table a" where a stands for the Columns. >> >> I cannot figure out how to add a new Column to a Table. What would be the type of such an operation? If I just want to >> add an empty Column (which what an RDBMS would do), would I do something like this? >> >> addColumn :: ColumnDef -> Table a -> Table b >> >> But what is this ColumnDef? It would need to contain the name and type of the new column. To implement this operation I >> would have to somewehre add a column to something. But what is the type of this something. I don't see how I can add a >> component to a Tuple in a generic way, or can I? >> > > type Person = ( Int, -- ID > String, -- Name > Int, -- Age > Bool -- Evil bit > ) > > type Place = ( Int, -- ID > String, -- Name > Double, -- Longitude > Double, -- Latitude > Double -- Elevation > ) > > data Column = Person | Place > > type Table = [Column] > > addColumn :: Table -> Column -> Table > addColumn table col = table ++ [col] Aren't you adding a *row* to a Table which allows rows of multiple shapes? What I am looking for is an operation which adds a *column* to a regular table, i.e. one where all rows have the same shape. But I like your idea of adding an "Evil bit" to Persons. From shishir.srivastava at gmail.com Mon Apr 27 10:02:01 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Mon, 27 Apr 2015 11:02:01 +0100 Subject: [Haskell-beginners] fmap Maybe Message-ID: Hi, Please can someone explain why these two expression behave differently - ---- fmap (\x -> x) Just 2 Just 2 ----- fmap (\x -> x+2) Just 2 *No instance for (Num (Maybe a0)) arising from a use of `it'* *In a stmt of an interactive GHCi command: print it* ---- The first expression evaluates fine whereas the second one fails. However if I do - ---- fmap (\x -> x+2) $ Just 2 Just 4 ---- Then the second expression also returns the Maybe value. Why is $ needed in second expression but not in the first one ? Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From rasen.dubi at gmail.com Mon Apr 27 10:12:44 2015 From: rasen.dubi at gmail.com (Alexey Shmalko) Date: Mon, 27 Apr 2015 10:12:44 +0000 Subject: [Haskell-beginners] fmap Maybe In-Reply-To: References: Message-ID: Hi, Shishir, It's because Haskell uses juxtaposition for argument passing. So the first case fmap (\x -> x) Just 2 is equal to (fmap (\x -> x) Just) 2 While fmap (\x -> x+2) $ Just 2 is fmap (\x -> x + 2) (Just 2) I believe you want the latter. Basically, the first example works because ((->) r) is an instance of Functor. instance Functor ((->) r) where fmap = (.) So basically first example is: ((\x -> x) . Just) 2 Now you should see why it behaves this way. Have a nice day! Alexey Shmalko -------------- next part -------------- An HTML attachment was scrubbed... URL: From ollie at ocharles.org.uk Mon Apr 27 10:13:16 2015 From: ollie at ocharles.org.uk (Oliver Charles) Date: Mon, 27 Apr 2015 11:13:16 +0100 Subject: [Haskell-beginners] fmap Maybe In-Reply-To: References: Message-ID: Unfortunately you are running in to strange behavior due to a lack of parenthesis. First of all, let's see what your original expression actually is: fmap (\x -> x) Just 2 = (fmap (\x -> x) Just) 2 So you can see that you are actually fmaping over Just, rather than Just 2. What does this mean? Well, let's ask GHC: :t fmap _ Just Found hole `_' with type: Maybe a -> b That is, when you try and fmap over the *function* Just, we have to provide a function that expects a Maybe a, rather than an a. In your first case, your providing the identity function, which fits the required type as Maybe a -> Maybe a. However, in your second example, you are trying to provide apply the (+ 2) function to a Maybe a value (because x :: Maybe a). You cannot in general add numbers to Maybe a, hence the error message. Your final expression works because $ is effectively providing parenthesis: fmap (\x -> x + 2) $ Just 2 = fmap (\x -> x + 2) (Just 2) The precedence of application in Haskell can be confusing at the start - I suggest liberally using parenthesis, and then using HLint to remove the ones that you don't need. Eventually, you'll build up the necessary intuition. Hope this helps, - Ollie On Mon, Apr 27, 2015 at 11:02 AM, Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > Hi, > > Please can someone explain why these two expression behave differently - > > ---- > fmap (\x -> x) Just 2 > Just 2 > > ----- > fmap (\x -> x+2) Just 2 > > *No instance for (Num (Maybe a0)) arising from a use of `it'* > *In a stmt of an interactive GHCi command: print it* > > ---- > The first expression evaluates fine whereas the second one fails. However > if I do - > ---- > > fmap (\x -> x+2) $ Just 2 > Just 4 > ---- > > Then the second expression also returns the Maybe value. Why is $ needed > in second expression but not in the first one ? > > Thanks, > Shishir > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at orlitzky.com Mon Apr 27 13:25:08 2015 From: michael at orlitzky.com (Michael Orlitzky) Date: Mon, 27 Apr 2015 09:25:08 -0400 Subject: [Haskell-beginners] How to "add column" to a Table? In-Reply-To: <553DDB60.50106@web.de> References: <553CBA4F.3090301@web.de> <553D408F.1070105@orlitzky.com> <553DDB60.50106@web.de> Message-ID: <553E38B4.4010204@orlitzky.com> On 04/27/2015 02:46 AM, martin wrote: > > Aren't you adding a *row* to a Table which allows rows of multiple > shapes? What I am looking for is an operation which adds a *column* > to a regular table, i.e. one where all rows have the same shape. > Oh, shit =) Adding a column is a lot harder and does need some kind of "heterogenous list" library. To do it without one, you need something like, https://github.com/orlitzky/tuple/commit/8f6623b827f2192343c4fa4d520a4eb173033d9d That has one advantage: you can understand what it's doing. But it's not, uh, what's the word -- "aesthetically pleasing." My "prepend" is basically your "addColumn," and you can see that the type is, prepend :: a -> b -> c but that there's a functional dependency, a b -> c, b c -> a which basically means that the output tuple's type is going to depend on the input tuple's type and the type of the element that you're prepending to it. You can make this work on a table, too: type Table a = [a] addColumn :: Prep a b c => a -> Table b -> Table c addColumn col = map (prepend col) But if you know the type of the new (bigger) row at compile-time, what you probably want instead is fixed-vector-hetero. Then you can write, import qualified Data.Vector.HFixed as H ( cons ) ... addColumn col = map (H.cons col) That will work for any HVector row type, but you need to either specify or have the result type inferred. Otherwise you'll get an ambiguous type error. So this won't work: ghci> let p1 = (1,"mjo",9000,True) :: Person ghci> let t1 = [p1] :: Table Person ghci> addColumn "new" t1 But this would, ghci> addColumn "new" t1 :: Table (String, Int, String, Int, Bool) [("new",1,"mjo",9000,True)] If the result type can't be inferred, the tuple solution I mentioned earlier might be less annoying, but switching "prepend" to "append" is up to you! From ertesx at gmx.de Mon Apr 27 14:19:20 2015 From: ertesx at gmx.de (Ertugrul =?utf-8?Q?S=C3=B6ylemez?=) Date: Mon, 27 Apr 2015 16:19:20 +0200 Subject: [Haskell-beginners] Partition a number or optimize In-Reply-To: <58055B45-9513-461A-BD99-8AEE32405199@icloud.com> References: <58055B45-9513-461A-BD99-8AEE32405199@icloud.com> Message-ID: > Now i wrote a crude parts function to do this > > nparts 0 = [] > nparts n = [n] : [x:xs | x <- [1..n`div`2], xs <- nparts(n - x)] > > which is a bad bad example of recursion coz it?s slow! It's not the recursion that makes it slow, but its asymptotic runtime, which is O(2^n). This one might run slightly faster: intParts :: Integer -> [[Integer]] intParts n = do x <- [1..n] let r = n - x if r > 0 then map (x :) (intParts (n - x)) else [[x]] Verify that this function takes a lot of time for an argument as small as 20, because it finds 2^19 partitionings. You need to eliminate candidates early. For example if you know that you only need 2-partitionings, then there is no need at all for the recursion and you can get away with O(n). Alternatively you can eliminate certain partitions by changing the third line. x <- [2..n] This finds partitions of at least 2. Or introduce a stop-early condition. Greets, Ertugrul -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 472 bytes Desc: not available URL: From animeshsaxena at icloud.com Mon Apr 27 14:23:44 2015 From: animeshsaxena at icloud.com (Animesh Saxena) Date: Mon, 27 Apr 2015 22:23:44 +0800 Subject: [Haskell-beginners] Partition a number or optimize In-Reply-To: References: <58055B45-9513-461A-BD99-8AEE32405199@icloud.com> Message-ID: <0ED252BE-2857-4FB2-BCBF-61BC282B507E@icloud.com> I did find a better solution but it?s still slow let cities = 6 let clinics = 10 let populations = [1,10000,2,3,400,1] let nparts n k = filter ((==n) . sum) $ replicateM k [1..n] let d2 = nparts clinics cities let d1 = map maximum (map (\x -> zipWith (/) populations (map (\n-> fromIntegral n) x)) $ d2) maximum $ zipWith (\n x -> (n `div` x) + (n `mod` x) ) populations $ d2 !! (head $ filter ((==minimum d1) . (d1 !!)) [0..]) here also nparts take time?.if we choose clinics > 10 Heres the problem statement The World Health Organization (WHO) wants to establish a total of B vaccination clinics across Ncities to immunization people against fatal diseases. Every city must have at least 1 clinic, and a clinic can only vaccinate people in the same city where they live. The goal is to minimize the number of vaccination kits needed in the largest clinic. For example, suppose you have: 2 cities and 7 clinics to be opened. If 200,000 is the population of the first city and 500,000 is the population of the second city, then two clinics can open in the first city and five in the second. This way, 100,000 people can be immunized in each of the two clinics in the first city, and 100,000 can be immunized in each clinic in the second city. So the maximum number of people to be immunized in the largest clinic is 100,000 -Animesh > On Apr 27, 2015, at 10:19 PM, Ertugrul S?ylemez wrote: > > as 20, because it finds 2^19 partitionings. You need to eliminate -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwm at mired.org Mon Apr 27 16:21:16 2015 From: mwm at mired.org (Mike Meyer) Date: Mon, 27 Apr 2015 11:21:16 -0500 Subject: [Haskell-beginners] Partition a number or optimize In-Reply-To: <0ED252BE-2857-4FB2-BCBF-61BC282B507E@icloud.com> References: <58055B45-9513-461A-BD99-8AEE32405199@icloud.com> <0ED252BE-2857-4FB2-BCBF-61BC282B507E@icloud.com> Message-ID: You don't want to do full search here. You want to do a "branch and bound" search, keeping track of the current best value (which suggests the State monad) and then terminating searches of subtrees when the best possible value for that subtree is worse than the current global best possible. I haven't looked into doing this in Haskell, but it should be a lot faster than trying to search the full tree. On Mon, Apr 27, 2015 at 9:23 AM, Animesh Saxena wrote: > let cities = 6 > let clinics = 10 > let populations = [1,10000,2,3,400,1] > let nparts n k = filter ((==n) . sum) $ replicateM k [1..n] > let d2 = nparts clinics cities > let d1 = map maximum (map (\x -> zipWith (/) populations (map (\n-> > fromIntegral n) x)) $ d2) > maximum $ zipWith (\n x -> (n `div` x) + (n `mod` x) ) populations $ d2 !! > (head $ filter ((==minimum d1) . (d1 !!)) [0..]) > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ky3 at atamo.com Tue Apr 28 07:20:57 2015 From: ky3 at atamo.com (Kim-Ee Yeoh) Date: Tue, 28 Apr 2015 14:20:57 +0700 Subject: [Haskell-beginners] This year's Google Summer of Code Message-ID: will see one of the actively helpful members of this list, Sumit Sahrawat, help contribute to making a full-featured Computer Algebra System an open-source reality. He will take the IHaskell package (inspired by IPython) one step closer to feature parity with Mathematica: https://www.google-melange.com/gsoc/project/details/google/gsoc2015/sumit_sahrawat/5750085036015616 Sumit: Congrats for bagging GSOC ! -- Kim-Ee -------------- next part -------------- An HTML attachment was scrubbed... URL: From haskell at elisehuard.be Tue Apr 28 09:37:49 2015 From: haskell at elisehuard.be (Elise Huard) Date: Tue, 28 Apr 2015 11:37:49 +0200 Subject: [Haskell-beginners] Data and Typeable for an opaque type Message-ID: Hi, I'm working on an open source patch, but stumbled upon the following problem: I'm introducing a type that is basically a pointer in a FFI library, pointing to an opaque type (which I'm told is common practice). -- | An opaque type encapsulating a font in C. data Font_Opaque type Font = Ptr Font_Opaque The problem is that insertion in the current code would require this to be an instance of Data and Typeable. In this case (gloss library) I've not 100% understood why that's a requirement, I've been grepping (case-insensitive) for typeOf, constr, gfold, and I've not found any obvious use. Anyway, the rough-and-ready approach for this would be to manually define instances of Data and Typeable for the opaque type - my question is: what would sensible implementations look like for such a type? Thank you, Elise From shishir.srivastava at gmail.com Tue Apr 28 09:53:06 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Tue, 28 Apr 2015 10:53:06 +0100 Subject: [Haskell-beginners] Variable re-use Message-ID: Hi, Please can anyone explain how does 'a' get re-used in the code below. My understanding so far of haskell is that variables are not allowed to mutate or re-assigned. --- do a <- [1,2,3] a <- [a+1] return a [2,3,4] --- Thanks, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From shishir.srivastava at gmail.com Tue Apr 28 10:11:02 2015 From: shishir.srivastava at gmail.com (Shishir Srivastava) Date: Tue, 28 Apr 2015 11:11:02 +0100 Subject: [Haskell-beginners] This year's Google Summer of Code Message-ID: Brilliant work ! Congrats to ever so helpful Sumit Sahrawat ! Cheers, Shishir -------------- next part -------------- An HTML attachment was scrubbed... URL: From rasen.dubi at gmail.com Tue Apr 28 10:11:47 2015 From: rasen.dubi at gmail.com (Alexey Shmalko) Date: Tue, 28 Apr 2015 10:11:47 +0000 Subject: [Haskell-beginners] Variable re-use In-Reply-To: References: Message-ID: If you rewrite your example without do notation, you'll get: [1,2,3] >>= \a -> [a+1] >>= return a You can notice that first `a` and the last one are different things. They are just different bindings that happen to have the same name (You'll get the shadowing warning if enable -Wall). They have nothing in common and can have different types as well. On Tue, Apr 28, 2015 at 12:53 PM Shishir Srivastava < shishir.srivastava at gmail.com> wrote: > Hi, > > Please can anyone explain how does 'a' get re-used in the code below. My > understanding so far of haskell is that variables are not allowed to mutate > or re-assigned. > > --- > do > a <- [1,2,3] > a <- [a+1] > return a > > [2,3,4] > --- > > Thanks, > Shishir > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From grzegorzmilka at gmail.com Tue Apr 28 10:12:10 2015 From: grzegorzmilka at gmail.com (Grzegorz Milka) Date: Tue, 28 Apr 2015 12:12:10 +0200 Subject: [Haskell-beginners] Variable re-use In-Reply-To: References: Message-ID: <553F5CFA.9040503@gmail.com> Hi, The variable is not reassigned, but hidden. The do notation is a syntactic sugar for: [1, 2, 3] >>= (\a -> [a + 1] >>= (\a -> return a)) The second 'a' is inside a nested lambda function and therefore inside a nested scope. The first 'a' still exists, but the value to which it refers is hidden inside the second lambda function, where 'a' is bound to a different value. On 28.04.2015 11:53, Shishir Srivastava wrote: > Hi, > > Please can anyone explain how does 'a' get re-used in the code below. My > understanding so far of haskell is that variables are not allowed to mutate > or re-assigned. > > --- > do > a <- [1,2,3] > a <- [a+1] > return a > > [2,3,4] > --- > > Thanks, > Shishir > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: OpenPGP digital signature URL: From rasen.dubi at gmail.com Tue Apr 28 10:15:48 2015 From: rasen.dubi at gmail.com (Alexey Shmalko) Date: Tue, 28 Apr 2015 10:15:48 +0000 Subject: [Haskell-beginners] Variable re-use In-Reply-To: <553F5CFA.9040503@gmail.com> References: <553F5CFA.9040503@gmail.com> Message-ID: I'm sorry, my example should've been: [1,2,3] >>= \a -> [a+1] >>= \a -> return a On Tue, Apr 28, 2015 at 1:12 PM Grzegorz Milka wrote: > Hi, > > The variable is not reassigned, but hidden. The do notation is a syntactic > sugar for: > > [1, 2, 3] >>= (\a -> > [a + 1] >>= (\a -> > return a)) > > > The second 'a' is inside a nested lambda function and therefore inside a > nested scope. The first 'a' still exists, but the value to which it refers > is hidden inside the second lambda function, where 'a' is bound to a > different value. > > On 28.04.2015 11:53, Shishir Srivastava wrote: > > Hi, > > Please can anyone explain how does 'a' get re-used in the code below. My > understanding so far of haskell is that variables are not allowed to mutate > or re-assigned. > > --- > do > a <- [1,2,3] > a <- [a+1] > return a > > [2,3,4] > --- > > Thanks, > Shishir > > > > > _______________________________________________ > Beginners mailing listBeginners at haskell.orghttp://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumit.sahrawat.apm13 at iitbhu.ac.in Tue Apr 28 11:26:24 2015 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Tue, 28 Apr 2015 16:56:24 +0530 Subject: [Haskell-beginners] This year's Google Summer of Code In-Reply-To: References: Message-ID: I am very humbled. Thanks, both of you. My proposal is available at https://github.com/sumitsahrawat/gsoc, if you're interested in knowing what I have planned to do. On 28 April 2015 at 15:41, Shishir Srivastava wrote: > Brilliant work ! > > Congrats to ever so helpful Sumit Sahrawat ! > > Cheers, > Shishir > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Regards Sumit Sahrawat -------------- next part -------------- An HTML attachment was scrubbed... URL: From ertesx at gmx.de Tue Apr 28 14:29:42 2015 From: ertesx at gmx.de (Ertugrul =?utf-8?Q?S=C3=B6ylemez?=) Date: Tue, 28 Apr 2015 16:29:42 +0200 Subject: [Haskell-beginners] Data and Typeable for an opaque type In-Reply-To: References: Message-ID: > data Font_Opaque > type Font = Ptr Font_Opaque > > [...] > > Anyway, the rough-and-ready approach for this would be to manually > define instances of Data and Typeable for the opaque type - my > question is: what would sensible implementations look like for such a > type? Manual instances of those are usually highly questionable. While you probably won't blow up anything with a manual Data instance, a manual Typeable instance is in the critical danger zone alongside unsafeCoerce. First of all Ptr is already Typeable and for concrete types like Font_Opaque you can derive Typeable. That makes Font Typeable. If you need a Data instance for processing, then one way to get it is to build an isomorphism between Font and a regular Haskell type. Start by rewriting Font to be a newtype wrapper. Derive Data for the helper type and write the Data instance for Font in terms of it. This might save you a lot of work, or it may create even more work depending on the API you're depending on. Final alternative: You do what many of us have done many times. In some cases implementing a Haskell variant of a foreign library from scratch is more efficient than trying to deal with a clumsy C API. Often this is not an option, but when it is, it's usually a good one. Greets, Ertugrul -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 472 bytes Desc: not available URL: From allbery.b at gmail.com Wed Apr 29 23:27:16 2015 From: allbery.b at gmail.com (Brandon Allbery) Date: Wed, 29 Apr 2015 23:27:16 +0000 Subject: [Haskell-beginners] abstracting parametrized record types In-Reply-To: <1043822803.108276.1412278273309.JavaMail.yahoo@jws10733.mail.gq1.yahoo.com> References: <1043822803.108276.1412278273309.JavaMail.yahoo@jws10733.mail.gq1.yahoo.com> Message-ID: On Thu, Oct 2, 2014 at 7:31 PM, Alia wrote: > I would like to define a higher-level record type which contains, > for configuration purposes, a certain set of jobs for execution. Let's > say we call it a JobSet and which could possibly look like this: > > data JobSet = JobSet > { jobsetID :: String > , jobsetName :: String > , jobs :: [Job] <-- yes I know this is not legal > } > Are you sure you don't want data JobSet a = JobSet {jobsetID :: String ,jobsetName :: String ,jobs :: [Job a] } ? -- brandon s allbery kf8nh sine nomine associates allbery.b at gmail.com ballbery at sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net -------------- next part -------------- An HTML attachment was scrubbed... URL: