From mpm at alumni.caltech.edu Sat Aug 1 13:17:20 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sat Aug 1 12:58:22 2009 Subject: [Haskell-beginners] MonadRandom or Control.Monad.Random In-Reply-To: <20090801010202.GA22160@seas.upenn.edu> References: <4A723526.2030605@alumni.caltech.edu> <20090731023321.GA16128@seas.upenn.edu> <4A73928F.4050208@alumni.caltech.edu> <20090801010202.GA22160@seas.upenn.edu> Message-ID: <4A7478A0.1030902@alumni.caltech.edu> Brent Yorgey wrote: > On Fri, Jul 31, 2009 at 05:55:43PM -0700, Michael P Mossey wrote: >> I'm looking at this example from the docs. I understand most of this but I >> can't find a definition of getRandomR. See die has type (Rand g Int) I'm >> assuming getRandomR is a function that has that type, but I can't find its >> definition. > > getRandomR has type > > (MonadRandom m, Random a) => (a, a) -> m a > > which in particular can be specialized to > > (RandomGen g) => (Int,Int) -> Rand g Int . > > The documentation for getRandomR, and the other methods of the > MonadRandom class, can be found here: > > http://hackage.haskell.org/packages/archive/MonadRandom/0.1.3/doc/html/Control-Monad-Random-Class.html Thanks. I'm still getting used to Haskell documentation. I was looking in Control.Monad.Random, but I needed to look in Control.Monad.Random.Class. So I would like to know how to do something which is on the surface imperative-like: toss a die until a 1 comes up, and count the number of tosses. This would involve some kind of looping with an exit condition in an imperative language. Can someone show me how to write that in Haskell? (Actually I want to do a lot more than that, but I just want to start there.) Thanks, Mike From byorgey at seas.upenn.edu Sat Aug 1 13:36:39 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sat Aug 1 13:17:38 2009 Subject: [Haskell-beginners] MonadRandom or Control.Monad.Random In-Reply-To: <4A7478A0.1030902@alumni.caltech.edu> References: <4A723526.2030605@alumni.caltech.edu> <20090731023321.GA16128@seas.upenn.edu> <4A73928F.4050208@alumni.caltech.edu> <20090801010202.GA22160@seas.upenn.edu> <4A7478A0.1030902@alumni.caltech.edu> Message-ID: <20090801173639.GA20806@seas.upenn.edu> On Sat, Aug 01, 2009 at 10:17:20AM -0700, Michael Mossey wrote: > > > Brent Yorgey wrote: >> On Fri, Jul 31, 2009 at 05:55:43PM -0700, Michael P Mossey wrote: > >>> I'm looking at this example from the docs. I understand most of this but >>> I can't find a definition of getRandomR. See die has type (Rand g Int) >>> I'm assuming getRandomR is a function that has that type, but I can't >>> find its definition. >> >> getRandomR has type >> (MonadRandom m, Random a) => (a, a) -> m a >> >> which in particular can be specialized to >> (RandomGen g) => (Int,Int) -> Rand g Int . >> The documentation for getRandomR, and the other methods of the >> MonadRandom class, can be found here: >> >> http://hackage.haskell.org/packages/archive/MonadRandom/0.1.3/doc/html/Control-Monad-Random-Class.html > > Thanks. I'm still getting used to Haskell documentation. I was looking in > Control.Monad.Random, but I needed to look in Control.Monad.Random.Class. > > So I would like to know how to do something which is on the surface > imperative-like: toss a die until a 1 comes up, and count the number of > tosses. This would involve some kind of looping with an exit condition in > an imperative language. Can someone show me how to write that in Haskell? > > (Actually I want to do a lot more than that, but I just want to start there.) You could do something as simple as this: tossesUntilOne :: (RandomGen g) => Rand g Int tossesUntilOne = do tosses <- getRandomRs (1,6) return $ length (takeWhile (/= 1) tosses) + 1 That is, instead of writing it as a loop with an exit condition, you can just generate an infinite list of tosses, then count the length of the portion before the first 1. -Brent From mpm at alumni.caltech.edu Sat Aug 1 13:44:49 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Sat Aug 1 13:25:56 2009 Subject: [Haskell-beginners] type constructors Message-ID: <4A747F11.20805@alumni.caltech.edu> I was playing around with type constructors and I wrote this: data Foo a b = Foo1 [a] | Foo2 (a -> b) t3 = Foo1 [1, 2, 3] I wanted to see what ghci thought the type of t3 was. Essentially, it's data that doesn't use all of the type variables. So this ran fine, and *Main> :t t3 t3 :: Foo Integer b Wow! The data exists but it doesn't have a "complete type" so to speak. This worked, too: f3 (Foo1 xs) = length xs *Main> f3 t3 3 This is surprising to a conventional programmer. But does this naturally relate to other features of Haskell. Perhaps laziness? (I.e. data of type Foo doesn't always need a type b so it just doesn't have one until it needs one.) Thanks, Mike From jason.dusek at gmail.com Sat Aug 1 14:43:10 2009 From: jason.dusek at gmail.com (Jason Dusek) Date: Sat Aug 1 14:24:07 2009 Subject: [Haskell-beginners] type constructors In-Reply-To: <4A747F11.20805@alumni.caltech.edu> References: <4A747F11.20805@alumni.caltech.edu> Message-ID: <42784f260908011143r5dc15283x64a8530f7bd24019@mail.gmail.com> 2009/08/01 Michael P Mossey : > This is surprising to a conventional programmer. But does this > naturally relate to other features of Haskell. Perhaps > laziness? (I.e. data of type Foo doesn't always need a type b > so it just doesn't have one until it needs one.) Laziness is a runtime thing; type constraints are compile time. So "...doesn't have one until it needs one." isn't right -- `t3` will *never* have a type for `b` in the program snippet above. If you add more code (create a different context) then you might constrain `b` more and lead to a more definite type. The type is always a static type, though -- types don't get more specific as the program runs. -- Jason Dusek From daniel.is.fischer at web.de Sat Aug 1 15:00:45 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Aug 1 14:42:32 2009 Subject: [Haskell-beginners] type constructors In-Reply-To: <4A747F11.20805@alumni.caltech.edu> References: <4A747F11.20805@alumni.caltech.edu> Message-ID: <200908012100.46173.daniel.is.fischer@web.de> Am Samstag 01 August 2009 19:44:49 schrieb Michael P Mossey: > I was playing around with type constructors and I wrote this: > > data Foo a b = Foo1 [a] > > | Foo2 (a -> b) > > t3 = Foo1 [1, 2, 3] > > I wanted to see what ghci thought the type of t3 was. Essentially, it's > data that doesn't use all of the type variables. So this ran fine, and > > *Main> :t t3 > t3 :: Foo Integer b Actually, the type of t3 could be t3 :: Num a => Foo a b but without a type signature the monomorphism restriction applies and a is defaulted to Integer. *MFoo> :t Foo2 even Foo2 even :: (Integral a) => Foo a Bool > > Wow! The data exists but it doesn't have a "complete type" so to speak. It does, it has a polymorphic type, or one could say it has many types: *MFoo> :t [t3,Foo2 even] [t3,Foo2 even] :: [Foo Integer Bool] *MFoo> :t [t3,Foo2 id] [t3,Foo2 id] :: [Foo Integer Integer] *MFoo> :t (t3 :: Foo Integer Bool) (t3 :: Foo Integer Bool) :: Foo Integer Bool *MFoo> :t (t3 :: Foo Integer Char) (t3 :: Foo Integer Char) :: Foo Integer Char *MFoo> :t (t3 `asTypeOf` (Foo2 even)) (t3 `asTypeOf` (Foo2 even)) :: Foo Integer Bool *MFoo> :t (t3 `asTypeOf` (Foo2 id)) (t3 `asTypeOf` (Foo2 id)) :: Foo Integer Integer > This worked, too: > > f3 (Foo1 xs) = length xs > > *Main> f3 t3 > 3 *MFoo> :t (\(Foo1 xs) -> length xs) (\(Foo1 xs) -> length xs) :: Foo t1 t -> Int > > This is surprising to a conventional programmer. But does this naturally > relate to other features of Haskell. Perhaps laziness? (I.e. data of type > Foo doesn't always need a type b so it just doesn't have one until it needs > one.) Polymorphism and type inference, not laziness. > > Thanks, > Mike From gandolfmatt at gmail.com Sat Aug 1 22:02:54 2009 From: gandolfmatt at gmail.com (Matt f) Date: Sat Aug 1 21:43:52 2009 Subject: [Haskell-beginners] Haskell OpenGL trouble Message-ID: <2717745e0908011902o4a3c4955ydd14141c7ac73ff0@mail.gmail.com> I am currently running Mac OS 10.5.7, and I have install many Haskell files, compiled a bouncing ball example, fixed the enableGUI bug, tried an IDE, and have started installing graphics libraries. I am using Cabal in the terminal to install what I need, though whenever I try to install opengl or a package of opengl; it comes up with an error. Macintosh-2:opengl matthew$ sudo cabal install Resolving dependencies... Configuring OpenGLRaw-1.0.1.0... cabal: Missing dependency on a foreign library: * Missing C library: GL This problem can usually be solved by installing the system package that provides this library (you may need the "-dev" version). If the library is already installed but in a non-standard location then you can use the flags --extra-include-dirs= and --extra-lib-dirs= to specify where it is. cabal: Error: some packages failed to install: GLURaw-1.0.0.0 depends on OpenGLRaw-1.0.1.0 which failed to install. OpenGL-2.3.0.0 depends on OpenGLRaw-1.0.1.0 which failed to install. OpenGLRaw-1.0.1.0 failed during the configure step. The exception was: exit: ExitFailure 1 Macintosh-2:opengl matthew$ It appears that I have zoned onto the bit that's causing all this mess, I'm missing a C library: GL. Unfortunately after googling a while I have found no answer. Am I doing something wrong? Is there another way? Could there be a fix? Thanks, -Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090801/f025e7bd/attachment-0001.html From gandolfmatt at gmail.com Sat Aug 1 22:08:54 2009 From: gandolfmatt at gmail.com (Matt f) Date: Sat Aug 1 21:49:51 2009 Subject: [Haskell-beginners] All-in-one package? Message-ID: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> Hey... I'm new to Haskell, been working in Java for 5 months and have decided to move up. Haskell is very much different than what I'm use to and I'm wondering if there is a all-in-one package I can download and just press install to get everything needed for Haskell. Something that includes compilers, libraries, wxHaskell, OpenGl for Haskell, ect... Like how Visual basic or Netbeans are. A few more questions: Is there an IDE? If not, is there some program that will open Haskell files, edit them, and be able to run them without any Terminal usage? Is there an official forum for Haskell? If Haskell had individual platform install packages installing everything needed for Haskell without any hassle with a beginner friendly forum and website, it'd become probably as popular as Java or Vb.net. Is anything like this planned? Thanks, -Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090801/3dcf5858/attachment.html From nicolaff at gmail.com Sat Aug 1 22:14:39 2009 From: nicolaff at gmail.com (..: NicolafF :..) Date: Sat Aug 1 21:55:41 2009 Subject: [Haskell-beginners] All-in-one package? In-Reply-To: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> References: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> Message-ID: <1249179279.3560.8.camel@TotaX> i'm using http://leksah.org/ El s?b, 01-08-2009 a las 21:08 -0500, Matt f escribi?: > Hey... I'm new to Haskell, been working in Java for 5 months and have > decided to move up. Haskell is very much different than what I'm use > to and I'm wondering if there is a all-in-one package I can download > and just press install to get everything needed for Haskell. Something > that includes compilers, libraries, wxHaskell, OpenGl for Haskell, > ect... Like how Visual basic or Netbeans are. > > > A few more questions: > Is there an IDE? > If not, is there some program that will open Haskell files, edit them, > and be able to run them without any Terminal usage? > Is there an official forum for Haskell? > > > If Haskell had individual platform install packages installing > everything needed for Haskell without any hassle with a beginner > friendly forum and website, it'd become probably as popular as Java or > Vb.net. Is anything like this planned? > > > > > Thanks, > -Matt > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From kyagrd at gmail.com Sat Aug 1 22:19:09 2009 From: kyagrd at gmail.com (Ahn, Ki Yung) Date: Sat Aug 1 22:00:20 2009 Subject: [Haskell-beginners] Re: All-in-one package? In-Reply-To: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> References: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> Message-ID: Matt f wrote: > Hey... I'm new to Haskell, been working in Java for 5 months and have > decided to move up. Haskell is very much different than what I'm use to > and I'm wondering if there is a all-in-one package I can download and > just press install to get everything needed for Haskell. Something that > includes compilers, libraries, wxHaskell, OpenGl for Haskell, ect... > Like how Visual basic or Netbeans are. Install GHC and the Haskell platform. > A few more questions: > Is there an IDE? Yes. It is one called leksah. It is also possible to use on Eclipse. I haven't used neither of them seriously, becuase I'm already a quite satisfied with the runnin ghci in the terminal. ghci is a very decent interactive environment, far more convenient than any other existing scripting languages like ocaml, python, perl. Ghci interactive environment has auto completion built in! Press tab and it tries to auto complete a binding name that is visible in the toplevel. I haven't seen such a user friendly interactive REPL other than ghci. > If not, is there some program that will open Haskell files, edit them, > and be able to run them without any Terminal usage? > Is there an official forum for Haskell? You are arleady here, where else would you want to look for. And, there are haskell-cafe mailing list and other haskell realted as well. There is also #haskell IRC channel at freenode IRC servers. > If Haskell had individual platform install packages installing > everything needed for Haskell without any hassle with a beginner > friendly forum and website, it'd become probably as popular as Java or > Vb.net. Is anything like this planned? As I previously mentioned, we already have it, and its called the Haskell Platform. I prefer using cabal-install and install only the packages that I need. -- Ahn, Ki Yung From felipe.lessa at gmail.com Sat Aug 1 23:13:47 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sat Aug 1 22:54:48 2009 Subject: [Haskell-beginners] Re: All-in-one package? In-Reply-To: References: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> Message-ID: <20090802031347.GA17561@kira.casa> > > ...it'd become probably as popular as Java or Vb.net. > ...we already have it! So we're ready for world domination! :) -- Felipe. From orclev at gmail.com Sat Aug 1 23:50:53 2009 From: orclev at gmail.com (Kyle Murphy) Date: Sat Aug 1 23:31:51 2009 Subject: [Haskell-beginners] All-in-one package? In-Reply-To: <1249179279.3560.8.camel@TotaX> References: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> <1249179279.3560.8.camel@TotaX> Message-ID: <2db78cee0908012050r622a588fm9b02b6f73ba9e76a@mail.gmail.com> FYI, I tried out leksah and it has a lot of promise but isn't yet at the point and click install and run level that something like eclipse is. To start with I'm pretty sure you can't download a pre-compiled binary for any platform so before you can even use it you need to already have haskell and the usual support utilities installed. It does have a build script that should take care of actually assembling everything into a running application but for windows users it's not going to be a simple process to get all the pieces installed and running that you need to get it to build (in my case I'm running XP 64 bit which apparently does not play nice with the wxHaskell library as as soon as I mouse over any wxWidget objects it crashes with a seg fault), although for an semi-experience linux user the process should be relatively straightforward if a bit time consuming (in fact most of the pre-reqs should already be installed). As for the actual IDE itself once you finally get it installed it's not bad although being a relative newbie to Haskell I probably don't appreciate fully all that it offers. As others have said on here you'll probably get a bit more mileage out of the pure GHCi environment as a newbie and then once you're comfortable with that and ready for something a bit more powerful you can pick up leksah (and hopefully it will be that much more polished at that point as well). Some other tools to look at would be HLint ( http://community.haskell.org/~ndm/hlint/) and HaRe ( http://www.cs.kent.ac.uk/projects/refactor-fp/hare.html). A note on HaRe, it's still pretty new itself and I can't speak to it's actual quality because I haven't used it myself yet. Having used GHC and the various other Haskell utilities on both a Linux (Ubuntu) and Windows (XP Pro 64 bit) system, it's definitely more straightforward on Linux (but what in the programming world isn't?) but at least as far as the core of GHC is concerned it's not too bad on Windows. With GHCi you can setup an external editor (I'm partial to notepad++ in windows) to be launched from inside GHCi so you can have a pretty standard process where you fire up GHCi, load your file, and then call the edit command which will launch your configured editor, you can make your changes, save, and then have GHCi reload the updated file. You have essentially a full development environment in two windows, although it's a bit awkward swapping back and forth between GHCi to test and evaluate code and the editor to essentially persist it. On Sat, Aug 1, 2009 at 10:14 PM, ..: NicolafF :.. wrote: > i'm using http://leksah.org/ > > > > El s?b, 01-08-2009 a las 21:08 -0500, Matt f escribi?: > > Hey... I'm new to Haskell, been working in Java for 5 months and have > > decided to move up. Haskell is very much different than what I'm use > > to and I'm wondering if there is a all-in-one package I can download > > and just press install to get everything needed for Haskell. Something > > that includes compilers, libraries, wxHaskell, OpenGl for Haskell, > > ect... Like how Visual basic or Netbeans are. > > > > > > A few more questions: > > Is there an IDE? > > If not, is there some program that will open Haskell files, edit them, > > and be able to run them without any Terminal usage? > > Is there an official forum for Haskell? > > > > > > If Haskell had individual platform install packages installing > > everything needed for Haskell without any hassle with a beginner > > friendly forum and website, it'd become probably as popular as Java or > > Vb.net. Is anything like this planned? > > > > > > > > > > Thanks, > > -Matt > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090801/f0bfdf30/attachment.html From apfelmus at quantentunnel.de Sun Aug 2 03:45:06 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Sun Aug 2 03:25:50 2009 Subject: [Haskell-beginners] Re: Haskell OpenGL trouble In-Reply-To: <2717745e0908011902o4a3c4955ydd14141c7ac73ff0@mail.gmail.com> References: <2717745e0908011902o4a3c4955ydd14141c7ac73ff0@mail.gmail.com> Message-ID: Matt f wrote: > I am currently running Mac OS 10.5.7, and I have install many Haskell files, > compiled a bouncing ball example, fixed the enableGUI bug, tried an IDE, and > have started installing graphics libraries. > I am using Cabal in the terminal to install what I need, though whenever I > try to install opengl or a package of opengl; it comes up with an error. > > Macintosh-2:opengl matthew$ sudo cabal install > Resolving dependencies... > Configuring OpenGLRaw-1.0.1.0... > cabal: Missing dependency on a foreign library: > * Missing C library: GL > This problem can usually be solved by installing the system package that > provides this library (you may need the "-dev" version). If the library is > already installed but in a non-standard location then you can use the flags > --extra-include-dirs= and --extra-lib-dirs= to specify where it is. > cabal: Error: some packages failed to install: > GLURaw-1.0.0.0 depends on OpenGLRaw-1.0.1.0 which failed to install. > OpenGL-2.3.0.0 depends on OpenGLRaw-1.0.1.0 which failed to install. > OpenGLRaw-1.0.1.0 failed during the configure step. The exception was: > exit: ExitFailure 1 > Macintosh-2:opengl matthew$ > > It appears that I have zoned onto the bit that's causing all this mess, I'm > missing a C library: GL. OpenGL is installed on MacOS X by default; it looks like the .cabal file is missing a -framework OpenGL flag or similar. Write an email to the package maintainer, listed on http://hackage.haskell.org/package/OpenGLRaw Regards, apfelmus -- http://apfelmus.nfshost.com From hjgtuyl at chello.nl Sun Aug 2 07:38:38 2009 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Sun Aug 2 07:19:36 2009 Subject: [Haskell-beginners] All-in-one package? In-Reply-To: <2db78cee0908012050r622a588fm9b02b6f73ba9e76a@mail.gmail.com> References: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> <1249179279.3560.8.camel@TotaX> <2db78cee0908012050r622a588fm9b02b6f73ba9e76a@mail.gmail.com> Message-ID: On Sun, 02 Aug 2009 05:50:53 +0200, Kyle Murphy wrote: > (in my case I'm running XP 64 bit which apparently does not play nice > with the wxHaskell library as as soon as I mouse over any wxWidget > objects it crashes with a seg fault) Does this happen with a compiled program or only in GHCi? -- Regards, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- From orclev at gmail.com Sun Aug 2 16:04:34 2009 From: orclev at gmail.com (Kyle Murphy) Date: Sun Aug 2 15:45:29 2009 Subject: [Haskell-beginners] All-in-one package? In-Reply-To: References: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> <1249179279.3560.8.camel@TotaX> <2db78cee0908012050r622a588fm9b02b6f73ba9e76a@mail.gmail.com> Message-ID: <2db78cee0908021304r525c609dtc7acf4771159ab20@mail.gmail.com> Both. I just ran the BouncingBalls.hs example included with wxHaskell-0.11.0 and it seg. faulted in both GHCi and the compiled exe with the message: Segmentation fault/access violation in generated code This is with GHC-6.10.1, and wxHaskell-0.11.0. Looking at the GHC and wxHaskell pages I notice that both GHC and wxHaskell are a few minor releases out of date, so I'm going to download the latest versions on my windows box and see if that takes care of the issues. On Sun, Aug 2, 2009 at 7:38 AM, Henk-Jan van Tuyl wrote: > On Sun, 02 Aug 2009 05:50:53 +0200, Kyle Murphy wrote: > > (in my case I'm running XP 64 bit which apparently does not play nice with >> the wxHaskell library as as soon as I mouse over any wxWidget objects it >> crashes with a seg fault) >> > > Does this happen with a compiled program or only in GHCi? > > -- > Regards, > Henk-Jan van Tuyl > > > -- > http://functor.bamikanarie.com > http://Van.Tuyl.eu/ > -- > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090802/1b066867/attachment.html From orclev at gmail.com Sun Aug 2 16:19:03 2009 From: orclev at gmail.com (Kyle Murphy) Date: Sun Aug 2 15:59:57 2009 Subject: [Haskell-beginners] All-in-one package? In-Reply-To: <2db78cee0908021304r525c609dtc7acf4771159ab20@mail.gmail.com> References: <2717745e0908011908w1115142dve38d737bc378b034@mail.gmail.com> <1249179279.3560.8.camel@TotaX> <2db78cee0908012050r622a588fm9b02b6f73ba9e76a@mail.gmail.com> <2db78cee0908021304r525c609dtc7acf4771159ab20@mail.gmail.com> Message-ID: <2db78cee0908021319y46708d34w1dd28a84de8fd841@mail.gmail.com> Just installed the latest versions of GHC and wxHaskell and that seems to have cleared up the seg faults. Seeing some odd behavior where it claims it can't find some dlls (cleared up one by copying the dll out of the system32 directory into the directory the exe is in which strictly speaking should not have been necessary), but I suspect I may just need to reboot or something. The good news is, the sample programs appear to run more or less correctly, and even when they error off trying to load some shared libraries they don't seg fault and continue to function to the best of their ability, which is really all you can ask of a program. On Sun, Aug 2, 2009 at 4:04 PM, Kyle Murphy wrote: > Both. I just ran the BouncingBalls.hs example included with > wxHaskell-0.11.0 and it seg. faulted in both GHCi and the compiled exe with > the message: > Segmentation fault/access violation in generated code > > This is with GHC-6.10.1, and wxHaskell-0.11.0. > > Looking at the GHC and wxHaskell pages I notice that both GHC and wxHaskell > are a few minor releases out of date, so I'm going to download the latest > versions on my windows box and see if that takes care of the issues. > > > On Sun, Aug 2, 2009 at 7:38 AM, Henk-Jan van Tuyl wrote: > >> On Sun, 02 Aug 2009 05:50:53 +0200, Kyle Murphy wrote: >> >> (in my case I'm running XP 64 bit which apparently does not play nice >>> with the wxHaskell library as as soon as I mouse over any wxWidget objects >>> it crashes with a seg fault) >>> >> >> Does this happen with a compiled program or only in GHCi? >> >> -- >> Regards, >> Henk-Jan van Tuyl >> >> >> -- >> http://functor.bamikanarie.com >> http://Van.Tuyl.eu/ >> -- >> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090802/52f4a3a8/attachment.html From matthewjwilliams1 at googlemail.com Mon Aug 3 15:57:41 2009 From: matthewjwilliams1 at googlemail.com (Matthew J. Williams) Date: Mon Aug 3 15:38:33 2009 Subject: [Haskell-beginners] The Haskell IRC Channel Message-ID: <4a774132.0508d00a.75fa.3105@mx.google.com> Dear all, Does the list recommend a particular TUI IRC client for windows? Apologies for the off topic post. Sincerely, MJW From builes.adolfo at googlemail.com Mon Aug 3 15:51:51 2009 From: builes.adolfo at googlemail.com (builes.adolfo@googlemail.com) Date: Mon Aug 3 22:11:53 2009 Subject: [Haskell-beginners] Trying to read a bitmap with hOpenGL Message-ID: <0016e6454006ea746204704219a8@google.com> Hi All, I have been following an OpenGL book which has its examples in cpp, but using haskell instead. I have a problem when trying to read a bitmap, I haven't managed to render the file to the buffer, I did a little parser based on the one in RWH for the bmp file, and apparently everything seems to work well, but when I call drawPixels I don't get a clear image. The code that I'm using is here : http://gist.github.com/160787 What am I doing wrong ? Thanks in advance for any help. abuiles -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090803/27660a84/attachment.html From toby.murray at comlab.ox.ac.uk Tue Aug 4 07:36:07 2009 From: toby.murray at comlab.ox.ac.uk (Toby Murray) Date: Tue Aug 4 07:16:56 2009 Subject: [Haskell-beginners] Transforming (State s a) to (StateT s m a) Message-ID: Hi all, Am very new to Haskell, apologies in advance. Suppose I have a transformer A of type State s a. Suppose I have other state transformers of type StateT s m a. These are similar to the first kind but e.g. might throw errors or perform IO or whatever. I can manually convert A to be of the second kind as follows: -- | Used to invoke a "pure" state transformer -- from a context in which other effects may occur. pure :: (Monad m) => State s a -> StateT s m a pure func = StateT (\arg -> (return (runState func arg))) This seems like something one might want to do often. For instance, I might have a state type that I want to operate on, call it System. Then type PureSystemTransformer a = State System a defines a type for "pure" System transformers that return results of type a. However, other system transformers might need to throw errors. So I might define type SystemTransformer a e = StateT System (Either e) a for the type of system transformers that return results of type a or throw errors of type e. 'pure' is then used to convert a PureSystemTransformer to a SystemTransformer. I wonder whether there is something in the standard libraries that achieves the same thing as 'pure' above. i.e. Is there a more standard way to do this? Cheers Toby From gale at sefer.org Tue Aug 4 09:09:32 2009 From: gale at sefer.org (Yitzchak Gale) Date: Tue Aug 4 08:50:42 2009 Subject: [Haskell-beginners] Transforming (State s a) to (StateT s m a) In-Reply-To: References: Message-ID: <2608b8a80908040609xa8400d4g8d64cf92d74e1377@mail.gmail.com> Hi Toby, Toby Murray wrote: > Suppose I have a transformer A of type State s a... > Suppose I have other state transformers of type StateT s m a... > I can manually convert A to be of the second kind as follows... > pure :: (Monad m) => State s a -> StateT s m a > pure func = StateT (\arg -> (return (runState func arg))) Yes, this does come up from time to time. It could be useful to give it a standard name in the libraries. But "pure" is not a good name - that is firmly entrenched to mean other important things in Control.Applicative and Control.Arrow. Perhaps liftT? liftT :: (Monad m) => State s a -> StateT s m a liftT (State f) = StateT $ return . f You can submit your proposal by following this procedure: http://www.haskell.org/haskellwiki/Library_submissions Regards, Yitz From bugfact at gmail.com Tue Aug 4 11:54:15 2009 From: bugfact at gmail.com (Peter Verswyvelen) Date: Tue Aug 4 11:35:07 2009 Subject: [Haskell-beginners] Trying to read a bitmap with hOpenGL In-Reply-To: <0016e6454006ea746204704219a8@google.com> References: <0016e6454006ea746204704219a8@google.com> Message-ID: You didn't provide the smiley.bmp image, so I made my own 24-bit bitmap. When loading it and printing the width/height in your bmp loader, I get twice a zero, so your loader seems incorrect. I don't have the time to dig deeper into your loader function, but maybe you can find some inspiration using this code: http://code.haskell.org/ANUPlot/ANUPlot-HEAD/ A BMP loader can be found in http://code.haskell.org/ANUPlot/ANUPlot-HEAD/src/Graphics/Plot/ Cheers, Peter On Mon, Aug 3, 2009 at 9:51 PM, wrote: > Hi All, > > I have been following an OpenGL book which has its examples in cpp, but > using haskell instead. I have a problem when trying to read a bitmap, I > haven't managed to render the file to the buffer, I did a little parser > based on the one in RWH for the bmp file, and apparently everything seems to > work well, but when I call drawPixels I don't get a clear image. The code > that I'm using is here : > http://gist.github.com/160787 > > What am I doing wrong ? > > > > Thanks in advance for any help. > > abuiles > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090804/9091633d/attachment-0001.html From mpm at alumni.caltech.edu Tue Aug 4 19:07:22 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Tue Aug 4 18:48:37 2009 Subject: [Haskell-beginners] am I wording this right? Message-ID: <4A78BF2A.4000502@alumni.caltech.edu> Is this the right way of saying what I'm trying to say? "Functor is a typeclass of type constructors which take one argument." Thanks, Mike From bugfact at gmail.com Tue Aug 4 20:15:44 2009 From: bugfact at gmail.com (Peter Verswyvelen) Date: Tue Aug 4 19:56:32 2009 Subject: [Haskell-beginners] am I wording this right? In-Reply-To: <4A78BF2A.4000502@alumni.caltech.edu> References: <4A78BF2A.4000502@alumni.caltech.edu> Message-ID: That sound okay to me. Usually when we have type constructor "T a" and an "instance Functor T where..." we just say that "T is a functor" Note that the signature of a type constructor is called the "kind" of the type constructor. For example, the following code data NotSoKind = X instance Functor NotSoKind where would give the error: Kind mis-match Expected kind `* -> *', but `NotSoKind' has kind `*' In the instance declaration for `Functor NotSoKind' and instance Functor (,) where gives the error (,)' is not applied to enough type arguments Expected kind `* -> *', but `(,)' has kind `* -> * -> *' In the instance declaration for `Functor (,)' Note however that the following is correct: instance Functor ((,) a) where fmap f (x,y) = (x, f y) and even: instance Functor ((->) a) where fmap f g = f . g You can ask GHCi to show the kind of a type constructor: :kind (,) (,) :: * -> * -> * :kind ((,) 1) ((,) 1) :: * -> * :kind Char * On Wed, Aug 5, 2009 at 1:07 AM, Michael P Mossey wrote: > > Is this the right way of saying what I'm trying to say? > > "Functor is a typeclass of type constructors which take one argument." > > Thanks, > Mike > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From mpm at alumni.caltech.edu Tue Aug 4 20:25:04 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Tue Aug 4 20:05:54 2009 Subject: [Haskell-beginners] am I wording this right? In-Reply-To: References: <4A78BF2A.4000502@alumni.caltech.edu> Message-ID: <4A78D160.3050606@alumni.caltech.edu> Peter Verswyvelen wrote: > > Note however that the following is correct: > > instance Functor ((,) a) where > fmap f (x,y) = (x, f y) > > and even: > > instance Functor ((->) a) where > fmap f g = f . g > Thanks. What's curious to me about these instances is that they have a type variable a which is never referenced in the definition. Is there ever a case in which you would refer to the type variable 'a' somewhere in the definition of an instance? I know that the types of the "member functions" of the instance are given in the class definition, so there is no place to put a type definition in the instance, I don't think. Thanks, Mike From bugfact at gmail.com Tue Aug 4 20:39:07 2009 From: bugfact at gmail.com (Peter Verswyvelen) Date: Tue Aug 4 20:19:55 2009 Subject: [Haskell-beginners] am I wording this right? In-Reply-To: <4A78D160.3050606@alumni.caltech.edu> References: <4A78BF2A.4000502@alumni.caltech.edu> <4A78D160.3050606@alumni.caltech.edu> Message-ID: On Wed, Aug 5, 2009 at 2:25 AM, Michael P Mossey wrote: > Peter Verswyvelen wrote: >> Note however that the following is correct: >> >> instance Functor ((,) a) where >> ? ?fmap f (x,y) = (x, f y) >> > > Thanks. What's curious to me about these instances is that they have a type > variable a which is never referenced in the definition. > > Is there ever a case in which you would refer to the type variable 'a' > somewhere in the definition of an instance? I know that the types of the > "member functions" of the instance are given in the class definition, so > there is no place to put a type definition in the instance, I don't think. Good question, I don't know. You can use it to add constraints, e.g. instance Show a => Functor ((,) a) where fmap f (x,y) = (x, f y) but the "a" type does not seem to be available in the definitions, it's scope seems to be limited, e.g. instance Functor ((,) a) where fmap f (x,y) = (x::a, f y) doesn't compile. But I'm just guessing here, don't know the details :-( > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From mpm at alumni.caltech.edu Tue Aug 4 21:02:29 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Tue Aug 4 20:43:34 2009 Subject: [Haskell-beginners] fmap fmap Message-ID: <4A78DA25.7070106@alumni.caltech.edu> How does one write fmap (fmap (*2)) xs without parenthesis? (Using . and $ instead.) I don't really understand . and $ well enough I guess. I tried a bunch of stuff but nothing worked. -Mike From felipe.lessa at gmail.com Tue Aug 4 21:16:08 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Tue Aug 4 20:57:00 2009 Subject: [Haskell-beginners] fmap fmap In-Reply-To: <4A78DA25.7070106@alumni.caltech.edu> References: <4A78DA25.7070106@alumni.caltech.edu> Message-ID: <20090805011608.GA11828@kira.casa> On Tue, Aug 04, 2009 at 06:02:29PM -0700, Michael P Mossey wrote: > How does one write > > fmap (fmap (*2)) xs > > without parenthesis? (Using . and $ instead.) fmap (fmap (*2)) xs flip fmap xs (fmap (*2)) flip fmap xs $ fmap (*2) flip fmap xs $ fmap (\x -> (*) x 2) flip fmap xs $ fmap (\x -> flip (*) 2 x) flip fmap xs $ fmap (flip (*) 2) flip fmap xs $ fmap $ flip (*) 2 -- Felipe. From ml at isaac.cedarswampstudios.org Tue Aug 4 21:17:56 2009 From: ml at isaac.cedarswampstudios.org (Isaac Dupree) Date: Tue Aug 4 20:58:55 2009 Subject: [Haskell-beginners] fmap fmap In-Reply-To: <4A78DA25.7070106@alumni.caltech.edu> References: <4A78DA25.7070106@alumni.caltech.edu> Message-ID: <4A78DDC4.90005@isaac.cedarswampstudios.org> Michael P Mossey wrote: > How does one write > > fmap (fmap (*2)) xs > > without parenthesis? (Using . and $ instead.) I don't think it's possible? "(fmap . fmap) (*2) xs" might be something you like, though. (also, the parentheses from (*2) are section syntax and can't just be removed in the same way) -Isaac From jason.dusek at gmail.com Tue Aug 4 21:49:38 2009 From: jason.dusek at gmail.com (Jason Dusek) Date: Tue Aug 4 21:30:25 2009 Subject: [Haskell-beginners] fmap fmap In-Reply-To: <4A78DA25.7070106@alumni.caltech.edu> References: <4A78DA25.7070106@alumni.caltech.edu> Message-ID: <42784f260908041849p53e38289n91ea0506bb51bfbf@mail.gmail.com> 2009/08/04 Michael P Mossey : > fmap (fmap (*2)) xs Not exactly what you asked for: fmap (*2) `fmap` xs Operator sections -- the `(*2)` -- require parens. Using backticks helps you clean up parenthesis. -- Jason Dusek From jason.dusek at gmail.com Tue Aug 4 21:54:14 2009 From: jason.dusek at gmail.com (Jason Dusek) Date: Tue Aug 4 21:35:04 2009 Subject: [Haskell-beginners] am I wording this right? In-Reply-To: <4A78D160.3050606@alumni.caltech.edu> References: <4A78BF2A.4000502@alumni.caltech.edu> <4A78D160.3050606@alumni.caltech.edu> Message-ID: <42784f260908041854m7fa5a3a0x94f415556a189a31@mail.gmail.com> 2009/08/04 Michael P Mossey : > Is there ever a case in which you would refer to the type > variable 'a' somewhere in the definition of an instance? When using overloaded functions to write the instance -- for example, `fmap` or `mappend` -- you might place type signatures on them to disambiguate. -- Jason Dusek From tonymorris at gmail.com Tue Aug 4 23:29:51 2009 From: tonymorris at gmail.com (Tony Morris) Date: Tue Aug 4 23:10:51 2009 Subject: [Haskell-beginners] fmap fmap In-Reply-To: <4A78DA25.7070106@alumni.caltech.edu> References: <4A78DA25.7070106@alumni.caltech.edu> Message-ID: <4A78FCAF.4080604@gmail.com> Michael P Mossey wrote: > How does one write > > fmap (fmap (*2)) xs > > without parenthesis? (Using . and $ instead.) > > I don't really understand . and $ well enough I guess. I tried a bunch > of stuff but nothing worked. > > -Mike > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > fmap . fmap $ (*2) or perhaps: (fmap . fmap) (*2) -- Tony Morris http://tmorris.net/ From djeinbrum at yahoo.co.uk Thu Aug 6 14:21:19 2009 From: djeinbrum at yahoo.co.uk (Daniel Everett) Date: Thu Aug 6 14:02:03 2009 Subject: [Haskell-beginners] Getting the Takusen example code to compile -failed import problem In-Reply-To: <125EACD0CAE4D24ABDB4D148C4593DA911026167@GBLONXMB02.corp.amvescap.net> Message-ID: <720711.1132.qm@web23007.mail.ird.yahoo.com> > > > > I have Takusen 0.8.5 installed and I'm trying to build > the > > code found at > > http://darcs.haskell.org/takusen/doc/html/Database-Enumerator. > html using ghc 6.10.3.? This always fails with the > error:? > > > > Could not find module `Database.Oracle.Enumerator' > > > > The analogous errors are encountered if I substitute > Oracle > > with Sqlite, Postgresql or ODBC.? Any ideas how > to resolve this? > > OK, this now compiles thanks to (a) hacking Setup.hs to refer to odbc_config rather than odbcconf and (b) unregistering the user packages with ghc-pkg --user unregister Takusen. However, if I then create a table in MySQL with: create table dummy (id int primary key); and then use a reduced form of the example code: import Database.Enumerator import Database.ODBC.Enumerator import Control.Monad.Trans(liftIO) query1Iteratee :: (Monad m) => Int -> String -> Double -> IterAct m [(Int, String, Double)] query1Iteratee a b c accum = result' ((a, b, c):accum) main :: IO () main = do withSession (connect "DSN=test") ( do -- simple query, returning reversed list of rows. r <- doQuery (sql "select id from dummy") query1Iteratee [] liftIO(putStrLn(show r)) ) then I get the error: fromUTF8Ptr: zero byte found in string as position 8 Is there any thing wrong with the above code? Also, what does liftIO actually do? Its documentation at http://cvs.haskell.org/Hugs/pages/libraries/mtl/Control-Monad-Trans.html does not actually say! The link at the top of that page is dead as well. Regards, Daniel From Alistair.Bayley at invesco.com Fri Aug 7 03:47:48 2009 From: Alistair.Bayley at invesco.com (Bayley, Alistair) Date: Fri Aug 7 03:28:30 2009 Subject: [Haskell-beginners] Getting the Takusen example code to compile -failed import problem In-Reply-To: <720711.1132.qm@web23007.mail.ird.yahoo.com> References: <125EACD0CAE4D24ABDB4D148C4593DA911026167@GBLONXMB02.corp.amvescap.net> <720711.1132.qm@web23007.mail.ird.yahoo.com> Message-ID: <125EACD0CAE4D24ABDB4D148C4593DA9110261C1@GBLONXMB02.corp.amvescap.net> > -----Original Message----- > From: Daniel Everett [mailto:djeinbrum@yahoo.co.uk] > > OK, this now compiles thanks to (a) hacking Setup.hs to refer > to odbc_config rather than odbcconf and (b) unregistering the > user packages with ghc-pkg --user unregister Takusen. Please create a darcs patch for Setup.hs and send it to me. IIRC, you were on Linux? I'm not sure if Takusen has been tested under Linux. We've receieved patches for OSX, Oleg uses BSD, and I have Windows, so it would be useful to get patches for Linux installs too. > create table dummy (id int primary key); > query1Iteratee :: (Monad m) => Int -> String -> Double -> > IterAct m [(Int, String, Double)] > query1Iteratee a b c accum = result' ((a, b, c):accum) > r <- doQuery (sql "select id from dummy") query1Iteratee [] > liftIO(putStrLn(show r)) > ) > fromUTF8Ptr: zero byte found in string as position 8 > > Is there any thing wrong with the above code? Yes. The iteratee function expects three columns in the result-set (with types Int, String, and Double, in that order), but your query only provides one column (dummy, of type Int). There is the beginnings of some code in a couple of the backends to validate the iteratee against the actual result-set, but it's nowhere near complete. So if you have a mismatch between iteratee and query, then you are likely to get marshaling erros and/or garbage. Note that it's OK to have a result-set return more columns than the iteratee consumes, but obviously to converse cannnot work. > Also, what does liftIO actually do? The monad that your database session is in is a ReaderT wrapper over IO. In order to perform actions that run in the IO monad, you need to "lift" them. http://www.haskell.org/haskellwiki/Monad_Transformers_Explained Alistair ***************************************************************** Confidentiality Note: The information contained in this message, and any attachments, may contain confidential and/or privileged material. It is intended solely for the person(s) or entity to which it is addressed. Any review, retransmission, dissemination, or taking of any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you received this in error, please contact the sender and delete the material from any computer. ***************************************************************** From jack at realmode.com Sat Aug 8 16:01:34 2009 From: jack at realmode.com (I. J. Kennedy) Date: Sat Aug 8 15:42:12 2009 Subject: [Haskell-beginners] Does this function already exist in one of the standard modules? Message-ID: <1008bfc90908081301i5e984afdt8b45c9cf40f28dec@mail.gmail.com> Does this function already exist in one of the standard modules? It computes f(f(f(...f(x))). I suspect it is a common function, but I can't find it, even using Hoogle. applyMany :: Int -> (a -> a) -> a -> a applyMany 0 f x = x applyMany n f x = applyMany (n-1) f (f x) From felipe.lessa at gmail.com Sat Aug 8 16:38:23 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sat Aug 8 16:19:05 2009 Subject: [Haskell-beginners] Does this function already exist in one of the standard modules? In-Reply-To: <1008bfc90908081301i5e984afdt8b45c9cf40f28dec@mail.gmail.com> References: <1008bfc90908081301i5e984afdt8b45c9cf40f28dec@mail.gmail.com> Message-ID: <20090808203823.GA6967@kira.casa> On Sat, Aug 08, 2009 at 03:01:34PM -0500, I. J. Kennedy wrote: > Does this function already exist in one of the standard modules? > It computes f(f(f(...f(x))). I suspect it is a common function, but I > can't find it, even using Hoogle. > > applyMany :: Int -> (a -> a) -> a -> a > applyMany 0 f x = x > applyMany n f x = applyMany (n-1) f (f x) applyMany n f x = iterate f x !! n -- Felipe. From daniel.is.fischer at web.de Sat Aug 8 16:54:15 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Aug 8 16:35:44 2009 Subject: [Haskell-beginners] Does this function already exist in one of the standard modules? In-Reply-To: <1008bfc90908081301i5e984afdt8b45c9cf40f28dec@mail.gmail.com> References: <1008bfc90908081301i5e984afdt8b45c9cf40f28dec@mail.gmail.com> Message-ID: <200908082254.15541.daniel.is.fischer@web.de> Am Samstag 08 August 2009 22:01:34 schrieb I. J. Kennedy: > Does this function already exist in one of the standard modules? > It computes f(f(f(...f(x))). I suspect it is a common function, but I > can't find it, even using Hoogle. > > applyMany :: Int -> (a -> a) -> a -> a > applyMany 0 f x = x > applyMany n f x = applyMany (n-1) f (f x) Not directly, I think. But we have iterate :: (a -> a) -> a -> [a] iterate f x = x:iterate f (f x) so applyMany n f x = iterate f x !! n Most of the time you either need different numbers of iterations for the same starting value, then iterate is what you want, or the same number of iterations for different values, then you use something like let g = foldl (.) id (replicate n f) in ... From jack at realmode.com Sat Aug 8 18:17:46 2009 From: jack at realmode.com (I. J. Kennedy) Date: Sat Aug 8 17:58:22 2009 Subject: [Haskell-beginners] Does this function already exist in one of the standard modules? In-Reply-To: <20090808203823.GA6967@kira.casa> References: <1008bfc90908081301i5e984afdt8b45c9cf40f28dec@mail.gmail.com> <20090808203823.GA6967@kira.casa> Message-ID: <1008bfc90908081517l7b690412pc58fd3e50bf96478@mail.gmail.com> I'm surprised there's no standard function for this. Using iterate f x !! n is ok I suppose, but: If I try to calculate the millionth fibonacci number like this fibStep (a,b) = (b,a+b) iterate fibStep (0,1) !! 1000000 I get a stack overflow, but if I use applyMany applyMany 1000000 fibStep (0,1) it works. On Sat, Aug 8, 2009 at 3:38 PM, Felipe Lessa wrote: > On Sat, Aug 08, 2009 at 03:01:34PM -0500, I. J. Kennedy wrote: >> Does this function already exist in one of the standard modules? >> It computes ?f(f(f(...f(x))). ?I suspect it is a common function, but I >> can't find it, even using Hoogle. >> >> ? applyMany :: Int -> (a -> a) -> a -> a >> ? applyMany 0 f x = x >> ? applyMany n f x = applyMany (n-1) f (f x) > > applyMany n f x = iterate f x !! n > > -- > Felipe. > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From daniel.is.fischer at web.de Sun Aug 9 10:02:57 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Aug 9 09:46:19 2009 Subject: [Haskell-beginners] Does this function already exist in one of the standard modules? In-Reply-To: <1008bfc90908081517l7b690412pc58fd3e50bf96478@mail.gmail.com> References: <1008bfc90908081301i5e984afdt8b45c9cf40f28dec@mail.gmail.com> <20090808203823.GA6967@kira.casa> <1008bfc90908081517l7b690412pc58fd3e50bf96478@mail.gmail.com> Message-ID: <200908091602.58046.daniel.is.fischer@web.de> Am Sonntag 09 August 2009 00:17:46 schrieb I. J. Kennedy: > I'm surprised there's no standard function for this. > Using iterate f x !! n is ok I suppose, but: > > If I try to calculate the millionth fibonacci number like this > > fibStep (a,b) = (b,a+b) > iterate fibStep (0,1) !! 1000000 > > I get a stack overflow, but if I use applyMany > > applyMany 1000000 fibStep (0,1) > > it works. > I can't reproduce that, I get a stack overflow for both (as it should be*). Both work, with about the same performance, if I use stricter versions: sfibStep :: (Integer,Integer) -> (Integer,Integer) sfibStep (a,b) = let c = a+b in c `seq` (b,c) applyMany' :: Int -> (a -> a) -> a -> a applyMany' 0 _ x = x applyMany' n f x = applyMany (n-1) f $! (f x) iterate' :: (a -> a) -> a -> [a] iterate' f x = x:(iterate' f $! f x) With the lazy original fibStep, both strict versions (applyMany' and iterate') work, but take much longer (roughly 20 times). [*] Both, iterate and the original applyMany build a thunk of one million nested function calls, that needs a larger stack than the default. From fbrubacher at gmail.com Sun Aug 9 12:39:08 2009 From: fbrubacher at gmail.com (Federico Brubacher) Date: Sun Aug 9 12:19:44 2009 Subject: [Haskell-beginners] fmap fmap In-Reply-To: <4A78FCAF.4080604@gmail.com> References: <4A78DA25.7070106@alumni.caltech.edu> <4A78FCAF.4080604@gmail.com> Message-ID: <206c53410908090939r1f8f37c9i43a2692be4713046@mail.gmail.com> fmap . fmap is close to applicative ? is it possible to do applicative instead of combining 2 fmaps ? Thanks On Wed, Aug 5, 2009 at 12:29 AM, Tony Morris wrote: > Michael P Mossey wrote: > > How does one write > > > > fmap (fmap (*2)) xs > > > > without parenthesis? (Using . and $ instead.) > > > > I don't really understand . and $ well enough I guess. I tried a bunch > > of stuff but nothing worked. > > > > -Mike > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > > fmap . fmap $ (*2) > > or perhaps: > > (fmap . fmap) (*2) > > -- > Tony Morris > http://tmorris.net/ > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Federico Brubacher www.fbrubacher.com Colonial Duty Free Shop www.colonial.com.uy -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090809/38c455d7/attachment.html From mpm at alumni.caltech.edu Sun Aug 9 15:31:47 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sun Aug 9 15:12:24 2009 Subject: [Haskell-beginners] some insights into functional programming Message-ID: <4A7F2423.1070204@alumni.caltech.edu> I'm starting to figure out a few things that I didn't "get" about functional programming and monads. I wanted to explain them. I'm not looking for a particular response to this post, other than any elaboration that seems natural. There is an exercise here working with the trivial monad W: Write a function g :: W a -> W a -> W a such that g (W x) (W y) = W (x+y) except don't use pattern matching, but >>= instead. The answer is g mx my = mx >>= (\x -> my >>= \y -> W (x+y)) There are a couple things here that threw me off. One is that I didn't expect 'my' to be available inside the first lambda. I somehow thought of lambda as isolated, sealed-off from the rest of the universe. But they aren't. I believe this is the concept of closures, or related to it? Secondly, I didn't expect >>= to be available inside the lambda. This is related to the mistaken conception of >>= as a procedural statement rather than an expression. In Python, where I have previously encountered lambdas, no statements are allowed inside lambdas. Of course, >>= is actually an expression and you can put any expression to the right of a lambda ->. Maybe these are typical beginner misconceptions, or maybe they have more to do with coming from Python and complete beginners actually find it more natural. Mike From mpm at alumni.caltech.edu Sun Aug 9 16:52:40 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sun Aug 9 16:33:18 2009 Subject: [Haskell-beginners] unit tests Message-ID: <5917.208.57.251.240.1249851160.squirrel@mail.alumni.caltech.edu> As I write Haskell code I find myself needing to write test code. If this test code were organized and documented, I could probably call it a set of unit tests. I'm trying to find some convention for naming functions and variables used in unit testing, deciding on location (in same module or a second module? same directory or sub-directory?), etc. Are there any Haskell community conventions? Thanks, Mike From haskell at colquitt.org Sun Aug 9 17:52:23 2009 From: haskell at colquitt.org (John Dorsey) Date: Sun Aug 9 17:32:56 2009 Subject: [Haskell-beginners] unit tests In-Reply-To: <5917.208.57.251.240.1249851160.squirrel@mail.alumni.caltech.edu> References: <5917.208.57.251.240.1249851160.squirrel@mail.alumni.caltech.edu> Message-ID: <20090809215223.GF14826@colquitt.org> Michael, > As I write Haskell code I find myself needing to write test code. If this > test code were organized and documented, I could probably call it a set of > unit tests. I'm trying to find some convention for naming functions and > variables used in unit testing, deciding on location (in same module or a > second module? same directory or sub-directory?), etc. Are there any > Haskell community conventions? quickcheck at least has the convention of calling testable properties by names starting with 'prop_'. I think it's common to include them within a package, but they're generally not compiled and run by default. Cabal has a way to hook your tests in so that 'cabal test ' does the right thing, but I don't remember, and my cabal fu isn't very strong. I don't think there's any consensus on where within your package to put them; you could put them in a test/ directory, or do anything that makes sense within your project. John From haskell at colquitt.org Sun Aug 9 18:05:21 2009 From: haskell at colquitt.org (John Dorsey) Date: Sun Aug 9 17:45:54 2009 Subject: [Haskell-beginners] some insights into functional programming In-Reply-To: <4A7F2423.1070204@alumni.caltech.edu> References: <4A7F2423.1070204@alumni.caltech.edu> Message-ID: <20090809220521.GG14826@colquitt.org> Michael, > g mx my = mx >>= (\x -> my >>= \y -> W (x+y)) > > There are a couple things here that threw me off. One is that I didn't > expect 'my' to be available inside the first lambda. I somehow thought of > lambda as isolated, sealed-off from the rest of the universe. But they > aren't. I believe this is the concept of closures, or related to it? Yes! You're spot on; 'my' is available precisely because closures encapsulate the part of the surrounding environment that's referenced by bound variables. > Secondly, I didn't expect >>= to be available inside the lambda. This is > related to the mistaken conception of >>= as a procedural statement > rather than an expression. In Python, where I have previously encountered > lambdas, no statements are allowed inside lambdas. Of course, >>= is > actually an expression and you can put any expression to the right of a > lambda ->. With all due respect to Python (a language I like but no longer use), it's no place to develop any intuition about lambdas. Python's lambda is an attempt to incorporate some of the syntactic benefit of anonymous functions while refusing them any real meaning or importance. > Maybe these are typical beginner misconceptions, or maybe they have more > to do with coming from Python and complete beginners actually find it > more natural. As you can probably guess, I think it's more the latter. But I can't say first-hand because I dabbled in dozens of languages before Haskell, and I got my intuition for lambda from scheme. I wish I'd learned them in Haskell though, because with purity they're more elegant. Cheers, John From tom.davie at gmail.com Sun Aug 9 19:52:49 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Sun Aug 9 19:33:23 2009 Subject: [Haskell-beginners] unit tests In-Reply-To: <5917.208.57.251.240.1249851160.squirrel@mail.alumni.caltech.edu> References: <5917.208.57.251.240.1249851160.squirrel@mail.alumni.caltech.edu> Message-ID: <00E32AC4-AA79-4568-B3CF-DB1341DAA635@gmail.com> On 9 Aug 2009, at 22:52, Michael Mossey wrote: > As I write Haskell code I find myself needing to write test code. If > this > test code were organized and documented, I could probably call it a > set of > unit tests. I'm trying to find some convention for naming functions > and > variables used in unit testing, deciding on location (in same module > or a > second module? same directory or sub-directory?), etc. Are there any > Haskell community conventions? Take a look at both QuickCheck and HUnit. Bob From adam at edea.se Sun Aug 9 21:07:44 2009 From: adam at edea.se (Adam Bergmark) Date: Sun Aug 9 20:48:34 2009 Subject: [Haskell-beginners] some insights into functional programming In-Reply-To: <4A7F2423.1070204@alumni.caltech.edu> References: <4A7F2423.1070204@alumni.caltech.edu> Message-ID: <608914D5-65B6-43FD-95C9-61825BEB68F4@edea.se> The reason my is available in the lambda \x -> my >>= \y -> W (x+y) has to do with scoping rules, Haskell (and almost all programming languages) use static scoping, meaning a variable defined in an outer function is available in the inner function, for instance, (\a -> \b - > (a,b)) 1 2 will evauate to (1,2) since a is bound to 1 in the outer lambda, and the inner one can refer to the outer one, if instead you write (\a -> \a -> (a,a)) 1 2 the result will be (2,2) since the innermost a will be used (no ambiguity here, but if shadowing is done by accident it can be hard to find the error). The book Structure and Interpretation of Computer Programs (freely available online) discusses this subject in detail. >>= is available inside the lambda for the same reason, >>= is imported into the modules namespace, and therefore available everewhere, unless a shadowing binding exists. I wouldn't say that this has anything to do with functional programming specifically. This also exists in Python i might add, you can read variables defined in an outer scope: >>> a = 1 >>> f() >>> def f(): ... return a ... >>> f() 1 The fact that most languages are scoped like this is nothing obvious, and like I said, Python is the same. I hope this helps! / Adam On Aug 9, 2009, at 9:31 PM, Michael Mossey wrote: > I'm starting to figure out a few things that I didn't "get" about > functional programming and monads. I wanted to explain them. I'm not > looking for a particular response to this post, other than any > elaboration that seems natural. > > There is an exercise here working with the trivial monad W: > > > > Write a function > g :: W a -> W a -> W a > > such that > g (W x) (W y) = W (x+y) > > except don't use pattern matching, but >>= instead. The answer is > > g mx my = mx >>= (\x -> my >>= \y -> W (x+y)) > > There are a couple things here that threw me off. One is that I > didn't expect 'my' to be available inside the first lambda. I > somehow thought of lambda as isolated, sealed-off from the rest of > the universe. But they aren't. I believe this is the concept of > closures, or related to it? > > Secondly, I didn't expect >>= to be available inside the lambda. > This is related to the mistaken conception of >>= as a procedural > statement rather than an expression. In Python, where I have > previously encountered lambdas, no statements are allowed inside > lambdas. Of course, >>= is actually an expression and you can put > any expression to the right of a lambda ->. > > Maybe these are typical beginner misconceptions, or maybe they have > more to do with coming from Python and complete beginners actually > find it more natural. > > Mike > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From mpm at alumni.caltech.edu Mon Aug 10 18:36:13 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Mon Aug 10 18:16:46 2009 Subject: [Haskell-beginners] some insights into functional programming In-Reply-To: <608914D5-65B6-43FD-95C9-61825BEB68F4@edea.se> References: <4A7F2423.1070204@alumni.caltech.edu> <608914D5-65B6-43FD-95C9-61825BEB68F4@edea.se> Message-ID: <4A80A0DD.50503@alumni.caltech.edu> Thanks for the ideas, Adam. I still have a few questions. Adam Bergmark wrote: > The reason my is available in the lambda \x -> my >>= \y -> W (x+y) has > to do with scoping rules, Haskell (and almost all programming languages) > use static scoping, meaning a variable defined in an outer function is > available in the inner function, for instance, (\a -> \b -> (a,b)) 1 2 > will evauate to (1,2) since a is bound to 1 in the outer lambda, and the > inner one can refer to the outer one, if instead you write (\a -> \a -> > (a,a)) 1 2 the result will be (2,2) since the innermost a will be used > (no ambiguity here, but if shadowing is done by accident it can be hard > to find the error). Because the lambda is executed by the implementation of >>=, doesn't the concept closure still apply? That value of 'my' has to "get into" the other routine. I am aware that other languages have closures, but in Python they are an advanced, rarely explored concept, so I haven't gotten a good intuition for them. (I don't mean to imply I've only programmed in Python---also Lisp and C++, but only to do boring things, never anything sophisticated from a CS point of view.) It's not that I don't understand the use of 'my'---it's just that it didn't occur to me at first. > The book Structure and Interpretation of Computer > Programs (freely available online) discusses this subject in detail. > > >>= is available inside the lambda for the same reason, >>= is imported > into the modules namespace, and therefore available everewhere, unless a > shadowing binding exists. > The problem is not that I didn't expect >>= to be outside the namespace. The problem is that I am still having to "unlearn" imperative concepts, so it was all too easy to think of >>= as an imperative concept, and in Python procedural statements are not allowed inside lambdas. Also, in the early stages of learning Haskell there are no monads used inside lambdas. So it's not that anyone told me I couldn't do it, just that it didn't occur to me the first time I saw the problem. There is no great revelation here, other than my own satisfaction at seeing a little deeper into the way things are done in Haskell, and finding these problems much easier after revisiting them (I didn't do anything Haskell for a couple months, and just came back to it). -Mike From k.srikanth.opensource at gmail.com Mon Aug 10 19:20:16 2009 From: k.srikanth.opensource at gmail.com (Srikanth K) Date: Mon Aug 10 19:00:46 2009 Subject: [Haskell-beginners] creating a complement for a given given test generator. Message-ID: Hi, I am trying to use the quickcheck to generate some test-data to test an api, along the lines of http://www.haskell.org/haskellwiki/QuickCheck_as_Test_Set_Generator. For the sake of example, I choose the following function to test data Result = Valid | Invalid api_under_test :: (Int,Int) -> Result api_under_test (x,y) | (x == 1) = Valid | otherwise = Invalid I had the following valid-generator which worked quite easily(trivial) validCombinations= [ (1,1), (1,2) ] validGen = elements validCombinations prop_valid_api_under_test = forAll validGen $ \xs -> (api_under_test xs) == (Valid) Now, I want to have a complement to state: forall tuples not in validCombinations, the api_under_test must return "Invalid". (i.e.) prop_invalid_api_under_test = forAll invalidGen $ \xs -> (api_under_test xs) == (Invalid) However, inspite of all googling, and reading the various docs including quickcheck, I am at loss on how I can elegantly define the "invalidGen" generator. One possible way I can think is to have a customized generator, that would generate two random numbers and then look up the tuple generated against the validCombinations list. However, I feel there just might be a better way of solving this. Any suggestion on how I should be trying to solve this. - Srikanth -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090810/00eb27b0/attachment.html From mpm at alumni.caltech.edu Mon Aug 10 20:08:16 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Mon Aug 10 19:48:55 2009 Subject: [Haskell-beginners] brief example of ZipList? Message-ID: <4A80B670.1000400@alumni.caltech.edu> Can someone give me a brief example using ZipList? I want to do something like z1 :: [Int -> Int] z1 = [succ,succ] z2 :: [Int] z2 = [1,2] z3 = z1 <*> z2 But don't know to get it to regard these as ZipLists and not regular lists. This is purely for learning purposes. No application in mind. -Mike From aslatter at gmail.com Mon Aug 10 20:55:34 2009 From: aslatter at gmail.com (Antoine Latter) Date: Mon Aug 10 20:36:06 2009 Subject: [Haskell-beginners] brief example of ZipList? In-Reply-To: <4A80B670.1000400@alumni.caltech.edu> References: <4A80B670.1000400@alumni.caltech.edu> Message-ID: <694519c50908101755n6de04134p47f57ab14ff248fa@mail.gmail.com> On Mon, Aug 10, 2009 at 7:08 PM, Michael P Mossey wrote: > Can someone give me a brief example using ZipList? I want to do something > like > > z1 :: [Int -> Int] > z1 = [succ,succ] > > z2 :: [Int] > z2 = [1,2] > > z3 = z1 <*> z2 > > But don't know to get it to regard these as ZipLists and not regular lists. > > This is purely for learning purposes. No application in mind. z3 = getZipList $ (ZipList z1) <*> (ZipList z2) Should do what you want. Does that make sense? Antoine From alexander.dunlap at gmail.com Mon Aug 10 22:08:25 2009 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Mon Aug 10 21:49:13 2009 Subject: [Haskell-beginners] creating a complement for a given given test generator. In-Reply-To: References: Message-ID: <57526e770908101908j15285e34l999b7e25f9831108@mail.gmail.com> On Mon, Aug 10, 2009 at 4:20 PM, Srikanth K wrote: > Hi, > ?? I am trying to use the quickcheck to generate some test-data to test an > api, along the lines of > http://www.haskell.org/haskellwiki/QuickCheck_as_Test_Set_Generator. > > For the sake of example, I choose the following function to test > > > data Result = Valid | Invalid > api_under_test :: (Int,Int) ->? Result > api_under_test (x,y) > ?? | (x == 1)? =?? Valid > ?? | otherwise =?Invalid > > > I had the following valid-generator which worked quite easily(trivial) > > validCombinations= [ (1,1), (1,2) ] > validGen = elements validCombinations > prop_valid_api_under_test = > ??? forAll validGen $ \xs -> > ???????? (api_under_test xs) == (Valid) > > Now, I want to have a complement to state: > ??? ?forall tuples not in validCombinations, the api_under_test must return > "Invalid".? (i.e.) > > prop_invalid_api_under_test = > ??? forAll invalidGen $ \xs -> > ??????? (api_under_test xs) == (Invalid) > > > > However, inspite of all? googling, and reading the various docs including > quickcheck, I am at loss on how I can elegantly define the "invalidGen" > generator.? One possible way I can think is to have a customized generator, > that would generate two random numbers and then look up the tuple generated > against the validCombinations list. > > However, I feel there just might be a better way of solving this. > > Any suggestion on how I should be trying to solve this. > > - Srikanth > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > The way I would do this is (untested) prop_invalid_api_under_test xs = not (xs `elem` validCombinations) ==> api_under_test xs = Invalid using the (==>) function from QuickCheck. Alex From magnus at therning.org Tue Aug 11 01:51:42 2009 From: magnus at therning.org (Magnus Therning) Date: Tue Aug 11 01:32:18 2009 Subject: [Haskell-beginners] some insights into functional programming In-Reply-To: <4A80A0DD.50503@alumni.caltech.edu> References: <4A7F2423.1070204@alumni.caltech.edu> <608914D5-65B6-43FD-95C9-61825BEB68F4@edea.se> <4A80A0DD.50503@alumni.caltech.edu> Message-ID: <4A8106EE.2060309@therning.org> Michael P Mossey wrote: > Thanks for the ideas, Adam. I still have a few questions. > > Adam Bergmark wrote: >> The reason my is available in the lambda \x -> my >>= \y -> W (x+y) has to >> do with scoping rules, Haskell (and almost all programming languages) use >> static scoping, meaning a variable defined in an outer function is >> available in the inner function, for instance, (\a -> \b -> (a,b)) 1 2 will >> evauate to (1,2) since a is bound to 1 in the outer lambda, and the inner >> one can refer to the outer one, if instead you write (\a -> \a -> (a,a)) 1 >> 2 the result will be (2,2) since the innermost a will be used (no ambiguity >> here, but if shadowing is done by accident it can be hard to find the >> error). > > > Because the lambda is executed by the implementation of >>=, doesn't the > concept closure still apply? That value of 'my' has to "get into" the other > routine. I think you are both right. AFAIU Adam comments on *visibility* of the variables, while you look more at the fact that you pass the lambda as an argument to (>>=). The lambda can "see" the variable my due to scoping, and (>>=) can trigger evaluation of the lambda due to closures. I'm looking forward to be corrected by someone who knows more about this than I do. /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: OpenPGP digital signature Url : http://www.haskell.org/pipermail/beginners/attachments/20090811/303059f8/signature.bin From tom.davie at gmail.com Tue Aug 11 01:52:40 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Tue Aug 11 01:33:11 2009 Subject: [Haskell-beginners] brief example of ZipList? In-Reply-To: <4A80B670.1000400@alumni.caltech.edu> References: <4A80B670.1000400@alumni.caltech.edu> Message-ID: z1 :: ZipList (Int -> Int) z1 = ZipList [succ,succ] z2 :: ZipList Int z2 = ZipList [1,2] z3 :: ZipList Int z3 = z1 <*> z2 Bob On 11 Aug 2009, at 02:08, Michael P Mossey wrote: > Can someone give me a brief example using ZipList? I want to do > something like > > z1 :: [Int -> Int] > z1 = [succ,succ] > > z2 :: [Int] > z2 = [1,2] > > z3 = z1 <*> z2 > > But don't know to get it to regard these as ZipLists and not regular > lists. > > This is purely for learning purposes. No application in mind. > > -Mike > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From dbastos+0 at toledo.com Wed Aug 12 01:21:24 2009 From: dbastos+0 at toledo.com (Daniel Bastos) Date: Wed Aug 12 01:10:34 2009 Subject: [Haskell-beginners] Re: Closure References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <4a70acb7.1c07d00a.389e.ffff9066@mx.google.com> <20090729202442.GA8017@seas.upenn.edu> Message-ID: In article <20090729202442.GA8017@seas.upenn.edu>, Brent Yorgey wrote: > With that said, on some level the idea of a closure is really just an > implementation detail---I wouldn't say that understanding it is of > fundamental importance in learning Haskell. But learning things never > hurts (except when it does). So it sounds correct to say that a closure is a function that brings an environment with it, such as variables defined outside of it. With this ability, we can construct functions on the fly because a function can return a closure which is amended and, say, returned again another closure more fully specified. From mpm at alumni.caltech.edu Wed Aug 12 21:59:16 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Wed Aug 12 21:40:17 2009 Subject: [Haskell-beginners] some terminology Message-ID: <4A837374.2050101@alumni.caltech.edu> I was looking at some code, saw a variable x, and said to myself, "Ah that variable is a monad." Then I realized "Monad" is the name of a type class. So maybe x should be called "an instance of a Monad." I think the word "instance" in this case is OO-like; but in Haskell "instance" refers to a type that is an instance of a type class. Or maybe it can refer to both? And Monad is a type class, not a type. Maybe I need the phrase "monadic type" to refer to an instance of a type class. So maybe x is just "a variable of a monadic type"? Thanks, Mike From allbery at ece.cmu.edu Wed Aug 12 22:04:40 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Wed Aug 12 21:45:21 2009 Subject: [Haskell-beginners] some terminology In-Reply-To: <4A837374.2050101@alumni.caltech.edu> References: <4A837374.2050101@alumni.caltech.edu> Message-ID: On Aug 12, 2009, at 21:59 , Michael P Mossey wrote: > I was looking at some code, saw a variable x, and said to myself, > "Ah that variable is a monad." Then I realized "Monad" is the name > of a type class. So maybe x should be called "an instance of a > Monad." I think the word "instance" in this case is OO-like; but in > Haskell "instance" refers to a type that is an instance of a type > class. Or maybe it can refer to both? And Monad is a type class, not > a type. Maybe I need the phrase "monadic type" to refer to an > instance of a type class. So maybe x is just "a variable of a > monadic type"? Strictly speaking, yes. In practice the common shorthand is "in the X monad" or just "in X". -- brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery@kf8nh.com system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon university KF8NH -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 195 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20090812/8d3aff21/PGP.bin From apfelmus at quantentunnel.de Thu Aug 13 05:14:17 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Thu Aug 13 04:54:51 2009 Subject: [Haskell-beginners] Re: some terminology In-Reply-To: <4A837374.2050101@alumni.caltech.edu> References: <4A837374.2050101@alumni.caltech.edu> Message-ID: Michael P Mossey wrote: > I was looking at some code, saw a variable x, and said to myself, "Ah > that variable is a monad." Then I realized "Monad" is the name of a type > class. So maybe x should be called "an instance of a Monad." I think the > word "instance" in this case is OO-like; but in Haskell "instance" > refers to a type that is an instance of a type class. Or maybe it can > refer to both? And Monad is a type class, not a type. Maybe I need the > phrase "monadic type" to refer to an instance of a type class. So maybe > x is just "a variable of a monadic type"? One common nomenclature is to say that x is a "monadic action" or just "action" for short. That's the terminology used in the Simon Peyton Jones. Tackling the awkward squad. http://research.microsoft.decenturl.com/awkward-squad tutorial. Regards, apfelmus -- http://apfelmus.nfshost.com From rziemba at gmail.com Thu Aug 13 11:25:07 2009 From: rziemba at gmail.com (Robert Ziemba) Date: Thu Aug 13 11:05:27 2009 Subject: [Haskell-beginners] function parameter types after flip Message-ID: <65135790908130825o601a1d5ct6a605f276ce61253@mail.gmail.com> Can anyone help me understand the behavior of the following expressions in ghci? ?I was trying to construct a flipped function 'elem' that would accept a list of characters first but I ran into this problem with the type signature. Thank you. Prelude Data.List Data.Char> :t elem elem :: (Eq a) => a -> [a] -> Bool ? ? ? ? ? ? ?-- OK Prelude Data.List Data.Char> :t (flip elem) (flip elem) :: (Eq a) => [a] -> a -> Bool ? ? ? -- OK this is what I want Prelude Data.List Data.Char> let fElem = (flip elem) Prelude Data.List Data.Char> :t fElem fElem :: [()] -> () -> Bool ? ? ? ? ? ? ? ? ? ? -- ?? Function will not accept a [Char] From seideld at tcs.inf.tu-dresden.de Thu Aug 13 11:35:22 2009 From: seideld at tcs.inf.tu-dresden.de (Daniel Seidel) Date: Thu Aug 13 11:15:45 2009 Subject: [Haskell-beginners] function parameter types after flip In-Reply-To: <65135790908130825o601a1d5ct6a605f276ce61253@mail.gmail.com> References: <65135790908130825o601a1d5ct6a605f276ce61253@mail.gmail.com> Message-ID: <4A8432BA.1090406@tcs.inf.tu-dresden.de> Robert Ziemba wrote: > Can anyone help me understand the behavior of the following > expressions in ghci? I was trying to construct a flipped function > 'elem' that would accept a list of characters first but I ran into > this problem with the type signature. Thank you. > > Prelude Data.List Data.Char> :t elem > elem :: (Eq a) => a -> [a] -> Bool -- OK > Prelude Data.List Data.Char> :t (flip elem) > (flip elem) :: (Eq a) => [a] -> a -> Bool -- OK this is what I want > Prelude Data.List Data.Char> let fElem = (flip elem) > Prelude Data.List Data.Char> :t fElem > fElem :: [()] -> () -> Bool -- ?? Function > will not accept a [Char] I think its due to the monomorphism restriction. If you define it like Prelude> let fElem x = (flip elem) x Prelude> :t fElem fElem :: (Eq a) => [a] -> a -> Bool it works. For the details look at http://haskell.org/haskellwiki/Monomorphism_restriction ... or wait for another answer (which I think will come). Daniel. > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From daniel.is.fischer at web.de Thu Aug 13 11:52:58 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Aug 13 11:34:18 2009 Subject: [Haskell-beginners] function parameter types after flip In-Reply-To: <65135790908130825o601a1d5ct6a605f276ce61253@mail.gmail.com> References: <65135790908130825o601a1d5ct6a605f276ce61253@mail.gmail.com> Message-ID: <200908131752.58655.daniel.is.fischer@web.de> Am Donnerstag 13 August 2009 17:25:07 schrieb Robert Ziemba: > Can anyone help me understand the behavior of the following > expressions in ghci? ?I was trying to construct a flipped function > 'elem' that would accept a list of characters first but I ran into > this problem with the type signature. Thank you. > > Prelude Data.List Data.Char> :t elem > elem :: (Eq a) => a -> [a] -> Bool ? ? ? ? ? ? ?-- OK > Prelude Data.List Data.Char> :t (flip elem) > (flip elem) :: (Eq a) => [a] -> a -> Bool ? ? ? -- OK this is what I want > Prelude Data.List Data.Char> let fElem = (flip elem) > Prelude Data.List Data.Char> :t fElem > fElem :: [()] -> () -> Bool ? ? ? ? ? ? ? ? ? ? -- ?? Function > will not accept a [Char] It's the monomorphism restriction. If you bind a name by a simple pattern binding (like [let] fElem = flip elem) and don't give a type signature, it must have a monomorphic type and in ghci, that defaults to () for unconstrained type variables. Ways to fix the behaviour: 1. give an explicit type signature (good in code files anyway, but cumbersome at the ghci prompt) 2. make it a function binding: let fElem xs x = x `elem` xs let fElem xs = (`elem` xs) let fElem xs = flip elem xs 3. run ghci without the monomorphism restriction Prelude> :set -XNoMonomorphismRestriction Prelude> let fElem = flip elem Prelude> :t fElem fElem :: (Eq a) => [a] -> a -> Bool (that would be a good entry in your .ghci file anyway, you rarely want it unless you are a compiler writer) From mauricio.antunes at gmail.com Thu Aug 13 13:34:12 2009 From: mauricio.antunes at gmail.com (=?ISO-8859-1?Q?Maur=ED=ADcio_CA?=) Date: Thu Aug 13 13:20:25 2009 Subject: [Haskell-beginners] Re: some terminology In-Reply-To: <4A837374.2050101@alumni.caltech.edu> References: <4A837374.2050101@alumni.caltech.edu> Message-ID: > I was looking at some code, saw a variable x, and said to myself, "Ah > that variable is a monad." Then I realized "Monad" is the name of a type > class. So maybe x should be called "an instance of a Monad." I think the > word "instance" in this case is OO-like; but in Haskell "instance" > refers to a type that is an instance of a type class. [...] In general, it helps to know that the current "de facto" Haskell standard actually accepts classes and instances built on top of many types: class SomeClass a b c where someF :: a -> b -> c anotherF :: b -> c -> a instance SomeClass T1 T2 T3 where someF = ... anotherF = ... This way it becomes clear that saying that some type "is of" or "instantiate" some class isn't apropriate. Best, Maur?cio From dbastos+0 at toledo.com Fri Aug 14 19:46:02 2009 From: dbastos+0 at toledo.com (Daniel Bastos) Date: Fri Aug 14 19:26:36 2009 Subject: [Haskell-beginners] Re: Closure References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <4a70acb7.1c07d00a.389e.ffff9066@mx.google.com> <20090729202442.GA8017@seas.upenn.edu> Message-ID: In article , Daniel Bastos wrote: > In article <20090729202442.GA8017@seas.upenn.edu>, > Brent Yorgey wrote: > >> With that said, on some level the idea of a closure is really just an >> implementation detail---I wouldn't say that understanding it is of >> fundamental importance in learning Haskell. But learning things never >> hurts (except when it does). > > So it sounds correct to say that a closure is a function that brings > an environment with it, such as variables defined outside of it. > > With this ability, we can construct functions on the fly because a > function can return a closure which is amended and, say, returned > again another closure more fully specified. Hello. This was actually a request for comments. Though I didn't say it. Does that sound correct? Any comments? Thanks much. From mpm at alumni.caltech.edu Fri Aug 14 20:55:02 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Fri Aug 14 20:35:28 2009 Subject: [Haskell-beginners] monad transformers Message-ID: <4A860766.7020602@alumni.caltech.edu> In Martin Grabmuller's tutorial "Monad Transformers Step by Step", found here http://user.cs.tu-berlin.de/~magr/pub/Transformers.pdf he gives an example of composing ErrorT, StateT, ReaderT, and WriterT. Early in the paper, where he composes just ErrorT and ReaderT type Eval3 a = ReaderT Env (ErrorT String Identity) a he uses 'ask' and 'throwError' in some example code. I notice that he doesn't have to lift throwError into the ErrorT monad. Why is this? Do I misunderstand something about monad transformers? Is it a convenience definition of throwError? Same thing the rest of the paper. I don't see anywhere he lifts anything. Thanks, Mike From mpm at alumni.caltech.edu Fri Aug 14 21:03:59 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Fri Aug 14 20:44:28 2009 Subject: [Haskell-beginners] Constructors as functions (was monad transformers) In-Reply-To: <4A860766.7020602@alumni.caltech.edu> References: <4A860766.7020602@alumni.caltech.edu> Message-ID: <4A86097F.5030900@alumni.caltech.edu> Michael P Mossey wrote: > In Martin Grabmuller's tutorial "Monad Transformers Step by Step", found > here > > http://user.cs.tu-berlin.de/~magr/pub/Transformers.pdf > Additional question: in this paper he uses a data constructor in an interesting way: back-quoting it to make it an operator. I thought, "Huh, a constructor is a lot like a function?" I did some experiments and found that I can map a constructor over a list and I can compose a constructor with other functions. Cool. So is a constructor a function, in every sense? Thanks, Mike From allbery at ece.cmu.edu Fri Aug 14 21:05:14 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Fri Aug 14 20:45:46 2009 Subject: [Haskell-beginners] monad transformers In-Reply-To: <4A860766.7020602@alumni.caltech.edu> References: <4A860766.7020602@alumni.caltech.edu> Message-ID: <7766B05E-BBA2-4F4D-894F-CD1D80CDD92E@ece.cmu.edu> On Aug 14, 2009, at 20:55 , Michael P Mossey wrote: > In Martin Grabmuller's tutorial "Monad Transformers Step by Step", > found here > > http://user.cs.tu-berlin.de/~magr/pub/Transformers.pdf > > he gives an example of composing ErrorT, StateT, ReaderT, and > WriterT. Early in the paper, where he composes just ErrorT and ReaderT > > type Eval3 a = ReaderT Env (ErrorT String Identity) a > > he uses 'ask' and 'throwError' in some example code. I notice that > he doesn't have to lift throwError into the ErrorT monad. Why is > this? Do I misunderstand something about monad transformers? Is it a > convenience definition of throwError? Look for definitions of the form > instance MonadReader Eval3 where ... > instance MonadError Eval3 where ... These effectively "import" definitions of ask, throwError, etc. with implicit lifting. -- brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery@kf8nh.com system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon university KF8NH -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 195 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20090814/9417d865/PGP.bin From ml at isaac.cedarswampstudios.org Fri Aug 14 21:10:40 2009 From: ml at isaac.cedarswampstudios.org (Isaac Dupree) Date: Fri Aug 14 20:51:06 2009 Subject: [Haskell-beginners] Constructors as functions (was monad transformers) In-Reply-To: <4A86097F.5030900@alumni.caltech.edu> References: <4A860766.7020602@alumni.caltech.edu> <4A86097F.5030900@alumni.caltech.edu> Message-ID: <4A860B10.9070202@isaac.cedarswampstudios.org> Michael P Mossey wrote: > Michael P Mossey wrote: >> In Martin Grabmuller's tutorial "Monad Transformers Step by Step", >> found here >> >> http://user.cs.tu-berlin.de/~magr/pub/Transformers.pdf >> > > Additional question: in this paper he uses a data constructor in an > interesting way: back-quoting it to make it an operator. I thought, > "Huh, a constructor is a lot like a function?" I did some experiments > and found that I can map a constructor over a list and I can compose a > constructor with other functions. Cool. So is a constructor a function, > in every sense? Yes. In expressions, a constructor is a function, no more and no less (albeit with some weird capitalization). Constructors however, can *also* be used in pattern-matching, unlike functions. That's the (only?) special thing about them. -Isaac From apfelmus at quantentunnel.de Sat Aug 15 03:44:16 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Sat Aug 15 03:24:51 2009 Subject: [Haskell-beginners] Re: Closure In-Reply-To: References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <4a70acb7.1c07d00a.389e.ffff9066@mx.google.com> <20090729202442.GA8017@seas.upenn.edu> Message-ID: Daniel Bastos wrote: > >> So it sounds correct to say that a closure is a function that brings >> an environment with it, such as variables defined outside of it. >> >> With this ability, we can construct functions on the fly because a >> function can return a closure which is amended and, say, returned >> again another closure more fully specified. > > Hello. This was actually a request for comments. Though I didn't say > it. Does that sound correct? Any comments? Thanks much. Yes, that's pretty much correct. The simplest example of a closure is indeed foo = add 3 where add = \x y -> x + y Reduction to weak head normal form yields foo = let x = 3 in \y -> x + y which means that foo is a function \y -> x + y paired with the value of the free variable x . Note that closures are an implementation detail. From a semantic point of view, add 3 can readily be understood as an ordinary function. Regards, apfelmus -- http://apfelmus.nfshost.com From uzytkownik2 at gmail.com Sat Aug 15 05:16:06 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Sat Aug 15 04:56:33 2009 Subject: [Haskell-beginners] Circular programming Message-ID: I'm not understending circular programming. What it is used for? Where feedback variable came from (yes - I know it's wrong question as Haskell is lazy)? I've read http://www.haskell.org/haskellwiki/Circular_programming but I didn't understend the concept and pattern. Regards From bugfact at gmail.com Sat Aug 15 07:43:16 2009 From: bugfact at gmail.com (Peter Verswyvelen) Date: Sat Aug 15 07:23:34 2009 Subject: [Haskell-beginners] Circular programming In-Reply-To: References: Message-ID: It might help to read the Yampa Arcadeand then Plugging a Space Leak with an Arrowto get a practical example of circuit and circular programming. On Sat, Aug 15, 2009 at 11:16 AM, Maciej Piechotka wrote: > I'm not understending circular programming. What it is used for? > Where feedback variable came from (yes - I know it's wrong question as > Haskell > is lazy)? > > I've read http://www.haskell.org/haskellwiki/Circular_programming but I > didn't > understend the concept and pattern. > > Regards > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090815/d8755cf3/attachment-0001.html From bugfact at gmail.com Sat Aug 15 08:27:54 2009 From: bugfact at gmail.com (Peter Verswyvelen) Date: Sat Aug 15 08:08:12 2009 Subject: [Haskell-beginners] Circular programming In-Reply-To: References: Message-ID: oh and reading first about fix should help too: http://en.wikibooks.org/wiki/Haskell/Fix_and_recursion On Sat, Aug 15, 2009 at 1:43 PM, Peter Verswyvelen wrote: > It might help to read the Yampa Arcadeand then Plugging > a Space Leak with an Arrowto get a practical example of circuit and circular programming. > > On Sat, Aug 15, 2009 at 11:16 AM, Maciej Piechotka wrote: > >> I'm not understending circular programming. What it is used for? >> Where feedback variable came from (yes - I know it's wrong question as >> Haskell >> is lazy)? >> >> I've read http://www.haskell.org/haskellwiki/Circular_programming but I >> didn't >> understend the concept and pattern. >> >> Regards >> >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090815/f922ad19/attachment.html From mpm at alumni.caltech.edu Sat Aug 15 10:36:46 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sat Aug 15 10:17:05 2009 Subject: [Haskell-beginners] learning to use Haskell types Message-ID: <4A86C7FE.2080204@alumni.caltech.edu> This is really a general question, but any advice is welcome. I'm currently working through Typeclassopedia and all the tutorials it links to. I'm really enjoying it, but a kind of scary question is: when I begin to write "real" software in Haskell, how will I find natural places to use the types and how will I make the transition to idiomatic Haskell? [Note: the main application I have for Haskell is my music composition hobby. I plan to use Haskell to write software for editing music and for computer-assisted composition (CAC). CAC means the computer does some of the tedious work involved in searching for, and evaluation of, combinations of musical themes. All my algorithms are personal to my own process. There is no off-the-shelf software that can help me. That's why it's fortunate I'm a programmer. The CAC features need to be tightly integrated into a musical score editor, hence I have to write that too. Really quite a fun project, and even if it takes two years, I will get years and years of enjoyment from it!] Then it occurred to me that a common theme in Haskell is to provide a way to express a solution to a problem in an expressive form that is natural to that problem. So maybe what I need to do is stop thinking, "Where can I use this type," and instead dream up ways to express ideas in a simple and natural form, then make use of Haskell types and type classes to make that expressive form a reality. For example, in a music editor, there are many actions that create new notes. A note needs many pieces of information to describe it: the note's place in time, its duration, dynamics, whether tied to successive notes, type of flag or beam... Much of this information can be inferred from the context in which the note is created, and so a natural expressive language would bring a new note into existence with a minimal need for providing details. Those details would be inferred from the context. So that's a Reader monad right there. Thanks, Mike From dbastos+0 at toledo.com Sat Aug 15 12:07:08 2009 From: dbastos+0 at toledo.com (Daniel Bastos) Date: Sat Aug 15 11:47:38 2009 Subject: [Haskell-beginners] Re: Closure References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <4a70acb7.1c07d00a.389e.ffff9066@mx.google.com> <20090729202442.GA8017@seas.upenn.edu> Message-ID: In article , Heinrich Apfelmus wrote: > The simplest example of a closure is indeed > > foo = add 3 > > where > > add = \x y -> x + y Question. This is actually equal to add x y = x + y But you wrote in terms of \. Why such preference? > Reduction to weak head normal form yields > > foo = let x = 3 in \y -> x + y > > which means that foo is a function \y -> x + y paired with the value > of the free variable x . I see. > Note that closures are an implementation detail. From a semantic point > of view, add 3 can readily be understood as an ordinary function. This makes sense. Because, even in a language like C, a similar effect can be achieved, no? For example int plus(int x, int y) { return x + y; } int plus3(int y) { plus(3, y); } So, what I can't do in C, besides almost everything I can't do, is to do this nicely like I do in Haskell. But we don't call this a closure. In fact, we say C does not allow for closures. So what am I missing? From daniel.is.fischer at web.de Sat Aug 15 12:31:14 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Aug 15 12:12:25 2009 Subject: [Haskell-beginners] Re: Closure In-Reply-To: References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> Message-ID: <200908151831.14649.daniel.is.fischer@web.de> Am Samstag 15 August 2009 18:07:08 schrieb Daniel Bastos: > In article , > > Heinrich Apfelmus wrote: > > The simplest example of a closure is indeed > > > > foo = add 3 > > > > where > > > > add = \x y -> x + y > > Question. This is actually equal to > > add x y = x + y > > But you wrote in terms of \. Why such preference? > > > Reduction to weak head normal form yields > > > > foo = let x = 3 in \y -> x + y > > > > which means that foo is a function \y -> x + y paired with the value > > of the free variable x . > > I see. > > > Note that closures are an implementation detail. From a semantic point > > of view, add 3 can readily be understood as an ordinary function. > > This makes sense. Because, even in a language like C, a similar effect > can be achieved, no? For example > > int plus(int x, int y) { return x + y; } > > int plus3(int y) { plus(3, y); } > > So, what I can't do in C, besides almost everything I can't do, is to > do this nicely like I do in Haskell. But we don't call this a > closure. In fact, we say C does not allow for closures. So what am I > missing? > You can't do cmp :: a -> a -> a -> Ordering cmp pivot x y = ... funkyFun :: (a -> a -> a -> Ordering) -> [a] -> [a] funkyFun _ [] = [] funkyFun c (x:xs) = x:sortBy (c x) xs main = do args <- getArgs print $ funkyFun cmp (some pseudorandom list depending on args) in C (at least not without some black magic). The plus3 example is a "closure" which is hardcoded and available at compile time. I think, to say that a language allows closures means it allows closures determined at run time. From allbery at ece.cmu.edu Sat Aug 15 12:34:25 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sat Aug 15 12:14:53 2009 Subject: [Haskell-beginners] Re: Closure In-Reply-To: References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <4a70acb7.1c07d00a.389e.ffff9066@mx.google.com> <20090729202442.GA8017@seas.upenn.edu> Message-ID: <1B14D870-7355-4EFD-B0C6-026109AB4F87@ece.cmu.edu> On Aug 15, 2009, at 12:07 , Daniel Bastos wrote: > This makes sense. Because, even in a language like C, a similar effect > can be achieved, no? For example > > int plus(int x, int y) { return x + y; } > > int plus3(int y) { plus(3, y); } > > So, what I can't do in C, besides almost everything I can't do, is to > do this nicely like I do in Haskell. But we don't call this a > closure. In fact, we say C does not allow for closures. So what am I > missing? In C you have to declare it. In Haskell you can just do it on the fly: > map (add 3) [1..10] or indeed > map (+3) [1..10] (The above is actually a "section", a closure created from an infix function. The difference is that I can specify either side of the operator, whereas to specify arguments other than the first for a regular function I must either coerce it into infix with `` or use the "flip" function to rearrange arguments.) -- brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery@kf8nh.com system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon university KF8NH -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 195 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20090815/c71a43c5/PGP.bin From dbastos+0 at toledo.com Sat Aug 15 13:04:33 2009 From: dbastos+0 at toledo.com (Daniel Bastos) Date: Sat Aug 15 12:45:00 2009 Subject: [Haskell-beginners] Re: Closure References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <4a70acb7.1c07d00a.389e.ffff9066@mx.google.com> <20090729202442.GA8017@seas.upenn.edu> <1B14D870-7355-4EFD-B0C6-026109AB4F87@ece.cmu.edu> Message-ID: In article <1B14D870-7355-4EFD-B0C6-026109AB4F87@ece.cmu.edu>, Brandon S. Allbery KF8NH wrote: > In C you have to declare it. The word would be `define'? > In Haskell you can just do it on the fly: > > > map (add 3) [1..10] I see. Just like we can create an integer on the fly in C, in Haskell we can create functions on the fly. I guess that's quite a difference. > or indeed > > > map (+3) [1..10] > > (The above is actually a "section", a closure created from an infix > function. The difference is that I can specify either side of the > operator, whereas to specify arguments other than the first for a > regular function I must either coerce it into infix with `` or use the > "flip" function to rearrange arguments.) And is this mere syntax sugar? From dbastos+0 at toledo.com Sat Aug 15 13:06:42 2009 From: dbastos+0 at toledo.com (Daniel Bastos) Date: Sat Aug 15 12:50:20 2009 Subject: [Haskell-beginners] Re: Closure References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <200908151831.14649.daniel.is.fischer@web.de> Message-ID: In article <200908151831.14649.daniel.is.fischer@web.de>, Daniel Fischer wrote: > The plus3 example is a "closure" which is hardcoded and available at > compile time. I think, to say that a language allows closures means > it allows closures determined at run time. Hm. But does Haskell allow me to define a function at run time? I know Lisp can, since a function is just a data structure which we can put together at run time. But how about Haskell? From daniel.is.fischer at web.de Sat Aug 15 15:14:39 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Aug 15 14:55:51 2009 Subject: [Haskell-beginners] Re: Closure In-Reply-To: References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <200908151831.14649.daniel.is.fischer@web.de> Message-ID: <200908152114.40077.daniel.is.fischer@web.de> Am Samstag 15 August 2009 19:06:42 schrieb Daniel Bastos: > In article <200908151831.14649.daniel.is.fischer@web.de>, > > Daniel Fischer wrote: > > The plus3 example is a "closure" which is hardcoded and available at > > compile time. I think, to say that a language allows closures means > > it allows closures determined at run time. > > Hm. But does Haskell allow me to define a function at run time? I know > Lisp can, since a function is just a data structure which we can put > together at run time. But how about Haskell? Depends on how you interpret it. In the sense of ... let foo = \y -> f x y in map foo list where the value of x is supplied at run time (and more complicated constructions depending on run time values), sure. If you write a good parser, you can also do putStrLn "Please enter function code:" code <- getLine let fun = parseFunction code use fun -- may segfault if the entered code isn't good In which (other) ways can you construct functions at run time in Lisp? From iand675 at gmail.com Sat Aug 15 20:12:43 2009 From: iand675 at gmail.com (Ian Duncan) Date: Sat Aug 15 19:52:59 2009 Subject: [Haskell-beginners] List combination function? Message-ID: <4A874EFB.8020009@gmail.com> Hello all, I'm trying to build a function that takes a string such as "123" and gives me permutations including permutations with lesser list lengths. I'm not sure how to phrase it, but here is what the output could look like: foo "123" => ["123","213","321","231","312","132", "12", "13", "21", "23", "31", "32", "1", "2", "3", ""] The ordering doesn't matter, and that null list at the end doesn't particularly matter, but I don't really know the mathematical phrasing of what I'm asking for. I'm trying to build a scrabble helper that can find the optimal score given a set of letters to work with. Thanks for your help, Ian Duncan From alexander.dunlap at gmail.com Sat Aug 15 20:16:45 2009 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Sat Aug 15 19:57:18 2009 Subject: [Haskell-beginners] List combination function? In-Reply-To: <4A874EFB.8020009@gmail.com> References: <4A874EFB.8020009@gmail.com> Message-ID: <57526e770908151716i1eac1ef3q690e70b9e6f102aa@mail.gmail.com> On Sat, Aug 15, 2009 at 5:12 PM, Ian Duncan wrote: > Hello all, > > I'm trying to build a function that takes a string such as "123" and gives > me permutations including permutations with lesser list lengths. I'm not > sure how to phrase it, but here is what the output could look like: > > foo "123" => ["123","213","321","231","312","132", "12", "13", "21", "23", > "31", "32", "1", "2", "3", ""] > > The ordering doesn't matter, and that null list at the end doesn't > particularly matter, but I don't really know the mathematical phrasing of > what I'm asking for. I'm trying to build a scrabble helper that can find the > optimal score given a set of letters to work with. > > Thanks for your help, > > Ian Duncan > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > Import Data.List, then the function you want is concatMap permutations . subsequences subsequences returns a list of all subsequences of the original list in order. permutations returns a list of all possible orderings of the list. concatMap applies permutations to every member of the subsequence list and then flattens the list down to a single list again. Hope that helps, Alex From uzytkownik2 at gmail.com Sun Aug 16 06:14:35 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Sun Aug 16 05:54:52 2009 Subject: [Haskell-beginners] Circular programming In-Reply-To: References: Message-ID: <1250417675.8044.58.camel@notebook> On Sat, 2009-08-15 at 14:27 +0200, Peter Verswyvelen wrote: > oh and reading first about fix should help too: > > > http://en.wikibooks.org/wiki/Haskell/Fix_and_recursion > Thanks. That helped a lot - so it is 'wired'[1] recursion. [1] for imperative programmers -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20090816/379a2977/attachment.bin From jamarier at gmail.com Sun Aug 16 08:04:10 2009 From: jamarier at gmail.com (Javier M Mora) Date: Sun Aug 16 07:44:23 2009 Subject: [Haskell-beginners] A rigid type and a better pattern Message-ID: <84a973e00908160504r55fd098j84f613bdc854582d@mail.gmail.com> (I had problems sending this email and I don't know if earlier arrived to mail list. I'm going to send again. Sorry if you get it duplicate) Hi All, this is my first email to beginners list. I'm ending my Master Degree in Robotics (in Spain). One of my assignment is about Motion Planning and I thought solve with Haskell. This is my problem: * Every robot has a local state. I can get the position of the robot from the state. The state can be rect coords or polar coords or distance moved on a fixed path or whatever. * I have a global state witch keep the local state of each robot. * Every state has a different system to action over it. So, in distance over fixed path we can "stop" or "go". In polar coords we can increase and decrease the radius and phi. And in rect coords we can move in x and y direction * I have several robots at same time. But every robot has the same state and the same action. So, all robots in the run of my program has same local state and action. So, I split the algorithm in a common part (used in all states and actions) and other for each specific state-action. This is the structure (abstract): class Robot a where ... class State a where getpos a -> [Position] ... class Action a where ... later I have instances for concrete cases. In phase 1, local state is a Int for each robot and action is a Bool (stop or run). data State1 = State1 [Int] instance State State1 where getpos (State1 a) = ... ... data Action1 = Action1 [Bool] instance Action Action1 where ... I have a function "newstate" to calculate the new state from an old state and the action. This is the type signature: newstate:: (State a,Action b) => a -> b -> a and my instantiation in phase 1 is newstate (State1 s) (Action1 u) = State1 $ zipWith (\x y -> if y then succ x else x) s u I want to use polymorphism in newstation because I need use newstate (State2 s) (Action2 u) in the future (phase 2) so I tried include newstate in a typeclass. But if I write: class State a where newstate:: (Action b)=> a -> b -> a ... or class Action a where newstate:: (State b) => b -> a -> b ... (and move newstate definition to correct instance block) I get similar errors in both cases: (this is the first case): Couldn't match expected type `b' against inferred type `Action1' `b' is a rigid type variable bound by the type signature for `newstate' at Tipos.hs:17:24 In the pattern: Action1 u In the definition of `newstate': newstate (State1 s) (Action1 u) = State1 $ zipWith (\ x y -> if y then succ x else x) s u In the instance declaration for `State State1' My questions: * How can I fix this error? * the point is associate every instance of Robot with one instance of State and with one instance of Action. So when I select the Robot I'm goint to use I get "automagically" the correct instances of newstate and others. Is there a pattern to this behaviour? My ideal is associate every function related with a Robot with a general typeclass "Robot" (I don't tested this) : class Robot a where initstate:: (State a) => a newstate:: (State a,Action b) => a-> b-> a And the instance: instance Robot Robot1 where initstate = State1 [0,0,0] newstate (State1 a) (Action1 b) = ... and instance Robot Robot2 where initstate = State2 [(0,0),(1,1),(2,2)] -- i.e. newstate (State2 a) (Action2 b) = ... and so on. But I think It can't work because neither initstate or newstate use Robot1. Any tips? Javier M Mora. From daniel.is.fischer at web.de Sun Aug 16 09:42:44 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Aug 16 09:23:54 2009 Subject: [Haskell-beginners] A rigid type and a better pattern In-Reply-To: <84a973e00908160504r55fd098j84f613bdc854582d@mail.gmail.com> References: <84a973e00908160504r55fd098j84f613bdc854582d@mail.gmail.com> Message-ID: <200908161542.44870.daniel.is.fischer@web.de> Am Sonntag 16 August 2009 14:04:10 schrieb Javier M Mora: > (I had problems sending this email and I don't know if earlier arrived > to mail list. I'm going to send again. Sorry if you get it duplicate) > > > > Hi All, this is my first email to beginners list. I'm ending my Master > Degree in Robotics (in Spain). One of my assignment is about Motion > Planning and I thought solve with Haskell. This is my problem: > > * Every robot has a local state. I can get the position of the robot > from the state. The state can be rect coords or polar coords or distance > moved on a fixed path or whatever. > > * I have a global state witch keep the local state of each robot. > > * Every state has a different system to action over it. So, in distance > over fixed path we can "stop" or "go". In polar coords we can increase > and decrease the radius and phi. And in rect coords we can move in x and > y direction > > * I have several robots at same time. But every robot has the same state > and the same action. So, all robots in the run of my program has same > local state and action. > > So, I split the algorithm in a common part (used in all states and > actions) and other for each specific state-action. > > This is the structure (abstract): > class Robot a where > ... > > class State a where > getpos a -> [Position] > ... > > class Action a where > ... > > later I have instances for concrete cases. In phase 1, local state is a > Int for each robot and action is a Bool (stop or run). > > data State1 = State1 [Int] > instance State State1 where > getpos (State1 a) = ... > ... > > data Action1 = Action1 [Bool] > instance Action Action1 where > ... > > > I have a function "newstate" to calculate the new state from an old > state and the action. This is the type signature: > > newstate:: (State a,Action b) => a -> b -> a > > and my instantiation in phase 1 is > > newstate (State1 s) (Action1 u) = State1 $ > zipWith (\x y -> if y then succ x else x) s u > > I want to use polymorphism in newstation because I need use > newstate (State2 s) (Action2 u) > in the future (phase 2) so I tried include newstate in a typeclass. > > But if I write: > > class State a where > newstate:: (Action b)=> a -> b -> a > ... > > or > > class Action a where > newstate:: (State b) => b -> a -> b > ... > > (and move newstate definition to correct instance block) > > I get similar errors in both cases: (this is the first case): > > Couldn't match expected type `b' against inferred type `Action1' > `b' is a rigid type variable bound by > the type signature for `newstate' at Tipos.hs:17:24 > In the pattern: Action1 u > In the definition of `newstate': > newstate (State1 s) (Action1 u) > = State1 $ zipWith (\ x y -> if y then succ x > else x) s u > In the instance declaration for `State State1' > Yes. The above signatures promise that newstate will work given any pair of arguments whose types belong to classes State and action respectively, so in the definition you can't pattern match on constructors since you have to be polymorphic. You can make it one multi-parameter type class {-# LANGUAGE MultiParamTypeClasses #-} class ActState a s where newstate :: s -> a -> s instance ActState Action1 State1 where newstate (State1 s) (Action1 u) = ... From the above I have the impression that each action type only works on one state type and each state type has only one action type that works for it, thus you could use functional dependencies or data families to aid resolution of instances. Since Robots are associated with States and Actions (presumably again in a 1-1 correspondence), it makes sense to tie them into it. With functional dependencies: {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} class ActState a s | a -> s, s -> a where newstate :: s -> a -> s instance ActState Action1 State1 where newstate (State1 s) (Action1 u) = ... class (ActState a s) => Robot r s a | r -> s, r -> a, s -> r, s-> a, a -> r, a -> s where ... instance Robot Robot1 State1 Action1 where ... (or leave out the ActState class and have it all in class Robot) With type Families: {-# LANGUAGE MultiParamTypeClasses, TypeFamilies #-} class Rob2 r where data St r data Ac r initstate :: St r newstate :: St r -> Ac r -> St r instance Rob2 Robot1 where data St Robot1 = State2 [Int] deriving Show data Ac Robot1 = Action2 [Bool] deriving Show initstate2 = State2 [0,0,0] newstate2 (State2 xs) (Action2 gs) = State2 $ zipWith (\x g -> if g then succ x else x) xs gs or, moving the families outside the class: data family St3 r data family Ac3 r data instance St3 Robot1 = State3 [Int] deriving Show data instance Ac3 Robot1 = Action3 [Bool] deriving Show class Rob3 r where initstate3 :: St3 r newstate3 :: St3 r -> Ac3 r -> St3 r instance Rob3 Robot1 where initstate3 = State3 [0,0,0] newstate3 (State3 xs) (Action3 gs) = State3 $ zipWith (\x g -> if g then succ x else x) xs gs > > My questions: > > * How can I fix this error? > > * the point is associate every instance of Robot with one instance of > State and with one instance of Action. So when I select the Robot I'm > goint to use I get "automagically" the correct instances of newstate and > others. > > Is there a pattern to this behaviour? Functional dependencies/Type families. Or you could use parameterized types. data Distance = Distance Double data Polar = Polar Double Double data Cartesian = Cartesian Int Int data Action a = Action [a -> a] data State a = State [a] data Robot a = Robot ??? class Robot a where initstate :: State a newstate :: State a -> Action a -> State a instance Robot Distance where ... instance Robot Polar where ... instance Robot Cartesian where ... > > My ideal is associate every function related with a Robot with a general > typeclass "Robot" (I don't tested this) : > > class Robot a where > initstate:: (State a) => a > newstate:: (State a,Action b) => a-> b-> a > > And the instance: > > instance Robot Robot1 where > initstate = State1 [0,0,0] > newstate (State1 a) (Action1 b) = ... > > and > > instance Robot Robot2 where > initstate = State2 [(0,0),(1,1),(2,2)] -- i.e. > newstate (State2 a) (Action2 b) = ... > > and so on. > > But I think It can't work because neither initstate or newstate use Robot1. > > Any tips? > > > > > > Javier M Mora. From apfelmus at quantentunnel.de Sun Aug 16 09:58:33 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Sun Aug 16 09:39:00 2009 Subject: [Haskell-beginners] Re: Closure In-Reply-To: References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <4a70acb7.1c07d00a.389e.ffff9066@mx.google.com> <20090729202442.GA8017@seas.upenn.edu> Message-ID: Daniel Bastos wrote: > Heinrich Apfelmus wrote: > >> The simplest example of a closure is indeed >> >> foo = add 3 >> >> where >> >> add = \x y -> x + y > > Question. This is actually equal to > > add x y = x + y > > But you wrote in terms of \. Why such preference? I wanted to emphasize that add is a value just like 4 or "baz" , i.e. that it's not very different from writing say add = "baz" >> Note that closures are an implementation detail. From a semantic point >> of view, add 3 can readily be understood as an ordinary function. > > This makes sense. Because, even in a language like C, a similar effect > can be achieved, no? For example > > int plus(int x, int y) { return x + y; } > > int plus3(int y) { plus(3, y); } > > So, what I can't do in C, besides almost everything I can't do, is to > do this nicely like I do in Haskell. But we don't call this a > closure. In fact, we say C does not allow for closures. So what am I > missing? A litmus test for being a functional language is the ability to define function composition f . g = \x -> f (g x) This is not possible in C; mainly because functions cannot be defined locally, they have to be declared at the top-level. (I think this test is due to Lennart Augustsson, but I can't find a reference on the web right now.) Hm... this means that Brent's example foo x = add where add y = x + y is actually a much better demonstration of a closure than the one I gave. Yes, I think this one is impossible to write in C. Regards, apfelmus -- http://apfelmus.nfshost.com From dbastos+0 at toledo.com Sun Aug 16 12:12:38 2009 From: dbastos+0 at toledo.com (Daniel Bastos) Date: Sun Aug 16 11:53:57 2009 Subject: [Haskell-beginners] Re: Closure References: <4a6f9f92.0a04d00a.37e5.ffff851a@mx.google.com> <200908151831.14649.daniel.is.fischer@web.de> <200908152114.40077.daniel.is.fischer@web.de> Message-ID: In article <200908152114.40077.daniel.is.fischer@web.de>, Daniel Fischer wrote: >> [Does] Haskell allow me to define a function at run time? I know >> Lisp can, since a function is just a data structure which we can >> put together at run time. But how about Haskell? [...] > If you write a good parser, you can also > > do putStrLn "Please enter function code:" > code <- getLine > let fun = parseFunction code > use fun -- may segfault if the entered code isn't good > > In which (other) ways can you construct functions at run time in Lisp? None. I guess the only difference, if so considered, is that since Lisp is so much syntactically simpler, it's easy to write a parser for it, and I guess most implementations already bring one for ya. And that's nice. It allows for the code that write code, which sounds great. But anyway, my interest here was understanding Haskell better, which I now do. Thanks for all inputs in this subthread. From joesmoe10 at gmail.com Sun Aug 16 21:16:54 2009 From: joesmoe10 at gmail.com (Joe Schafer) Date: Sun Aug 16 22:40:14 2009 Subject: [Haskell-beginners] Ambigous Types with Haskell Functional Graph Library Message-ID: <87iqgnkznd.fsf@gmail.com> Hey all, New to Haskell and I'm trying to use the FGL but I keep running into the same error. If I load Data.Graph.Inductive.Example and use one of the example functions such as ucycle I get: Ambiguous type variable `gr' in the constraint: `Graph gr' arising from a use of `ucycle' at :1:0-7 Probable fix: add a type signature that fixes these type variable(s) Here's the type of ucycle for reference. ucycle :: Graph gr => Int -> gr () () I'm using GHC 6.10.1 and FGL 5.4.2.2 Thanks, Joe From apfelmus at quantentunnel.de Mon Aug 17 02:18:47 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Mon Aug 17 01:59:12 2009 Subject: [Haskell-beginners] Re: learning to use Haskell types In-Reply-To: <4A86C7FE.2080204@alumni.caltech.edu> References: <4A86C7FE.2080204@alumni.caltech.edu> Message-ID: Michael Mossey wrote: > This is really a general question, but any advice is welcome. > > I'm currently working through Typeclassopedia and all the tutorials it > links to. I'm really enjoying it, but a kind of scary question is: when > I begin to write "real" software in Haskell, how will I find natural > places to use the types and how will I make the transition to idiomatic > Haskell? > > [...] > > Then it occurred to me that a common theme in Haskell is to provide a > way to express a solution to a problem in an expressive form that is > natural to that problem. So maybe what I need to do is stop thinking, > "Where can I use this type," and instead dream up ways to express ideas > in a simple and natural form, then make use of Haskell types and type > classes to make that expressive form a reality. Yes, that's the best approach. The hard part is finding a formulation that is natural to the problem; and by definition it's hard to give general advice there. I know of no other way than learning from examples, like this one Simon Peyton Jones, Jean-Marc Eber, Julian Seward. "Composing contracts: an adventure in financial engineering" http://research.microsoft.decenturl.com/composing-contracts What the Typeclassopedia can help with is to provide a few known concepts where it's always worth checking whether they apply naturally. I'd recommend the following order Monoid | | Applicative Monad | Arrow In particular, Monoids are very common. The others usually only apply when the problem domain involves polymorphism, i.e. when the object of discourse is a type constructor. That being said, the many concrete applicative functors and monads like state monads, the list monad, zip lists, parser combinators, probabilistic monads etc. are very useful implementation techniques. But they are limited to "small scale" simplifications, they generally do *not* help with finding a formulation that is natural to the whole problem domain. (Except when it's very obvious, i.e. when the problem *is* to model a state machine, to parse something, to sample a probability distribution, etc.) > For example, in a music editor, there are many actions that create new > notes. A note needs many pieces of information to describe it: the > note's place in time, its duration, dynamics, whether tied to successive > notes, type of flag or beam... Much of this information can be inferred > from the context in which the note is created, and so a natural > expressive language would bring a new note into existence with a minimal > need for providing details. Those details would be inferred from the > context. So that's a Reader monad right there. This would be an example where I think that the Reader monad is an implementation detail, not a model of the problem domain. (Not to mention that I think that the Reader monad has very limited applications.) The latter would be about trying to eliminate the need for a context altogether, to group the many details so that they can be "polymorphized away", etc. Regards, apfelmus -- http://apfelmus.nfshost.com From b.lehnert at gmx.de Tue Aug 18 10:12:50 2009 From: b.lehnert at gmx.de (Bernhard Lehnert) Date: Tue Aug 18 09:52:58 2009 Subject: [Haskell-beginners] Start file with associated prog (windows only?) Message-ID: <1250604770.3888.17.camel@sol> Hello list, I believe I am looking for a haskell equivalent to a python library function called os.startfile(...) which starts any given file with its associated program. http://docs.python.org/library/os.html#os.startfile says: "...this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated. [...] startfile() returns as soon as the associated application is launched." So to show a readme you just write: import os os.startfile("README.rtf") to show your programs documentation you just write os.startfile("documentation.pdf") and windows will decide which program to use to open a PDF. The must urgent thing I actually want to do is open an Internet Browser with my sponsors URL. Any good ideas? Thanks in advance, Bernhard From magnus at therning.org Tue Aug 18 11:07:46 2009 From: magnus at therning.org (Magnus Therning) Date: Tue Aug 18 10:47:53 2009 Subject: [Haskell-beginners] Start file with associated prog (windows only?) In-Reply-To: <1250604770.3888.17.camel@sol> References: <1250604770.3888.17.camel@sol> Message-ID: On Tue, Aug 18, 2009 at 3:12 PM, Bernhard Lehnert wrote: > Hello list, > > I believe I am looking for a haskell equivalent to a python library > function called os.startfile(...) which starts any given file with its > associated program. > > http://docs.python.org/library/os.html#os.startfile says: > "...this acts like double-clicking the file in Windows Explorer, or > giving the file name as an argument to the start command from the > interactive command shell: the file is opened with whatever application > (if any) its extension is associated. > [...] > startfile() returns as soon as the associated application is launched." > > So to show a readme you just write: > import os > os.startfile("README.rtf") > > to show your programs documentation you just write > os.startfile("documentation.pdf") > and windows will decide which program to use to open a PDF. > > The must urgent thing I actually want to do is open an Internet Browser > with my sponsors URL. > > Any good ideas? Windows has a command "start" which you can use e.g. via System.Process.proc. /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe From b.lehnert at gmx.de Tue Aug 18 13:56:55 2009 From: b.lehnert at gmx.de (Bernhard Lehnert) Date: Tue Aug 18 13:37:03 2009 Subject: [Haskell-beginners] Start file with associated prog (windows only?) In-Reply-To: References: <1250604770.3888.17.camel@sol> Message-ID: <1250618215.3888.21.camel@sol> Am Dienstag, den 18.08.2009, 16:07 +0100 schrieb Magnus Therning: > Windows has a command "start" which you can use e.g. via System.Process.proc. Thank you, Magnus - this is exactly what I was looking for. (By the way, someone should implement something like this for GNOME and KDE, too ;-) ) From ml at isaac.cedarswampstudios.org Tue Aug 18 15:34:09 2009 From: ml at isaac.cedarswampstudios.org (Isaac Dupree) Date: Tue Aug 18 15:14:21 2009 Subject: [Haskell-beginners] Start file with associated prog (windows only?) In-Reply-To: <1250618215.3888.21.camel@sol> References: <1250604770.3888.17.camel@sol> <1250618215.3888.21.camel@sol> Message-ID: <4A8B0231.1090604@isaac.cedarswampstudios.org> Bernhard Lehnert wrote: > Am Dienstag, den 18.08.2009, 16:07 +0100 schrieb Magnus Therning: > >> Windows has a command "start" which you can use e.g. via System.Process.proc. > > Thank you, Magnus - this is exactly what I was looking for. (By the way, > someone should implement something like this for GNOME and KDE, > too ;-) ) Well, there is `xdg-open` command, which is not as well-known as it should be. OS X calls the equivalent command "open". I'm not sure what xdg-open does with executable files (Does it really make sense, in a unixy context, to just execute them?) -Isaac From magnus at therning.org Tue Aug 18 16:57:04 2009 From: magnus at therning.org (Magnus Therning) Date: Tue Aug 18 16:37:11 2009 Subject: [Haskell-beginners] Start file with associated prog (windows only?) In-Reply-To: <4A8B0231.1090604@isaac.cedarswampstudios.org> References: <1250604770.3888.17.camel@sol> <1250618215.3888.21.camel@sol> <4A8B0231.1090604@isaac.cedarswampstudios.org> Message-ID: <4A8B15A0.4010203@therning.org> Isaac Dupree wrote: > Bernhard Lehnert wrote: >> Am Dienstag, den 18.08.2009, 16:07 +0100 schrieb Magnus Therning: >> >>> Windows has a command "start" which you can use e.g. via >>> System.Process.proc. >> >> Thank you, Magnus - this is exactly what I was looking for. (By the way, >> someone should implement something like this for GNOME and KDE, >> too ;-) ) > > Well, there is `xdg-open` command, which is not as well-known as it > should be. OS X calls the equivalent command "open". I'm not sure what > xdg-open does with executable files (Does it really make sense, in a > unixy context, to just execute them?) In Gnome there's also 'gnome-open'. % xdg-open /usr/bin/gedit Error showing url: No application is registered as handling this file Same behaviour for gnome-open. /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: OpenPGP digital signature Url : http://www.haskell.org/pipermail/beginners/attachments/20090818/dc32ce3c/signature.bin From apfelmus at quantentunnel.de Tue Aug 18 06:35:18 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Tue Aug 18 22:28:29 2009 Subject: [Haskell-beginners] Re: learning to use Haskell types In-Reply-To: <4A8960F2.8060109@alumni.caltech.edu> References: <4A86C7FE.2080204@alumni.caltech.edu> <4A8960F2.8060109@alumni.caltech.edu> Message-ID: Michael Mossey wrote: > Heinrich Apfelmus wrote: >> This would be an example where I think that the Reader monad is an >> implementation detail, not a model of the problem domain. (Not to >> mention that I think that the Reader monad has very limited >> applications.) The latter would be about trying to eliminate the need >> for a context altogether, to group the many details so that they >> can be >> "polymorphized away", etc. > > Can you explain more about what it means to "polymorphize away" > details? I'm not clear about that. > > You mention "grouping" details. Does this mean creating data which > types that hold all the details, and the data type itself is some > kind of larger concept? For example, you could say a note has many > details such as time, duration, dynamic, etc. And you could also > create > > data Note = Note { time :: Ratio, duration :: Ratio, dyn :: Dynamic } > > and work with Notes as much as possible without peering inside them. Yes, the goal is to avoid peering inside. Creating a new abstraction (= no peeking inside) is the only way to make things elegant. Using record data types are a first step towards that goal. Another technique is to use parametric polymorphism, that's what I intend to convey with the phrase "polymorphize away". The idea is that the type system can make sure that you don't peek inside. Consider the following (almost too trivial) example: length :: [Note] -> Int This function is intended to calculate the length of a list of notes. But of course, it's wholly unimportant that the lists consists of notes, it could as well be a list of apples or integers. In fact, the specialization to notes is a mental burden, and it's much simpler to write a length function that does not care about the contents length :: [a] -> Int The key point is that the type alone already ensures that length *cannot* peek inside the list elements, because it's polymorphic in a . Another example is the function sortBy :: (a -> a -> Ordering) -> [a] -> [a] which does not want to know anything about the list elements except that they can be compared. Of course, these were rather general and well-known examples; the key is to find similar patterns in your own code and problem domain. For instance, notes in staff notation don't really care about velocities, notes in a piano roll are actually just rectangles in a grid, etc. The goal is to focus solely on the relevant details and hide the unimportant details behind a type variable a . Regards, apfelmus -- http://apfelmus.nfshost.com From sparry04 at googlemail.com Tue Aug 18 17:41:45 2009 From: sparry04 at googlemail.com (Simon Parry) Date: Tue Aug 18 22:30:49 2009 Subject: [Haskell-beginners] my ugly code and the Maybe monad Message-ID: <1250631705.2431.24.camel@localhost.localdomain> hello all, Intro: I'm fairly new to Haskell, read some tutorials/books, this is my first real attempt at making something rather than doing tutorial problems - I thought I'd recode some financial maths up in Haskell...see below. It seems to work ok (I haven't properly tested it yet) but I feel the pvs function is just ugly. However it seems like its a fairly common requirement for maths modelling ie using Maybe or Error or such to represent conditions on the input variables and then later having to combine those 'wrapped' values with other things. Basically it seems inelegant and I feel like I'm confusing the monadic and non-monadic parts? help/criticism welcome, thanks Simon module TimeValueMoney1 where --taken from Financial Numerical Recipes in C++ by B A Odegaard (2006): --Chapter 3 import Control.Monad --time periods - assumes now is time 0-- times :: [Int] times = [0..] minusOne :: Double minusOne = -1.0 --can have eg discrete or continuous compounding type Compounding = Double -> Int -> Maybe Double --discounting and present value-- discreteCompounding :: Compounding discreteCompounding yield elapsed | yield > minusOne = Just ( 1.0/ (1.0 + yield)^elapsed ) | otherwise = Nothing continuousCompounding :: Compounding continuousCompounding yield elapsed | yield > minusOne = Just (exp( minusOne * yield * fromIntegral elapsed ) ) | otherwise = Nothing pvs :: Compounding -> Double -> [Double] -> Maybe [Double] pvs df yield cashflow = zipWithM ( \c -> (>>= \d -> return $ c*d ) ) cashflow discounts where discounts = map discount times discount = df yield From jakubuv at gmail.com Wed Aug 19 07:53:42 2009 From: jakubuv at gmail.com (Jan Jakubuv) Date: Wed Aug 19 07:34:03 2009 Subject: [Haskell-beginners] my ugly code and the Maybe monad In-Reply-To: <1250631705.2431.24.camel@localhost.localdomain> References: <1250631705.2431.24.camel@localhost.localdomain> Message-ID: <20090819115342.GA25258@lxultra2.macs.hw.ac.uk> Hi Simon, On Tue, Aug 18, 2009 at 10:41:45PM +0100, Simon Parry wrote: > It seems to work ok (I haven't properly tested it yet) but I feel the > pvs function is just ugly. However it seems like its a fairly common > requirement for maths modelling ie using Maybe or Error or such to > represent conditions on the input variables and then later having to > combine those 'wrapped' values with other things. > I don't quite understand what is function `pvs` supposed to do ?? Anyway, I try to guess. It seems that it just applies `(df yield)` to `times` and then multiply the resulting values one by one with `cashflow`. So it seems that you need to lift multiplication `(*)` to the Maybe monad in the second argument only. You can write your own version of `liftM2` (from `Control.Monad`) like this: liftM2snd f a mb = do { b <- mb; return (f a b) } You can verify that liftM2snd == (fmap .) Thus you can rewrite `pvs` as: pvs2 df yield cashflow = multiply cashflow discounts where multiply = zipWithM (fmap . (*)) discounts = map (df yield) times You could alternatively use the library version of `liftM2` but then you need to ?lift? the `cashflow` list using `return`. Like this: pvs3 df yield cashflow = multiply (map return cashflow) discounts where multiply = zipWithM (liftM2 (*)) discounts = map (df yield) times When you take the advantage of commutativity of `*` you can write: pvs4 df yield = multiply discounts . map return where multiply = zipWithM (liftM2 (*)) discounts = map (df yield) times or maybe even better: pvs5 df yield = multiply discounts where multiply = zipWithM (flip $ fmap . (*)) discounts = map (df yield) times Anyway, note that all the `pvs` functions (including the your one) return `Nothing` when `(df yield)` returns `Nothing` for at least one related member of `times`. Is that what you want? > Basically it seems inelegant and I feel like I'm confusing the monadic > and non-monadic parts? > You are using this function: fce = \c -> (>>= \d -> return $ c*d) which is pretty ugly and not very intuitive. Note that this is simply `liftM2snd (*)` from above, that is, `fmap . (*)`. > help/criticism welcome, You might want to look at the `liftM` functions from `Control.Monad`. Note that I have inlined the only use of `discount`. In my opinion it improves readability. But it's up to you to judge. I hope this helps a little. I don't know any financial stuff so maybe I didn't understand well what is going on. Sincerely, Jan. > > thanks > > Simon > > > module TimeValueMoney1 where > > --taken from Financial Numerical Recipes in C++ by B A Odegaard (2006): > --Chapter 3 > > import Control.Monad > > --time periods - assumes now is time 0-- > times :: [Int] > times = [0..] > > minusOne :: Double > minusOne = -1.0 > > --can have eg discrete or continuous compounding > type Compounding = Double -> Int -> Maybe Double > > --discounting and present value-- > discreteCompounding :: Compounding > discreteCompounding yield elapsed > | yield > minusOne = Just ( 1.0/ (1.0 + yield)^elapsed ) > | otherwise = Nothing > > continuousCompounding :: Compounding > continuousCompounding yield elapsed > | yield > minusOne = Just (exp( minusOne * yield * fromIntegral > elapsed ) ) > | otherwise = Nothing > > pvs :: Compounding -> Double -> [Double] -> Maybe [Double] > pvs df yield cashflow = zipWithM ( \c -> (>>= \d -> return $ c*d ) ) > cashflow discounts > where discounts = map discount times > discount = df yield > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- Heriot-Watt University is a Scottish charity registered under charity number SC000278. From Christian.Maeder at dfki.de Wed Aug 19 11:16:41 2009 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Wed Aug 19 10:56:45 2009 Subject: [Haskell-beginners] Re: Ambigous Types with Haskell Functional Graph Library In-Reply-To: <87iqgnkznd.fsf@gmail.com> References: <87iqgnkznd.fsf@gmail.com> Message-ID: <4A8C1759.5020605@dfki.de> The type constructor variable "gr" can be instantiated with "Data.Graph.Inductive.Tree.Gr" via a type signature: Prelude Data.Graph.Inductive.Example> ucycle 5 :: Data.Graph.Inductive.Tree.Gr () () 1:()->[((),2)] 2:()->[((),3)] 3:()->[((),4)] 4:()->[((),5)] 5:()->[((),1)] HTH Christian Joe Schafer wrote: > Hey all, > > New to Haskell and I'm trying to use the FGL but I keep running into the > same error. > > If I load Data.Graph.Inductive.Example and use one of the example > functions such as ucycle I get: > > Ambiguous type variable `gr' in the constraint: > `Graph gr' arising from a use of `ucycle' at :1:0-7 > Probable fix: add a type signature that fixes these type variable(s) > > Here's the type of ucycle for reference. > > ucycle :: Graph gr => Int -> gr () () > > I'm using GHC 6.10.1 and FGL 5.4.2.2 > > Thanks, > Joe From sparry04 at googlemail.com Wed Aug 19 18:57:47 2009 From: sparry04 at googlemail.com (Simon Parry) Date: Thu Aug 20 05:40:35 2009 Subject: [Haskell-beginners] my ugly code and the Maybe monad In-Reply-To: <20090819115342.GA25258@lxultra2.macs.hw.ac.uk> References: <1250631705.2431.24.camel@localhost.localdomain> <20090819115342.GA25258@lxultra2.macs.hw.ac.uk> Message-ID: <1250722667.2431.65.camel@localhost.localdomain> Thanks Jan, very helpful and you're right I am just trying to combine 2 lists; one with 'wrapped' values, one without. > You can write your own version of `liftM2` (from > `Control.Monad`) like this: > > liftM2snd f a mb = do { b <- mb; return (f a b) } > so the b <- mb bit is 'unwrapping' the Maybe b to use it with the pure function f? I guess I didn't realise this as I've only seen it in the IO monad, but naturally it would work with all monads. > You can verify that > > liftM2snd == (fmap .) if I look at this in GHCi the liftM2snd acts over monads and the (fmap .) acts over functors. Now I'm still trying to get comfortable with simple monad manipulations so maybe I should just read this as functors are equivalent to monads and not worry too much about it yet? With that in mind fmap acts to map some pure function over a 'wrapped' value? Thanks also for the other suggestions, its always helpful to see a progression rather than jumping in at say pvs5. > Anyway, note that all the `pvs` functions (including the your one) return > `Nothing` when `(df yield)` returns `Nothing` for at least one related > member of `times`. Is that what you want? I did want it to only perform the calc if the yield was sensible. thanks again Simon On Wed, 2009-08-19 at 12:53 +0100, Jan Jakubuv wrote: > Hi Simon, > > On Tue, Aug 18, 2009 at 10:41:45PM +0100, Simon Parry wrote: > > It seems to work ok (I haven't properly tested it yet) but I feel the > > pvs function is just ugly. However it seems like its a fairly common > > requirement for maths modelling ie using Maybe or Error or such to > > represent conditions on the input variables and then later having to > > combine those 'wrapped' values with other things. > > > > I don't quite understand what is function `pvs` supposed to do ?? Anyway, > I try to guess. It seems that it just applies `(df yield)` to `times` and > then multiply the resulting values one by one with `cashflow`. So it seems > that you need to lift multiplication `(*)` to the Maybe monad in the second > argument only. You can write your own version of `liftM2` (from > `Control.Monad`) like this: > > liftM2snd f a mb = do { b <- mb; return (f a b) } > > You can verify that > > liftM2snd == (fmap .) > > Thus you can rewrite `pvs` as: > > pvs2 df yield cashflow = multiply cashflow discounts > where multiply = zipWithM (fmap . (*)) > discounts = map (df yield) times > > You could alternatively use the library version of `liftM2` but then you > need to ?lift? the `cashflow` list using `return`. Like this: > > pvs3 df yield cashflow = multiply (map return cashflow) discounts > where multiply = zipWithM (liftM2 (*)) > discounts = map (df yield) times > > When you take the advantage of commutativity of `*` you can write: > > pvs4 df yield = multiply discounts . map return > where multiply = zipWithM (liftM2 (*)) > discounts = map (df yield) times > > or maybe even better: > > pvs5 df yield = multiply discounts > where multiply = zipWithM (flip $ fmap . (*)) > discounts = map (df yield) times > > Anyway, note that all the `pvs` functions (including the your one) return > `Nothing` when `(df yield)` returns `Nothing` for at least one related > member of `times`. Is that what you want? > > > Basically it seems inelegant and I feel like I'm confusing the monadic > > and non-monadic parts? > > > > You are using this function: > > fce = \c -> (>>= \d -> return $ c*d) > > which is pretty ugly and not very intuitive. Note that this is simply > `liftM2snd (*)` from above, that is, `fmap . (*)`. > > > help/criticism welcome, > > You might want to look at the `liftM` functions from `Control.Monad`. > > Note that I have inlined the only use of `discount`. In my opinion it > improves readability. But it's up to you to judge. > > I hope this helps a little. I don't know any financial stuff so maybe I > didn't understand well what is going on. > > Sincerely, > Jan. > > > > > thanks > > > > Simon > > > > > > module TimeValueMoney1 where > > > > --taken from Financial Numerical Recipes in C++ by B A Odegaard (2006): > > --Chapter 3 > > > > import Control.Monad > > > > --time periods - assumes now is time 0-- > > times :: [Int] > > times = [0..] > > > > minusOne :: Double > > minusOne = -1.0 > > > > --can have eg discrete or continuous compounding > > type Compounding = Double -> Int -> Maybe Double > > > > --discounting and present value-- > > discreteCompounding :: Compounding > > discreteCompounding yield elapsed > > | yield > minusOne = Just ( 1.0/ (1.0 + yield)^elapsed ) > > | otherwise = Nothing > > > > continuousCompounding :: Compounding > > continuousCompounding yield elapsed > > | yield > minusOne = Just (exp( minusOne * yield * fromIntegral > > elapsed ) ) > > | otherwise = Nothing > > > > pvs :: Compounding -> Double -> [Double] -> Maybe [Double] > > pvs df yield cashflow = zipWithM ( \c -> (>>= \d -> return $ c*d ) ) > > cashflow discounts > > where discounts = map discount times > > discount = df yield > > > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > From jakubuv at gmail.com Thu Aug 20 06:29:24 2009 From: jakubuv at gmail.com (Jan Jakubuv) Date: Thu Aug 20 06:10:12 2009 Subject: [Haskell-beginners] my ugly code and the Maybe monad In-Reply-To: <1250722667.2431.65.camel@localhost.localdomain> References: <1250631705.2431.24.camel@localhost.localdomain> <20090819115342.GA25258@lxultra2.macs.hw.ac.uk> <1250722667.2431.65.camel@localhost.localdomain> Message-ID: <20090820102924.GA24428@lxultra2.macs.hw.ac.uk> On Wed, Aug 19, 2009 at 11:57:47PM +0100, Simon Parry wrote: > Thanks Jan, very helpful and you're right I am just trying to combine 2 > lists; one with 'wrapped' values, one without. > > > You can write your own version of `liftM2` (from > > `Control.Monad`) like this: > > > > liftM2snd f a mb = do { b <- mb; return (f a b) } > > > > so the b <- mb bit is 'unwrapping' the Maybe b to use it with the pure > function f? That's correct. In fact it is just a syntactic abbreviation (sugar) for liftM2snd f a mb = mb >>= \b -> return (f a b) You can always rewrite expressions with `do` using just `>>=`, `>>`, and `->`. (Note that `<-` becomes the ?dot? `->`.) > I guess I didn't realise this as I've only seen it in the IO monad, but > naturally it would work with all monads. > > > You can verify that > > > > liftM2snd == (fmap .) > > if I look at this in GHCi the liftM2snd acts over monads and the (fmap .) acts over functors. > Now I'm still trying to get comfortable with simple monad manipulations so maybe I should just > read this as functors are equivalent to monads and not worry too much about it yet? > With that in mind fmap acts to map some pure function over a 'wrapped' value? > Every Monad is automatically a Functor as well. You can define `fmap` using monadic operations: fmap f ma = ma >>= return . f Anyway, for some reasons this is not done automatically. You can do it automatically with some GHC extensions. Load this into GHCi (don't forget the first line): {-# OPTIONS -XFlexibleInstances -XUndecidableInstances #-} instance Monad m => Functor m where fmap f ma = ma >>= return . f And here we go (in my GHCi 6.10.4): *Main> :t fmap fmap :: (Monad f) => (a -> b) -> f a -> f b Usually, however, you don't need to do this because all instances of Monad are already instances of Functor. Also note that fmap :: (Functor f) => (a -> b) -> f a -> f b holds as well, that is, the type of `fmap` is ambiguous (because of the GHC extensions above). Sincerely, Jan. -- Heriot-Watt University is a Scottish charity registered under charity number SC000278. From jack at realmode.com Sun Aug 23 14:12:16 2009 From: jack at realmode.com (I. J. Kennedy) Date: Sun Aug 23 13:52:08 2009 Subject: [Haskell-beginners] type inference question Message-ID: <1008bfc90908231112o466c036ey24530ce89c09ad0@mail.gmail.com> Given a sort function that works on numbers, you can sort in reverse order by first negating the list, then sorting, then negating again: Prelude Data.List> let revsort = (map negate) . sort . (map negate) The function sort takes any list of Ord; negate works on any Num. Prelude Data.List> :t negate negate :: (Num a) => a -> a Prelude Data.List> :t sort sort :: (Ord a) => [a] -> [a] I'd therefore expect my revsort function to work on any type that is both an Ord and a Num. However: Prelude Data.List> :t revsort revsort :: [Integer] -> [Integer] I was expecting something like revsort :: (Ord a, Num a) => [a] -> [a] instead. Question: Why did the GHCI's type inference mechanism jump to the conclusion that revsort should only work with Integer lists? From daniel.is.fischer at web.de Sun Aug 23 14:44:25 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Aug 23 14:25:15 2009 Subject: [Haskell-beginners] type inference question In-Reply-To: <1008bfc90908231112o466c036ey24530ce89c09ad0@mail.gmail.com> References: <1008bfc90908231112o466c036ey24530ce89c09ad0@mail.gmail.com> Message-ID: <200908232044.25233.daniel.is.fischer@web.de> Am Sonntag 23 August 2009 20:12:16 schrieb I. J. Kennedy: > Given a sort function that works on numbers, you can sort > in reverse order by first negating the list, then sorting, then > negating again: > > Prelude Data.List> let revsort = (map negate) . sort . (map negate) > > The function sort takes any list of Ord; negate works on any Num. > > Prelude Data.List> :t negate > negate :: (Num a) => a -> a > Prelude Data.List> :t sort > sort :: (Ord a) => [a] -> [a] > > I'd therefore expect my revsort function to work on any type that is > both an Ord and a Num. However: > > Prelude Data.List> :t revsort > revsort :: [Integer] -> [Integer] > > I was expecting something like > revsort :: (Ord a, Num a) => [a] -> [a] > instead. > > Question: Why did the GHCI's type inference mechanism jump to > the conclusion that revsort should only work with Integer lists? Because you defined it without an argument or type signature. By the monomorphism restriction ( http://www.haskell.org/haskellwiki/Monomorphism_Restriction ), such values must have a monomorphic type and by the defaulting rules, that is chosen as Integer. You can a) specify a type signature (good in source files) b) define it as a function binding let revsort xs = map negate . sort . map negate $ xs c) turn off the monomorphism restriction in ghci: Prelude> :set -XNoMonomorphismRestriction Prelude> :m +Data.List Prelude Data.List> let revsort = map negate . sort . map negate Prelude Data.List> :t revsort revsort :: (Num a, Ord a) => [a] -> [a] (might put :set -XNoMonomorphismRestriction in your .ghci file) btw, another way to revsort is let revsort = sortBy (flip compare) From mpm at alumni.caltech.edu Sun Aug 23 20:44:27 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sun Aug 23 20:24:19 2009 Subject: [Haskell-beginners] definition of combinator Message-ID: <4A91E26B.9010808@alumni.caltech.edu> Although I can use libraries like Parsec, I don't really understand what a combinator is, theoretically. There is an article here http://en.wikipedia.org/wiki/Combinator with the statement "A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments." Okay, so I believe a "higher-order function" is a function that takes function(s) as its argument(s). I don't know what "uses only function application" means. Application of what functions to what? Can someone give a concrete example that's simple? Thanks, Mike From allbery at ece.cmu.edu Sun Aug 23 21:06:25 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sun Aug 23 20:46:16 2009 Subject: [Haskell-beginners] definition of combinator In-Reply-To: <4A91E26B.9010808@alumni.caltech.edu> References: <4A91E26B.9010808@alumni.caltech.edu> Message-ID: <6DF41B5B-6437-4E71-B9BF-C3CB5E8DBE9C@ece.cmu.edu> On Aug 23, 2009, at 20:44 , Michael Mossey wrote: > Although I can use libraries like Parsec, I don't really understand > what a combinator is, theoretically. There is an article here Example: in Parsec, "many" is a combinator which takes a parser as an argument and produces a parser that matches multiple successive copies of whatever the argument matches. It doesn't need to know anything about its argument except that it's a parser. This kind of function lets you build up complex but general parsers from smaller pieces. -- brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery@kf8nh.com system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon university KF8NH -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 195 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20090823/a5cb87bd/PGP.bin From jakubuv at gmail.com Mon Aug 24 06:23:29 2009 From: jakubuv at gmail.com (Jan Jakubuv) Date: Mon Aug 24 06:03:33 2009 Subject: [Haskell-beginners] definition of combinator In-Reply-To: <4A91E26B.9010808@alumni.caltech.edu> References: <4A91E26B.9010808@alumni.caltech.edu> Message-ID: <20090824102329.GA13891@lxultra2.macs.hw.ac.uk> Hi Michael, On Sun, Aug 23, 2009 at 05:44:27PM -0700, Michael Mossey wrote: > "A combinator is a higher-order function that uses only function > application and earlier defined combinators to define a result from its > arguments." > > Okay, so I believe a "higher-order function" is a function that takes > function(s) as its argument(s). I don't know what "uses only function > application" means. Application of what functions to what? Briefly, a combinator applies ?earlier defined combinators? to ?its arguments?. But remember that a combinator's argument can be a function as well, so it may become more complicated. Then it simply applies functions (other combinators, combinator's arguments, library functions) to their arguments (other combinators, combinator's arguments, library functions, constants, ...). Finally, I guess that the word ?only? suggests that it doesn't read any parsed text by itself but it only calls (combine) other parsers. Sincerely, Jan. -- Heriot-Watt University is a Scottish charity registered under charity number SC000278. From mpm at alumni.caltech.edu Mon Aug 24 13:45:06 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Mon Aug 24 13:25:08 2009 Subject: [Haskell-beginners] definition of combinator In-Reply-To: <6DF41B5B-6437-4E71-B9BF-C3CB5E8DBE9C@ece.cmu.edu> References: <4A91E26B.9010808@alumni.caltech.edu> <6DF41B5B-6437-4E71-B9BF-C3CB5E8DBE9C@ece.cmu.edu> Message-ID: <4A92D1A2.8040703@alumni.caltech.edu> Brandon S. Allbery KF8NH wrote: > On Aug 23, 2009, at 20:44 , Michael Mossey wrote: >> Although I can use libraries like Parsec, I don't really understand >> what a combinator is, theoretically. There is an article here > > > Example: in Parsec, "many" is a combinator which takes a parser as an > argument and produces a parser that matches multiple successive copies > of whatever the argument matches. It doesn't need to know anything > about its argument except that it's a parser. This kind of function > lets you build up complex but general parsers from smaller pieces. > What makes it a "combinator" and not a general function? The fact that it takes only a function (parser) as input (no data) and produces only a function? Is any function that takes only functions and produces a function called a combinator? Thanks, Mike From apfelmus at quantentunnel.de Tue Aug 25 04:02:19 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Tue Aug 25 03:42:30 2009 Subject: [Haskell-beginners] Re: definition of combinator In-Reply-To: <4A92D1A2.8040703@alumni.caltech.edu> References: <4A91E26B.9010808@alumni.caltech.edu> <6DF41B5B-6437-4E71-B9BF-C3CB5E8DBE9C@ece.cmu.edu> <4A92D1A2.8040703@alumni.caltech.edu> Message-ID: Michael Mossey wrote: > > Brandon S. Allbery KF8NH wrote: >> >> Example: in Parsec, "many" is a combinator which takes a parser as an >> argument and produces a parser that matches multiple successive copies >> of whatever the argument matches. It doesn't need to know anything >> about its argument except that it's a parser. This kind of function >> lets you build up complex but general parsers from smaller pieces. > > What makes it a "combinator" and not a general function? The fact that > it takes only a function (parser) as input (no data) and produces only a > function? Is any function that takes only functions and produces a > function called a combinator? The term "combinator" is just another name for "function", but with a special connotation. It mainly applies to functions building and combining values of an abstract data type. In particular, parsers are abstract. They are defined by the following combinators return :: a -> P a (>>=) :: P a -> (a -> P b) -> P b symbol :: P Char mzero :: P a mplus :: P a -> P a -> P a and an observation function like run :: P a -> String -> Maybe a The above functions are called combinators because they make new parsers from old ones. In contrast, run turns a parser into something else, so it's not called "combinator". Regards, apfelmus -- http://apfelmus.nfshost.com From mpm at alumni.caltech.edu Sat Aug 29 10:22:06 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sat Aug 29 10:01:50 2009 Subject: [Haskell-beginners] pretty-printing data Message-ID: <4A99398E.4040403@alumni.caltech.edu> For debugging purposes I'm interested in pretty-printing data; to start with, lists of algebraic data types. Basically I'd like 'show' with the ability to put each entry of a list on a separate line, and indented. Note that the algebraic data might have an inner list as one of its elements, so this is a non-obvious formatting problem. I believe I can make instances of Show, can I not? Is there something called showList which I can use to code my own method of showing lists of a particular type? My understanding is that I can't make [a] an instance of Show; hence they provided showList. So basically, I'm wondering if a pretty-printing (for data!) library already exists, or whether I should try to make instances of Show. Thanks, Mike From jack at realmode.com Sat Aug 29 11:43:02 2009 From: jack at realmode.com (I. J. Kennedy) Date: Sat Aug 29 11:22:36 2009 Subject: [Haskell-beginners] partitions made of unique parts Message-ID: <1008bfc90908290843l688c4b9eu5e819a1c362e4d20@mail.gmail.com> The following function finds all the partitions of an integer that are made of unique parts. It works, but I'm not happy with it--seems too complex. Is there a more haskelly (clever) way to implement this? -- parts n finds all the partitions of n having unique parts -- helper function parts' n r m finds partitions of n from a set r of remaining possible parts, -- with a minimum part of m. parts n = parts' n [1..n] 1 where parts' 0 _ _ = [[]] -- there's always one way ([]) to get a sum of 0 parts' n [] _ = [] -- if n /= 0, there are no possible partitions of the empty list parts' n remaining atleast = [(x:y) | x <- filter (>= atleast) remaining, y <- (parts' (n-x) (remaining \\ [x])) x] *Main> parts 11 [[1,2,3,5],[1,2,8],[1,3,7],[1,4,6],[1,10],[2,3,6],[2,4,5],[2,9],[3,8],[4,7],[5,6],[11]] From daniel.is.fischer at web.de Sat Aug 29 12:39:18 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Aug 29 12:21:58 2009 Subject: [Haskell-beginners] partitions made of unique parts In-Reply-To: <1008bfc90908290843l688c4b9eu5e819a1c362e4d20@mail.gmail.com> References: <1008bfc90908290843l688c4b9eu5e819a1c362e4d20@mail.gmail.com> Message-ID: <200908291839.18876.daniel.is.fischer@web.de> Am Samstag 29 August 2009 17:43:02 schrieb I. J. Kennedy: > The following function finds all the partitions of an integer that are > made of unique parts. > It works, but I'm not happy with it--seems too complex. Is there a > more haskelly (clever) > way to implement this? > > -- parts n finds all the partitions of n having unique parts > -- helper function parts' n r m finds partitions of n from a set > r of remaining possible parts, > -- with a minimum part of m. > > parts n = parts' n [1..n] 1 where > parts' 0 _ _ = [[]] -- there's always one way ([]) > to get a sum of 0 > parts' n [] _ = [] -- if n /= 0, there are no > possible partitions of the empty list > parts' n remaining atleast = [(x:y) | x <- filter (>= atleast) > remaining, y <- (parts' (n-x) (remaining \\ [x])) x] > > > *Main> parts 11 > [[1,2,3,5],[1,2,8],[1,3,7],[1,4,6],[1,10],[2,3,6],[2,4,5],[2,9],[3,8],[4,7] >,[5,6],[11]] You don't have to have a list of possible parts, the possible parts follow from the minimum: parts :: Int -> [[Int]] -- or (Num a, Ord a) => a -> [[a]] parts 0 = [[]] parts n | n < 0 = [] | otherwise = mpart n 1 where -- mpart m k partitions m into distinct parts of size at least k mpart m k | m < k = [] | m <= 2*k = [[m]] | otherwise = map (k:) (mpart (m-k) (k+1)) ++ mpart m (k+1) From daniel.is.fischer at web.de Sat Aug 29 13:39:42 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Aug 29 13:20:46 2009 Subject: [Haskell-beginners] partitions made of unique parts In-Reply-To: <1008bfc90908290843l688c4b9eu5e819a1c362e4d20@mail.gmail.com> References: <1008bfc90908290843l688c4b9eu5e819a1c362e4d20@mail.gmail.com> Message-ID: <200908291939.42461.daniel.is.fischer@web.de> Am Samstag 29 August 2009 17:43:02 schrieb I. J. Kennedy: > The following function finds all the partitions of an integer that are > made of unique parts. > It works, but I'm not happy with it--seems too complex. Is there a > more haskelly (clever) > way to implement this? > > -- parts n finds all the partitions of n having unique parts > -- helper function parts' n r m finds partitions of n from a set > r of remaining possible parts, > -- with a minimum part of m. > > parts n = parts' n [1..n] 1 where > parts' 0 _ _ = [[]] -- there's always one way ([]) > to get a sum of 0 > parts' n [] _ = [] -- if n /= 0, there are no > possible partitions of the empty list > parts' n remaining atleast = [(x:y) | x <- filter (>= atleast) > remaining, y <- (parts' (n-x) (remaining \\ [x])) x] > > > *Main> parts 11 > [[1,2,3,5],[1,2,8],[1,3,7],[1,4,6],[1,10],[2,3,6],[2,4,5],[2,9],[3,8],[4,7],[5,6],[11]] Another thing: In your list of possible parts, you keep values smaller than the minimum value and values larger than the remaining value to be partitioned. This leads to horrible performance (1 second to partition 20 and 20 minutes to partition 30 on my box) since you have to scan through unnecessarily long lists and you try to partition negative numbers. In particular the latter cripples performance, inserting a guard ? parts' n remaining atleast | n < 0 = [] | otherwise = [(x:y) | x <- filter (>= atleast) remaining , y <- (parts' (n-x) (remaining \\ [x])) (x)] into the last clause of parts' brings the time for parts 30 down to 0.06 seconds, for parts 70 to 2.06 seconds :) (still about 100 times slower than the code from my previous post). From magnus at therning.org Sat Aug 29 18:09:15 2009 From: magnus at therning.org (Magnus Therning) Date: Sat Aug 29 17:48:47 2009 Subject: [Haskell-beginners] pretty-printing data In-Reply-To: <4A99398E.4040403@alumni.caltech.edu> References: <4A99398E.4040403@alumni.caltech.edu> Message-ID: On Sat, Aug 29, 2009 at 3:22 PM, Michael Mossey wrote: > For debugging purposes I'm interested in pretty-printing data; to start > with, lists of algebraic data types. Basically I'd like 'show' with the > ability to put each entry of a list on a separate line, and indented. Note > that the algebraic data might have an inner list as one of its elements, so > this is a non-obvious formatting problem. > > I believe I can make instances of Show, can I not? Is there something called > showList which I can use to code my own method of showing lists of a > particular type? My understanding is that I can't make [a] an instance of > Show; hence they provided showList. > > So basically, I'm wondering if a pretty-printing (for data!) library already > exists, or whether I should try to make instances of Show. Take a look at the pretty-printing libraries available on Hackage. I've personally used two of them, pretty and wl-pprint. I'm fairly sure both of them define pretty-printing for lists, but I don't know whether it's done the way you want. /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe From poliquin at softcomp.com Sun Aug 30 02:57:25 2009 From: poliquin at softcomp.com (Tom Poliquin) Date: Sun Aug 30 02:39:53 2009 Subject: [Haskell-beginners] Type Class Woes .. Message-ID: <200908292357.25041.poliquin@softcomp.com> I've been writing Haskell programs (even useful ones :-) ) for awhile and I thought it was time to experiment with my own type classes. I chose the (contrived toy) problem of computing the volume of various fruits. First I wrote the code using algebraic data types .. (shown below); then I 'converted' it to use type classes (also shown below) The type class version gives me the errors .. Main.hs:12:16: Not in scope: type constructor or class `Banana' Main.hs:15:16: Not in scope: type constructor or class `Watermelon' .. which makes sense since Banana and Watermelon are 'data constructors' and not 'type constructors'. The problem is I'm not sure how to get around it .. If I try putting data Orange = Orange data Banana = Banana .. then what does 'initFruit' return .. ? it can't return [Fruit FruitType] anymore .. It seems like this should be a simple problem. I'm clearly not 'getting it'. Any help greatly appreciated, Tom ---------- Algegraic Data Type Version (works) ---------- module Main where data Fruit a = F {radius::Double, len::Double, fType::a} data FruitType = Orange | Apple | Banana | Watermelon deriving Show initFruit :: [Fruit FruitType] initFruit = [ (F 3.0 0.0 Orange), (F 3.0 0.0 Apple), (F 3.0 2.0 Banana), (F 40.0 20.0 Watermelon) ] volume :: Fruit FruitType -> Double volume F{radius=r,len=l,fType=Orange} = (4.0/3.0) * pi * r * r * r volume F{radius=r,len=l,fType=Apple} = (4.0/3.0) * pi * r * r * r volume F{radius=r,len=l,fType=Banana} = pi * (r * r) * l volume F{radius=r,len=l,fType=Watermelon} = (4.0/3.0) * pi * (2.0 * r) * l * (0.5 * l) ---------- -- Main -- ---------- main = do fruit <- return $ initFruit mapM (\f@(F{fType=t}) -> putStrLn ("Volume -> " ++ show t ++ " = " ++ show (volume f))) fruit Volume -> Orange = 113.09733552923255 Volume -> Apple = 113.09733552923255 Volume -> Banana = 56.548667764616276 Volume -> Watermelon = 67020.64327658225 ---------- Type Class Version (fails) ---------- module Main where data Fruit a = F {radius::Double, len::Double, fType::a} data FruitType = Orange | Apple | Banana | Watermelon class Volume a where volume :: (FruitType a) => Fruit a -> Double -- default spherical fruit .. volume F{radius=r,len=l} = (4.0/3.0) * pi * r * r * r instance Volume Banana where volume F{radius=r,len=l} = pi * (r * r) * l instance Volume Watermelon where volume F{radius=r,len=l} = (4.0/3.0) * pi * (2.0 * r) * l * (0.5 * l) initFruit :: [Fruit FruitType] initFruit = [ (F 3.0 0.0 Orange), (F 3.0 0.0 Apple), (F 3.0 2.0 Banana), (F 40.0 20.0 Watermelon) ] ---------- -- Main -- ---------- main = do fruit <- return $ initFruit mapM (\f@(F{fType=t}) -> putStrLn ("Volume -> " ++ show t ++ " = " ++ show (volume f))) fruit Main.hs:12:16: Not in scope: type constructor or class `Banana' Main.hs:15:16: Not in scope: type constructor or class `Watermelon' From jamarier at gmail.com Sun Aug 30 05:11:23 2009 From: jamarier at gmail.com (Javier M Mora) Date: Sun Aug 30 04:50:19 2009 Subject: [Haskell-beginners] Type Class Woes .. In-Reply-To: <200908292357.25041.poliquin@softcomp.com> References: <200908292357.25041.poliquin@softcomp.com> Message-ID: <4A9A423B.2090808@gmail.com> Tom Poliquin escribi?: > ---------- > Type Class Version (fails) > ---------- > > module Main where > > data Fruit a = F {radius::Double, len::Double, fType::a} > > data FruitType = Orange | Apple | Banana | Watermelon > > class Volume a where > volume :: (FruitType a) => Fruit a -> Double > -- default spherical fruit .. > volume F{radius=r,len=l} = (4.0/3.0) * pi * r * r * r > > instance Volume Banana where > volume F{radius=r,len=l} = pi * (r * r) * l The problem here is you only can instance datatypes. The datatype here is FruitType. Banana is a DataConstructor. How to fix it? (I'm newbie too, so you have to think more with my answer) A posibility is create a data type for each frute: ----- [...] class FruitType a where volume :: Fruit a -> Double -- default spherical volume F{radius=r,len=l} = (4.0/3.0) * pi * r * r * r data Orange = Orange data Apple = Apple data Banana = Banana data Watermelon = Watermelon instance FruitType Orange where instance FruitType Apple where instance FruitType Banana where volume F{radius=r,len=l} = pi * (r * r) * l instance FruitType Watermelon where volume F{radius=r,len=l} = (4.0/3.0) * pi * (2.0 * r) * l * (0.5 * l) [...] ----- But, you can't later define a list with mixed types because the first one is "::Fruit Orange" and the second is "::Fruit Apple" ----- WRONG vvv initFruit :: FruitType a => [Fruit a] initFruit = [ (F 3.0 0.0 Orange), (F 3.0 0.0 Apple), (F 3.0 2.0 Banana), (F 40.0 20.0 Watermelon) ] ----- WRONG ^^^ The second posibilitie is use patterns. So, I'm sorry this example is very similar to your first attempt: ----- SECOND ATTEMPT module Main where data Fruit a = F {radius::Double, len::Double, fType::a} data FruitType = Orange | Apple | Banana | Watermelon deriving Show class Volume a where volume:: a -> Double instance Volume (Fruit FruitType) where volume F{radius=r,len=l,fType=Banana} = pi * (r * r) * l volume F{radius=r,len=l,fType=Watermelon} = (4.0/3.0) * pi * (2.0 * r) * l * (0.5 * l) volume F{radius=r,len=l} = (4.0/3.0) * pi * r * r * r initFruit :: [Fruit FruitType] initFruit = [ (F 3.0 0.0 Orange), (F 3.0 0.0 Apple), (F 3.0 2.0 Banana), (F 40.0 20.0 Watermelon) ] ---------- -- Main -- ---------- main = do fruit <- return $ initFruit mapM (\f@(F{fType=t}) -> putStrLn ("Volume -> " ++ show t ++ " = " ++ show (volume f))) fruit But, you need define "FlexibleInstances" add on because: "instance Volume (Fruit FruitType)" is not standard Haskell THIRD IDEA. Make a wrapper volume function: ----- module Main where data Fruit a = F {radius::Double, len::Double, fType::a} data FruitType = Orange | Apple | Banana | Watermelon deriving Show class Volume a where volume:: a -> Double -> Double -> Double instance Volume FruitType where volume Banana r l = pi * (r * r) * l volume Watermelon r l = (4.0/3.0) * pi * (2.0 * r) * l * (0.5 * l) volume _ r l = (4.0/3.0) * pi * r * r * r volumeFruit F{radius=r,len=l,fType=f} = volume f r l initFruit :: [Fruit FruitType] initFruit = [ (F 3.0 0.0 Orange), (F 3.0 0.0 Apple), (F 3.0 2.0 Banana), (F 40.0 20.0 Watermelon) ] ---------- -- Main -- ---------- main = do let fruit = initFruit mapM (\f@(F{fType=t}) -> putStrLn ("Volume -> " ++ show t ++ " = " ++ show (volumeFruit f))) fruit ----- So. This problem is more interesting that I thought. Javier M Mora. PD. initFruit is a Pure Function. I prefer the "let" construction. From timothyea at comcast.net Sun Aug 30 06:57:47 2009 From: timothyea at comcast.net (Tim Attwood) Date: Sun Aug 30 06:44:36 2009 Subject: [Haskell-beginners] Re: Type Class Woes .. In-Reply-To: <200908292357.25041.poliquin@softcomp.com> References: <200908292357.25041.poliquin@softcomp.com> Message-ID: Orange, Apple etc are values of type FruitType, not types themselves. module Main where data FruitType = Orange | Apple | Banana | Watermelon deriving (Eq, Show) data Fruit = Fruit {fruitRadius::Double, fruitLength::Double, fType::FruitType} data VegType = Tomato | StringBean deriving (Eq, Show) data Veg = Veg {vegRadius::Double, vegLength::Double, vType::VegType} data GeoType = Sphere | Elipsoid deriving (Eq, Show) data Geometric = Geo {radius1::Double, radius2::Double, radius3::Double, gType::GeoType} class ObjectCalc a where volume :: a -> Double surfaceArea :: a -> Double instance ObjectCalc Geometric where volume g | gType g == Sphere = (4.0/3.0) * pi * ( (radius1 g) ** 3.0) | gType g == Elipsoid = (4.0/3.0) * pi * (radius1 g) * (radius2 g) * (radius3 g) | otherwise = undefined surfaceArea g = undefined instance ObjectCalc Fruit where volume f | fType f == Orange = volume (Geo (fruitRadius f) undefined undefined Sphere) | fType f == Apple = volume (Geo (fruitRadius f) undefined undefined Sphere) | fType f == Banana = volume (Geo (fruitRadius f) (fruitRadius f) (fruitLength f) Elipsoid) | fType f == Watermelon = volume (Geo ((fruitRadius f)*2.0) ((fruitLength f)*0.5) (fruitLength f) Elipsoid) | otherwise = undefined surfaceArea f = undefined instance ObjectCalc Veg where volume v = undefined surfaceArea v = undefined initFruit :: [Fruit] initFruit = [ (Fruit 3.0 0.0 Orange), (Fruit 3.0 0.0 Apple), (Fruit 3.0 2.0 Banana), (Fruit 40.0 20.0 Watermelon) ] main = let f = initFruit v = map volume f ft = map fType f s = zipWith (\a b -> putStrLn ("Volume -> " ++ (show a) ++ " = " ++ (show b))) ft v in sequence_ s From patrick.leboutillier at gmail.com Sun Aug 30 08:32:56 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Sun Aug 30 08:12:27 2009 Subject: [Haskell-beginners] Type Class Woes .. In-Reply-To: <200908292357.25041.poliquin@softcomp.com> References: <200908292357.25041.poliquin@softcomp.com> Message-ID: Hi, volume :: Fruit FruitType -> Double > volume F{radius=r,len=l,fType=Orange} = (4.0/3.0) * pi * r * r * r > > volume F{radius=r,len=l,fType=Apple} = (4.0/3.0) * pi * r * r * r > volume F{radius=r,len=l,fType=Banana} = pi * (r * r) * l > volume F{radius=r,len=l,fType=Watermelon} = (4.0/3.0) * pi * (2.0 * r) > * l * (0.5 * l) Can anyone explain the above pattern matching syntax? I've never seen it before... Thanks, Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090830/a967a563/attachment.html From daniel.is.fischer at web.de Sun Aug 30 09:06:02 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Aug 30 08:46:36 2009 Subject: [Haskell-beginners] Type Class Woes .. In-Reply-To: References: <200908292357.25041.poliquin@softcomp.com> Message-ID: <200908301506.02234.daniel.is.fischer@web.de> Am Sonntag 30 August 2009 14:32:56 schrieb Patrick LeBoutillier: > Hi, > > volume :: Fruit FruitType -> Double > > > volume F{radius=r,len=l,fType=Orange} = (4.0/3.0) * pi * r * r * r > > > > > > volume F{radius=r,len=l,fType=Apple} = (4.0/3.0) * pi * r * r * r > > volume F{radius=r,len=l,fType=Banana} = pi * (r * r) * l > > volume F{radius=r,len=l,fType=Watermelon} = (4.0/3.0) * pi * (2.0 * r) > > * l * (0.5 * l) > > Can anyone explain the above pattern matching syntax? I've never seen it > before... > > > Thanks, > > Patrick It's named-field syntax, cf. http://haskell.org/onlinereport/exps.html#sect3.15 If you have a type with named fields, like data FType = Con1 { field1 :: Int, field2 :: Bool } | Con2 { field1 :: Int, field3 :: Char } you can pattern-match either by position: fun (Con1 i b) = ... or by named field syntax: fun Con1{field2=True, field1=x} = ... -- corresponds to fun (Con1 x True) fun Con2{field3='a'} = ... -- fun (Con2 _ 'a') It's very convenient if you need only a few arguments of a multi-argument constructor: fun C{fieldx=y} vs. fun (C _ _ _ _ _ y _ _ _ _) From chaddai.fouche at gmail.com Sun Aug 30 09:10:28 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Sun Aug 30 08:50:00 2009 Subject: [Haskell-beginners] Type Class Woes .. In-Reply-To: References: <200908292357.25041.poliquin@softcomp.com> Message-ID: On Sun, Aug 30, 2009 at 2:32 PM, Patrick LeBoutillier wrote: >> volume :: Fruit FruitType -> Double >> volume F{radius=r,len=l,fType=Orange} = (4.0/3.0) * pi * r * r * r >> >> volume F{radius=r,len=l,fType=Apple} ?= (4.0/3.0) * pi * r * r * r >> volume F{radius=r,len=l,fType=Banana} = pi * (r * r) * l >> volume F{radius=r,len=l,fType=Watermelon} = (4.0/3.0) * pi * (2.0 * r) >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? * l * (0.5 * l) > > Can anyone explain the above pattern matching syntax? I've never seen it > before... It's part of what record syntax allows : record pattern. record_pattern = data_constructor '{' (field_pattern ',')* '}' field_pattern = field_name '=' pattern You don't have to use all the fields of the datatype in a pattern if you don't need them all. A special case is when you put zero field_pattern in the {}, in this case you can even use this syntax for regular datatype (no record syntax), to write thing like : > isJust Just {} = True > isJust _ = False (especially interesting for constructors with plenty of parameters, of course) ----------- To come back to the initial subject, if you use datatypes and typeclass rather than dataconstructors and pattern matching to allow extensibility of data, you can still have a list of different fruits type, using existential types, though that is not without minus : > data Fruit a = F { radius, length :: Double } > data Orange; data Banana; > > class Volume a where > vol :: a -> Double > > instance Volume (Fruit Orange) where > vol (F r _) = (4/3) * pi * r * r * r > instance Volume (Fruit Banana) where > vol (F r l) = pi * (r * r) * l > > data Volumic = Volume a => V a > > fruit_list :: [Volumic] > fruit_list = [V (F 3 undefined :: Fruit Orange), V (F 1 6 :: Fruit Banana) ] In this particular case it is really uninteresting since you could as well stock a list of volumes (the only thing you can do with a Volumic is get the volume of its content) but with more versatile typeclass, it may be different. -- Jeda? From poliquin at softcomp.com Sun Aug 30 15:14:57 2009 From: poliquin at softcomp.com (Tom Poliquin) Date: Sun Aug 30 14:57:24 2009 Subject: [Haskell-beginners] Re: Type Class Woes .. In-Reply-To: References: <200908292357.25041.poliquin@softcomp.com> Message-ID: <200908301214.57658.poliquin@softcomp.com> Thanks everyone for the replies! Comments below .. Tom Poliquin wrote: > I chose the (contrived toy) problem of computing the volume > of various fruits. > First I wrote the code using algebraic data types .. > ...then I 'converted' it to use type classes > The type class version gives me the errors .. > Main.hs:12:16: Not in scope: type constructor or class `Banana' > Main.hs:15:16: Not in scope: type constructor or class `Watermelon' On Sunday 30 August 2009 03:57, Tim Attwood wrote: > Orange, Apple etc are values of type FruitType, not types themselves. > > module Main where > > data FruitType = Orange | Apple | Banana | Watermelon deriving (Eq, Show) > data Fruit = Fruit {fruitRadius::Double, fruitLength::Double, > fType::FruitType} > > data VegType = Tomato | StringBean deriving (Eq, Show) > data Veg = Veg {vegRadius::Double, vegLength::Double, vType::VegType} > > data GeoType = Sphere | Elipsoid deriving (Eq, Show) > data Geometric = Geo {radius1::Double, radius2::Double, radius3::Double, > gType::GeoType} > > class ObjectCalc a where > ? ?volume :: a -> Double > ? ?surfaceArea :: a -> Double > > instance ObjectCalc Geometric where > ? ?volume g | gType g == Sphere ? = (4.0/3.0) * pi * ( (radius1 g) ** 3.0) > ? ? ? ? ? ? | gType g == Elipsoid = (4.0/3.0) * pi * (radius1 g) * (radius2 > g) * (radius3 g) > ? ? ? ? ? ? | otherwise = undefined > ? ?surfaceArea g = undefined > > instance ObjectCalc Fruit where > ? ?volume f | fType f == Orange ? ? = volume (Geo (fruitRadius f) undefined > undefined Sphere) > ? ? ? ? ? ? | fType f == Apple ? ? ?= volume (Geo (fruitRadius f) undefined > undefined Sphere) > ? ? ? ? ? ? | fType f == Banana ? ? = volume (Geo (fruitRadius f) > (fruitRadius f) (fruitLength f) Elipsoid) > ? ? ? ? ? ? | fType f == Watermelon = volume (Geo ((fruitRadius f)*2.0) > ((fruitLength f)*0.5) (fruitLength f) Elipsoid) > ? ? ? ? ? ? | otherwise ? ? ? ? ? ? = undefined > ? ?surfaceArea f = undefined > > instance ObjectCalc Veg where > ? ?volume v = undefined > ? ?surfaceArea v = undefined > > initFruit :: [Fruit] > initFruit = [ > ? ? ? ? ? ? ? (Fruit ?3.0 ?0.0 Orange), > ? ? ? ? ? ? ? (Fruit ?3.0 ?0.0 Apple), > ? ? ? ? ? ? ? (Fruit ?3.0 ?2.0 Banana), > ? ? ? ? ? ? ? (Fruit 40.0 20.0 Watermelon) > ? ? ? ? ? ? ] > > main = > ? ?let f = initFruit > ? ? ? ?v = map volume f > ? ? ? ?ft = map fType f > ? ? ? ?s = zipWith (\a b -> putStrLn ("Volume -> " ++ (show a) ++ " = " ++ > (show b))) ft v > ? ?in sequence_ s This looks great .. it even added an extra idea .... that different fruit/vegs have different geometric shapes .. Abstractly then .. 'Grown Things' each have a geometric shape, then each geometric shape has a method for computing volume and surface area .. Javier M Mora wrote: > THIRD IDEA. Make a wrapper volume function: > > ----- > module Main where > > data Fruit a = F {radius::Double, len::Double, fType::a} > > data FruitType = Orange | Apple | Banana | Watermelon > ? ?deriving Show > > class Volume a where > ? ?volume:: a -> Double -> Double -> Double > > instance Volume FruitType where > ? ?volume Banana r l = pi * (r * r) * l > ? ?volume Watermelon r l = (4.0/3.0) * pi * (2.0 * r) * l * (0.5 * l) > ? ?volume _ r l = (4.0/3.0) * pi * r * r * r > > volumeFruit F{radius=r,len=l,fType=f} = volume f r l > > initFruit :: [Fruit FruitType] > initFruit = [ > ? ? ? ? ? ? ? ?(F ?3.0 ?0.0 Orange), > ? ? ? ? ? ? ? ?(F ?3.0 ?0.0 Apple), > ? ? ? ? ? ? ? ?(F ?3.0 ?2.0 Banana), > ? ? ? ? ? ? ? ?(F 40.0 20.0 Watermelon) > ? ? ? ? ? ? ?] > > ---------- > -- Main -- > ---------- > > main = do > > ? ? let fruit = initFruit > > ? ? mapM (\f@(F{fType=t}) -> putStrLn ("Volume -> " ++ show t ++ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?" = " ++ show (volumeFruit f))) fruit > ----- > > > So. This problem is more interesting that I thought. > > Javier M Mora. This has the flavor (no pun intended) of pattern matching since there's only one instance .. Chadda? Fouch? wrote: > To come back to the initial subject, if you use datatypes and > typeclass rather than dataconstructors and pattern matching to allow > extensibility of data, you can still have a list of different fruits > type, using existential types, though that is not without minus : > data Fruit a = F { radius, length :: Double } > data Orange; data Banana; > > class Volume a where > vol :: a -> Double > > instance Volume (Fruit Orange) where > vol (F r _) = (4/3) * pi * r * r * r > instance Volume (Fruit Banana) where > vol (F r l) = pi * (r * r) * l > > data Volumic = Volume a => V a > > fruit_list :: [Volumic] > fruit_list = [V (F 3 undefined :: Fruit Orange), V (F 1 6 :: Fruit Banana) ] > In this particular case it is really uninteresting since you could as > well stock a list of volumes (the only thing you can do with a Volumic > is get the volume of its content) but with more versatile typeclass, > it may be different. I've never used existentials .. but this seems like a powerful idea. Unfortunately I couldn't get this to compile .. It was unhappy about 'data Volumic' so I changed it to 'data Volumic a' .. it was still unhappy and took me down the road of compiler switch options .. until I had .. ghc -XFlexibleInstances -XExistentialQuantification -XEmptyDataDecls --make Main.hs which was also unsuccessful. Philosophical Summary ... All the examples of type classes examples I've seen in tutorials and books look simple, beautiful and elegant. No disrespect intended to the coding suggestions but they seem a little more difficult than I had expected for my toy problem .. So I'm wondering why that is .. - I'm stupidly trying to shoehorn my toy problem into a type class example which is not the best approach. - The problem is *not* a toy problem and is really complicated. - Type classes are more appropriate at the 'system' level than the 'application' level. Applications are better off using algebraic data types. - Tom (me) has expectations that are too high. I do have high expectations of Haskell. I've written several mid sized applications (obviously without using type classes :-) ) and found them easy to write and unbelievably easy to refactor!!! Thoughts appreciated. Thanks again to eveyone! Tom From wiggly at wiggly.org Sun Aug 30 18:09:41 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Sun Aug 30 17:47:48 2009 Subject: [Haskell-beginners] Utter Newbie - simple problems, output - GHC vs GHCi Message-ID: <4A9AF8A5.3050500@wiggly.org> I am trying to get my head around Haskell but seem to keep butting against problems that have nothing to do with FP yet, but are simply to do with not understanding the tools. I've been trying a lot of code from multiple tutorials but I keep finding that the code simply does not work out of the box, and requires some other setup I am unaware of. I am currently on Debian, using GHC 6.8.2 installed using apt, so I assume that the toolchain is installed and working correctly. For example, the most recent tutorial I've been looking at is the "yet another haskell tutorial", here - http://www.cs.utah.edu/~hal/docs/daume02yaht.pdf One of the exercises after talking about functions that act on lists is to determine the number of lowercase letters in a string. Fine, that makes complete sense to me. I figure something along the lines of: length( filter( Char.isLower "LoweR" ) ) should return the value 3 If I attempt this at the interactive GHC prompt I get the following: ------------------------------------------------------------------------------------------ wiggly@mink:~/src/ht$ ghci GHCi, version 6.8.2: http://www.haskell.org/ghc/ :? for help Loading package base ... linking ... done. Prelude> show( length( filter( Char.isLower "LoweR" ) ) ) :1:35: Couldn't match expected type `Char' against inferred type `[Char]' In the first argument of `GHC.Unicode.isLower', namely `"LoweR"' In the first argument of `filter', namely `(GHC.Unicode.isLower "LoweR")' In the first argument of `length', namely `(filter (GHC.Unicode.isLower "LoweR"))' Prelude> ------------------------------------------------------------------------------------------ If I attempt to put the code into a file and compile it I get the following: [Code] ------------------------------------------------------------------------------------------ module Main where import Char main = show( length( filter( Char.isLower "LoweR" ) ) ) ------------------------------------------------------------------------------------------ [Terminal] ------------------------------------------------------------------------------------------ wiggly@mink:~/src/ht$ ghc -o test ex3.hs ex3.hs:3:42: Couldn't match expected type `Char' against inferred type `[Char]' In the first argument of `isLower', namely `"LoweR"' In the first argument of `filter', namely `(isLower "LoweR")' In the first argument of `length', namely `(filter (isLower "LoweR"))' wiggly@mink:~/src/ht$ ------------------------------------------------------------------------------------------ This is one of the smallest examples I can think of posting for some help, and quite frankly, I'm feeling a bit dim because I just cannot understand why this doesn't work...I've tried in vain to mess with the code (I won't attempt to describe it, I'm not au fait enough with Haskell terminology yet, it would sound like gibberish *and* be incorrect) Any help would be awesome, equally, any ready-to-run examples/tutorials that people could recommend would likewise be awesome and beer-worthy[0]. Cheers, n [0] offer only applies to those in the London area or those environs where I find myself randomly From magnus at therning.org Sun Aug 30 18:13:14 2009 From: magnus at therning.org (Magnus Therning) Date: Sun Aug 30 17:52:43 2009 Subject: [Haskell-beginners] Utter Newbie - simple problems, output - GHC vs GHCi In-Reply-To: <4A9AF8A5.3050500@wiggly.org> References: <4A9AF8A5.3050500@wiggly.org> Message-ID: On Sun, Aug 30, 2009 at 11:09 PM, Nigel Rantor wrote: > > I am trying to get my head around Haskell but seem to keep butting > against problems that have nothing to do with FP yet, but are simply to > do with not understanding the tools. > > I've been trying a lot of code from multiple tutorials but I keep > finding that the code simply does not work out of the box, and requires > some other setup I am unaware of. > > I am currently on Debian, using GHC 6.8.2 installed using apt, so I > assume that the toolchain is installed and working correctly. > > For example, the most recent tutorial I've been looking at is the "yet > another haskell tutorial", here - > http://www.cs.utah.edu/~hal/docs/daume02yaht.pdf > > One of the exercises after talking about functions that act on lists is > to determine the number of lowercase letters in a string. > > Fine, that makes complete sense to me. I figure something along the > lines of: > > length( filter( Char.isLower "LoweR" ) ) try this instead length (filter Char.isLower "LoweR") `filter` takes two arguments. /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe From wiggly at wiggly.org Sun Aug 30 18:32:14 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Sun Aug 30 18:10:16 2009 Subject: [Haskell-beginners] Utter Newbie - simple problems, output - GHC vs GHCi In-Reply-To: References: <4A9AF8A5.3050500@wiggly.org> Message-ID: <4A9AFDEE.30104@wiggly.org> Magnus Therning wrote: > On Sun, Aug 30, 2009 at 11:09 PM, Nigel Rantor wrote: >> >> length( filter( Char.isLower "LoweR" ) ) > > try this instead > > length (filter Char.isLower "LoweR") > > `filter` takes two arguments. Thank you, I have been flip-flopping between having no parentheses and lots...I think I get it now. I owe you a beer. This will, however, probably not be my last post... n From daniel.is.fischer at web.de Sun Aug 30 18:48:03 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Aug 30 18:30:33 2009 Subject: [Haskell-beginners] Utter Newbie - simple problems, output - GHC vs GHCi In-Reply-To: <4A9AF8A5.3050500@wiggly.org> References: <4A9AF8A5.3050500@wiggly.org> Message-ID: <200908310048.03973.daniel.is.fischer@web.de> Am Montag 31 August 2009 00:09:41 schrieb Nigel Rantor: > I am trying to get my head around Haskell but seem to keep butting > against problems that have nothing to do with FP yet, but are simply to > do with not understanding the tools. > > I've been trying a lot of code from multiple tutorials but I keep > finding that the code simply does not work out of the box, and requires > some other setup I am unaware of. It's often old code which may have become obsolete by changes in the compiler and libraries. > > I am currently on Debian, using GHC 6.8.2 installed using apt, so I > assume that the toolchain is installed and working correctly. > > For example, the most recent tutorial I've been looking at is the "yet > another haskell tutorial", here - > http://www.cs.utah.edu/~hal/docs/daume02yaht.pdf > > One of the exercises after talking about functions that act on lists is > to determine the number of lowercase letters in a string. > > Fine, that makes complete sense to me. I figure something along the > lines of: > > length( filter( Char.isLower "LoweR" ) ) > > should return the value 3 > > If I attempt this at the interactive GHC prompt I get the following: > > --------------------------------------------------------------------------- >--------------- wiggly@mink:~/src/ht$ ghci > GHCi, version 6.8.2: http://www.haskell.org/ghc/ :? for help > Loading package base ... linking ... done. > Prelude> show( length( filter( Char.isLower "LoweR" ) ) ) > > :1:35: > Couldn't match expected type `Char' against inferred type `[Char]' > In the first argument of `GHC.Unicode.isLower', namely `"LoweR"' > In the first argument of `filter', namely > `(GHC.Unicode.isLower "LoweR")' > In the first argument of `length', namely > `(filter (GHC.Unicode.isLower "LoweR"))' > Prelude> > --------------------------------------------------------------------------- >--------------- Wrong parentheses. 'filter' takes two arguments, the predicate by which to filter and the list to be filtered. With your parentheses, you pass it only one argument, namely (Data.Char.isLower "LoweR") However, isLower takes a Char as argument, while here it is given a String, this is the type error reported by ghci. What you wanted is length (filter Data.Char.isLower "LoweR") Function application doesn't need parentheses in Haskell, so a multi-argument function is called function arg1 arg2 arg3 and not function(arg1, arg2, arg3) as in most imperative languages. It takes a bit getting used to. You don't need the 'show', by the way, ghci prints the result of the evaluation of an expression typed at the prompt anyway. And, while the modules Char, List, IO etc. still exist, the compiler now uses hierarchical modules and they now live in Data.Char, Data.List, System.IO etc. Better to get the habit of using hierarchical modules from the start. > > If I attempt to put the code into a file and compile it I get the > following: > > [Code] > --------------------------------------------------------------------------- >--------------- module Main where > import Char > main = show( length( filter( Char.isLower "LoweR" ) ) ) > --------------------------------------------------------------------------- >--------------- Same parenthisation issue as above, on top of that, main must have type IO (), but show whatEver is a String. It would be import Data.Char main = print (length (filter isLower "LoweR")) > > [Terminal] > --------------------------------------------------------------------------- >--------------- wiggly@mink:~/src/ht$ ghc -o test ex3.hs > > ex3.hs:3:42: > Couldn't match expected type `Char' against inferred type `[Char]' > In the first argument of `isLower', namely `"LoweR"' > In the first argument of `filter', namely `(isLower "LoweR")' > In the first argument of `length', namely > `(filter (isLower "LoweR"))' > wiggly@mink:~/src/ht$ > --------------------------------------------------------------------------- >--------------- > > This is one of the smallest examples I can think of posting for some > help, and quite frankly, I'm feeling a bit dim because I just cannot > understand why this doesn't work...I've tried in vain to mess with the > code (I won't attempt to describe it, I'm not au fait enough with > Haskell terminology yet, it would sound like gibberish *and* be incorrect) > > Any help would be awesome, equally, any ready-to-run examples/tutorials > that people could recommend would likewise be awesome and beer-worthy[0]. > Try the wikibook: http://en.wikibooks.org/wiki/Haskell it contains (almost?) all of YAHT and much more. It's still being written, but it's already very usable. Also, you might take a look at http://book.realworldhaskell.org/ . > Cheers, > > n > > [0] offer only applies to those in the London area or those environs > where I find myself randomly Dang. Could've done with a beer :( From chaddai.fouche at gmail.com Sun Aug 30 19:53:13 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Sun Aug 30 19:32:41 2009 Subject: [Haskell-beginners] Re: Type Class Woes .. In-Reply-To: <200908301214.57658.poliquin@softcomp.com> References: <200908292357.25041.poliquin@softcomp.com> <200908301214.57658.poliquin@softcomp.com> Message-ID: On Sun, Aug 30, 2009 at 9:14 PM, Tom Poliquin wrote: > Chadda? Fouch? ?wrote: >> >> data Volumic = Volume a => V a >> > I've never used existentials .. but this seems like a powerful idea. > Unfortunately I couldn't get this to compile .. > It was unhappy about 'data Volumic' so I changed it to > 'data Volumic a' .. it was still unhappy and took me down > the road of compiler switch options .. until I had .. > ghc -XFlexibleInstances -XExistentialQuantification -XEmptyDataDecls --make > Main.hs > which was also unsuccessful. > Oops... Sorry, I just put together a simple example and didn't test it, I forgot the forall : > data Volumic = forall a . (Volume a) => V a You must explicitly quantify the type variable to do existentials (and use the proper extensions, which you did). > > Philosophical Summary ... > All the examples of type classes examples I've seen in tutorials and > books look simple, beautiful and elegant. No disrespect intended > to the coding suggestions but they seem a little more difficult than > I had expected for my toy problem .. > > So I'm wondering why that is .. > > - I'm stupidly trying to shoehorn my toy problem > ?into a type class example which is not the best approach. > Well it is a _toy_ problem where you're specifically trying to shoehorn something into the form you wished to discover, this kind of thing sometimes seems harder to do than resolve real problems where the context and the practical objectives give you clues all along. > > - The problem is *not* a toy problem and is really > ? complicated. > In fact you're trying to address the so called "Expression problem" here, it isn't a simple feat and while Haskell bring some answer they are not so straightforwardly supported and easy to use as could be wished (though I'm unaware of any practical language that do better currently IMHO). > > - Type classes are more appropriate at the 'system' level > ? than the 'application' level. Applications are better off > ? using algebraic data types. > Depend on what you call "Application" I guess, given that creating a big application in Haskell seems to consist of creating a framework/dsl to express the main program in two lines, it may be that you'll still need type class for that, but it's true that type classes are better placed in libraries than in the application code, where algebraic/record type and pattern matching are often a more appropriate solution. > > - Tom (me) has expectations that are too high. > ? I do have high expectations of Haskell. I've written > ? several mid sized applications (obviously without > ? using type classes :-) ) and found them easy to write > ? and unbelievably easy to refactor!!! > It may be that too, while Haskell is impressive, it isn't perfect just yet. ;) -- Jeda? From Christian.Maeder at dfki.de Mon Aug 31 07:31:51 2009 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Mon Aug 31 07:11:20 2009 Subject: [Haskell-beginners] Re: pretty-printing data In-Reply-To: <4A99398E.4040403@alumni.caltech.edu> References: <4A99398E.4040403@alumni.caltech.edu> Message-ID: <4A9BB4A7.1040203@dfki.de> Michael Mossey wrote: > For debugging purposes I'm interested in pretty-printing data; to start > with, lists of algebraic data types. Basically I'd like 'show' with the > ability to put each entry of a list on a separate line, and indented. > Note that the algebraic data might have an inner list as one of its > elements, so this is a non-obvious formatting problem. > > I believe I can make instances of Show, can I not? Is there something > called showList which I can use to code my own method of showing lists > of a particular type? My understanding is that I can't make [a] an > instance of Show; hence they provided showList. For your own data type say "Foo" you can provide your own showList definition, that will be used whenever you show something of type "[Foo]". You cannot rewrite the (generic) "instance Show a => Show [a]". instance Show Foo where show _ = "Foo" showList l s = unlines (map ((" " ++) . show) l) ++ s With overlapping instances you could rewrite "instance Show [Foo]", but you should prefer the above or start with a separate class "Pretty" and use show as default implementation: class Show a = Pretty a pretty :: a -> String pretty = show With some ghc extension (undecidable instances?) you can get instances for all types: instance Show a = Pretty a Provide a list instance: instance Pretty a => Pretty [a] where pretty l = ... and you can write (overlapping) instances for other types. For your own data types use "deriving Show" and provide a Pretty instance (if you don't like the Show result). HTH Christian From wiggly at wiggly.org Mon Aug 31 07:42:01 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Mon Aug 31 07:21:33 2009 Subject: [Haskell-beginners] Utter Newbie - simple problems, output - GHC vs GHCi In-Reply-To: <200908310048.03973.daniel.is.fischer@web.de> References: <4A9AF8A5.3050500@wiggly.org> <200908310048.03973.daniel.is.fischer@web.de> Message-ID: <4A9BB709.7070105@wiggly.org> Daniel Fischer wrote: > Am Montag 31 August 2009 00:09:41 schrieb Nigel Rantor: >> I am trying to get my head around Haskell but seem to keep butting >> against problems that have nothing to do with FP yet, but are simply to >> do with not understanding the tools. [snip] >> Any help would be awesome, equally, any ready-to-run examples/tutorials >> that people could recommend would likewise be awesome and beer-worthy[0]. >> > > Try the wikibook: > > http://en.wikibooks.org/wiki/Haskell > > it contains (almost?) all of YAHT and much more. It's still being written, but it's > already very usable. > > Also, you might take a look at http://book.realworldhaskell.org/ . Thanks for this, the extra info around my problems is a big help, and makes me feel slightly less frustrated. >> Cheers, >> >> n >> >> [0] offer only applies to those in the London area or those environs >> where I find myself randomly > > Dang. Could've done with a beer :( You never know, I may be in a town near you soon...and, also, I'm liable to be asking for more help. If anyone gets 12 points I'll ship a case... n From patrick.leboutillier at gmail.com Mon Aug 31 13:33:48 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Mon Aug 31 13:13:15 2009 Subject: [Haskell-beginners] Parsec newbie question Message-ID: Hi all, I'd like to use parsec to parse IP addresses. So far I've written a (tiny) parser for bytes: byte :: GenParser Char st Word8 byte = do n <- many1 digit return (read n) The function works fine, but it accepts numbers greater than 255. How do I encapsulate this condition in the parser so that it fails (with en appropriate error message) in this case? Thanks a lot, Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090831/0508dd4d/attachment.html From daniel.is.fischer at web.de Mon Aug 31 15:26:28 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Aug 31 15:07:02 2009 Subject: [Haskell-beginners] Parsec newbie question In-Reply-To: References: Message-ID: <200908312126.29044.daniel.is.fischer@web.de> Am Montag 31 August 2009 19:33:48 schrieb Patrick LeBoutillier: > Hi all, > > I'd like to use parsec to parse IP addresses. So far I've written a (tiny) > parser for bytes: > > byte :: GenParser Char st Word8 > byte = do > n <- many1 digit > return (read n) > > The function works fine, but it accepts numbers greater than 255. > How do I encapsulate this condition in the parser so that it fails (with en > appropriate error message) in this case? > byte :: GenParser Char st Word8 byte = do ds <- many1 digit let n :: Integer -- or Int, if you're not too paranoid n = read ds if n < 256 then return (fromIntegral n) else fail $ "Number " ++ ds ++ " too large for a byte." > > Thanks a lot, > > Patrick From poliquin at softcomp.com Mon Aug 31 15:02:36 2009 From: poliquin at softcomp.com (Tom Poliquin) Date: Mon Aug 31 16:15:20 2009 Subject: [Haskell-beginners] Re: Type Class Woes .. In-Reply-To: References: <200908292357.25041.poliquin@softcomp.com> <200908301214.57658.poliquin@softcomp.com> Message-ID: <200908311202.37033.poliquin@softcomp.com> Tom Poliquin wrote: > I chose the (contrived toy) problem of computing the volume > of various fruits. Chadda? Fouch? wrote: > ....you can still have a list of different fruits > type, using existential types, > [ Code supplied] Chaddai .. I added the 'forall' and it works great! Thanks very much for the code and the 'philosophical' comments ! Full code of your solution below. Tom {-# OPTIONS_GHC -XFlexibleInstances #-} {-# OPTIONS_GHC -XExistentialQuantification #-} {-# OPTIONS_GHC -XEmptyDataDecls #-} module Main where data Fruit a = F {radius, length :: Double } data Orange; data Banana -- empty data decls class Volume a where vol :: a -> Double instance Volume (Fruit Orange) where vol (F r _) = (4/3) * pi * r * r * r instance Volume (Fruit Banana) where -- flexible instances vol (F r l) = pi * (r * r) * l data Volumic = forall a . (Volume a) => V a -- existential quantification fruit_list :: [Volumic] fruit_list = [ V (F 3 undefined :: Fruit Orange) ,V (F 1 6 :: Fruit Banana) ] main = do fruit <- return $ fruit_list mapM (\(V f) -> putStrLn ("Volume -> " ++ " = " ++ show (vol f))) fruit ------------------------------------------------------ > On Sun, Aug 30, 2009 at 9:14 PM, Tom Poliquin wrote: > > Chadda? Fouch? ?wrote: > >> data Volumic = Volume a => V a > > > > I've never used existentials .. but this seems like a powerful idea. > > Unfortunately I couldn't get this to compile .. > > It was unhappy about 'data Volumic' so I changed it to > > 'data Volumic a' .. it was still unhappy and took me down > > the road of compiler switch options .. until I had .. > > ghc -XFlexibleInstances -XExistentialQuantification -XEmptyDataDecls > > --make Main.hs > > which was also unsuccessful. > > Oops... Sorry, I just put together a simple example and didn't test > > it, I forgot the forall : > > data Volumic = forall a . (Volume a) => V a > > You must explicitly quantify the type variable to do existentials (and > use the proper extensions, which you did). > > > Philosophical Summary ... > > All the examples of type classes examples I've seen in tutorials and > > books look simple, beautiful and elegant. No disrespect intended > > to the coding suggestions but they seem a little more difficult than > > I had expected for my toy problem .. > > > > So I'm wondering why that is .. > > > > - I'm stupidly trying to shoehorn my toy problem > > ?into a type class example which is not the best approach. > > Well it is a _toy_ problem where you're specifically trying to > shoehorn something into the form you wished to discover, this kind of > thing sometimes seems harder to do than resolve real problems where > the context and the practical objectives give you clues all along. > > > - The problem is *not* a toy problem and is really > > ? complicated. > > In fact you're trying to address the so called "Expression problem" > here, it isn't a simple feat and while Haskell bring some answer they > are not so straightforwardly supported and easy to use as could be > wished (though I'm unaware of any practical language that do better > currently IMHO). > > > - Type classes are more appropriate at the 'system' level > > ? than the 'application' level. Applications are better off > > ? using algebraic data types. > > Depend on what you call "Application" I guess, given that creating a > big application in Haskell seems to consist of creating a > framework/dsl to express the main program in two lines, it may be that > you'll still need type class for that, but it's true that type classes > are better placed in libraries than in the application code, where > algebraic/record type and pattern matching are often a more > appropriate solution. > > > - Tom (me) has expectations that are too high. > > ? I do have high expectations of Haskell. I've written > > ? several mid sized applications (obviously without > > ? using type classes :-) ) and found them easy to write > > ? and unbelievably easy to refactor!!! > > It may be that too, while Haskell is impressive, it isn't perfect just yet. > ;) From jack at realmode.com Mon Aug 31 22:08:01 2009 From: jack at realmode.com (I. J. Kennedy) Date: Mon Aug 31 21:47:27 2009 Subject: [Haskell-beginners] haskell code to html Message-ID: <1008bfc90908311908n12e1ef5ai83ad93caa5eea022@mail.gmail.com> Is there a decent utility out there for syntax coloring haskell code?(haskell to html) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090831/9e81a648/attachment.html From daniel.is.fischer at web.de Mon Aug 31 22:18:44 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Aug 31 21:59:13 2009 Subject: [Haskell-beginners] haskell code to html In-Reply-To: <1008bfc90908311908n12e1ef5ai83ad93caa5eea022@mail.gmail.com> References: <1008bfc90908311908n12e1ef5ai83ad93caa5eea022@mail.gmail.com> Message-ID: <200909010418.45026.daniel.is.fischer@web.de> Am Dienstag 01 September 2009 04:08:01 schrieb I. J. Kennedy: > Is there a decent utility out there for syntax coloring haskell > code?(haskell to html) HsColour: http://hackage.haskell.org/package/hscolour cabal update && cabal install hscolour if you have a working cabal binary (if you haven't, you should get yourself one) From ezyang at MIT.EDU Mon Aug 31 23:02:10 2009 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Mon Aug 31 22:54:24 2009 Subject: [Haskell-beginners] Figuring out errors Message-ID: <1251773361-sup-1494@javelin> Hello all, I've been looking at [1] and trying to make tops and bottoms (pardon the pun) of error handling in Haskell. I am still uncertain of what to do. I recognize that there are different areas of code that may have different requirements for errors: * Pure code that is simple enough can probably get away with returning Maybe a * Pure code that has multiple failure modes (the canonical example is parsing) should return a Either e a. The type of e is a little difficult: many standard libraries seem to use String, but coming from Python this seems analogous to the long deprecated "string exceptions", which are quick and easy but not long-term maintainable due to lack of an easy way to match for them. This leads naturally into Either MyError, which is supported using throwError and catchError. * However, [1] specifically warns against using this technique in the IO monad, and I need a way to short circuit execution when a crucial pure operation fails (in Python, this would have just been an uncaught exception). This suggests using ErrorT on IO, however, [1] also claims that this is generally not a good idea, and suggests to use throwDyn (which actually looks like it's been renamed to throw) * Unfortunately, when I've tried to use this technique, I've run up against the fact that throw is implemented using bottom, so if I do a throw in a pure function, the exception might not actually surface up until I'm, say, attempting to print its return value to IO. Denizens on #haskell have instructed me to treat bottom as the bane of existence and opt for stacking ErrorT on IO (it would be nice to know if this was a good idea or bad idea) At which point, I am most thoroughly confused. Pointers, please! Cheers, Edward [1] http://www.randomhacks.net/articles/2007/03/10/haskell-8-ways-to-report-errors