From max.cs.2009 at googlemail.com Thu Jan 1 02:32:13 2009 From: max.cs.2009 at googlemail.com (Max.cs) Date: Thu Jan 1 02:24:15 2009 Subject: [Haskell-beginners] definition of data Message-ID: <72BD3446DDCA468BB5237C62EA7B780B@hxzhao> hi all, I want to define a data type Tree a that can either be a or Branch (Tree a) (Tree a)? I tried data Tree a = a | Branch (Tree a) (Tree a) deriving Show but it seems not accpetable in haskell ? any way I could achieve this ? Thanks max -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090101/11fad6a9/attachment.htm From allbery at ece.cmu.edu Thu Jan 1 02:35:55 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Thu Jan 1 02:28:10 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] definition of data In-Reply-To: <72BD3446DDCA468BB5237C62EA7B780B@hxzhao> References: <72BD3446DDCA468BB5237C62EA7B780B@hxzhao> Message-ID: On 2009 Jan 1, at 2:32, Max.cs wrote: > data Tree a = a | Branch (Tree a) (Tree a) deriving Show > > but it seems not accpetable in haskell ? You need a constructor in both legs of the type: > data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show -- 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 -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090101/8ddd680d/attachment-0001.htm From max.cs.2009 at googlemail.com Thu Jan 1 03:36:24 2009 From: max.cs.2009 at googlemail.com (Max.cs) Date: Thu Jan 1 03:28:29 2009 Subject: [Haskell-beginners] pattern matching on date type In-Reply-To: References: <72BD3446DDCA468BB5237C62EA7B780B@hxzhao> Message-ID: <3D524BA96876446CA9B57BDB8E09605E@hxzhao> thanks! suppose we have > data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show and how I could define a function foo :: a -> Tree a that foo a = Leaf a where a is not a type of Tree foo b = b where b is one of the type of Tree (Leaf or Branch) ? The following code seems not working...... foo (Leaf a) = a foo a = Leaf a saying 'Couldn't match expected type `a' against inferred type `Btree a'' any idea? Thanks, Max From: Brandon S. Allbery KF8NH Sent: Thursday, January 01, 2009 7:35 AM To: Max.cs Cc: Brandon S. Allbery KF8NH ; beginners@haskell.org ; haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] definition of data On 2009 Jan 1, at 2:32, Max.cs wrote: data Tree a = a | Branch (Tree a) (Tree a) deriving Show but it seems not accpetable in haskell ? You need a constructor in both legs of the type: > data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show -- 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 -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090101/f7240635/attachment.htm From alexander.dunlap at gmail.com Thu Jan 1 04:44:33 2009 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Thu Jan 1 04:36:24 2009 Subject: [Haskell-beginners] pattern matching on date type In-Reply-To: <3D524BA96876446CA9B57BDB8E09605E@hxzhao> References: <72BD3446DDCA468BB5237C62EA7B780B@hxzhao> <3D524BA96876446CA9B57BDB8E09605E@hxzhao> Message-ID: <57526e770901010144o45750683o37dad7a207f5d8db@mail.gmail.com> On Thu, Jan 1, 2009 at 12:36 AM, Max.cs wrote: > thanks! > > suppose we have > >> data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show > > and how I could define a function foo :: a -> Tree a that > > foo a = Leaf a where a is not a type of Tree > foo b = b where b is one of the type of Tree (Leaf or > Branch) ? > > The following code seems not working...... > > foo (Leaf a) = a > foo a = Leaf a > > saying 'Couldn't match expected type `a' against inferred type `Btree a'' > > any idea? > > Thanks, > Max You can't define such a function. foo :: a -> Tree a, but the definition foo b = b has the type a -> a, which is why the compiler says it can't match type "a" against "Tree a". In general, Haskell functions can't "look" at the type of their arguments: they are either monomorphic or are polymorphic, in which case you can only use polymorphic functions that match the polymorphic type. For the problem you are trying to solve, you probably need to encode this logic higher up in the overall function (e.g. have one function to deal with "a"s and another to deal with "Tree a"s). Hope that helps, Alex From tom.davie at gmail.com Thu Jan 1 04:58:26 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Thu Jan 1 04:50:35 2009 Subject: [Haskell-beginners] Re: about the concatenation on a tree In-Reply-To: <1CBBCE84485E411E888C8551DA3423B1@hxzhao> References: <902ff3e80812310659j2ee7949du7a54bcf5de7c0139@mail.gmail.com> <902ff3e80812310702y7b2e4c28g356baffbb8df678@mail.gmail.com> <2CD4FDAC-247C-4ED5-854E-9FC3CCEF4996@gmail.com> <9FADE9BDA1DF47F59D37C761C47B2FF2@hxzhao> <0E6B9C34-EDDC-415D-B329-526EEBDB1895@gmail.com> <1CBBCE84485E411E888C8551DA3423B1@hxzhao> Message-ID: > > hi Bob, > > I believe the type of foldTree is implementable, but what confuses > me is > > the output example: > >> concatT (Leaf t) = t >> concatT (Branch (Leaf t1) (Leaf t2)) = Branch t1 t2 > > they seem to be inconsistent with the type of concatT which return a > Tree only, but in the Leaf case, a atomic value is returned? > > anything important I am missing? You need to remember what type is stored in that Leaf ? remember that this is a Tree (Tree a) ? i.e. the variable t in the line above has the type Tree a. Bob From tom.davie at gmail.com Thu Jan 1 05:04:23 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Thu Jan 1 04:56:17 2009 Subject: [Haskell-beginners] pattern matching on date type In-Reply-To: <3D524BA96876446CA9B57BDB8E09605E@hxzhao> References: <72BD3446DDCA468BB5237C62EA7B780B@hxzhao> <3D524BA96876446CA9B57BDB8E09605E@hxzhao> Message-ID: <0DF9BA91-8F11-42CA-964C-131A626571EA@gmail.com> On 1 Jan 2009, at 09:36, Max.cs wrote: > thanks! > > suppose we have > > > data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show > > and how I could define a function foo :: a -> Tree a that > > foo a = Leaf a where a is not a type of Tree > foo b = b where b is one of the type of Tree (Leaf > or Branch) ? > > The following code seems not working...... > > foo (Leaf a) = a > foo a = Leaf a > > saying 'Couldn't match expected type `a' against inferred type > `Btree a' Hi again Max, I'm assuming this is continuing from the concatT example, and that you're struggling with first function you must pass to foldTree. Remember the type of the function ? it's not a -> Tree a, but Tree a - > Tree a, because your leaves in the parent tree all contain trees to glue on at that point. So, the function you want, is the function which looks at the parameter it's given, goes "oh, that's interesting", does nothing to it, and hands it back to replace the Leaf. I recommend searching hoogle for functions of type a -> a, the function you're looking for is built in. Bob From steve at steveklabnik.com Thu Jan 1 15:28:00 2009 From: steve at steveklabnik.com (Steve Klabnik) Date: Thu Jan 1 15:19:50 2009 Subject: [Haskell-beginners] until and Time In-Reply-To: <200901010454.44854.daniel.is.fischer@web.de> References: <200901010454.44854.daniel.is.fischer@web.de> Message-ID: Ahh. Thank you. That makes much more sense now. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090101/29d59a85/attachment.htm From iamkeke at gmail.com Sat Jan 3 03:17:17 2009 From: iamkeke at gmail.com (keke) Date: Sat Jan 3 03:09:01 2009 Subject: [Haskell-beginners] Question about typeclasses Message-ID: <7386ba0901030017i2b924187y260f5e558441d391@mail.gmail.com> Hi, I am bit struggling with understanding the typeclasses usage in Text.Regex.Posix (=~) while reading Real world haskell. The type of (=~) is (RegexMaker Regex CompOption ExecOption source, RegexContext Regex source1 target) => source1 -> source -> target I am from Java world. My question is that can I understand source1 in the way which is a value has type of RegexMaker, Regex, CompOption and ExecOption? And the definiton of instance RegexMaker Regex CompOption ExecOption Stringmakes it possible for us to pass a String as the parameter of =~? Where can I find some good metarials about GHC's type classes? I googled a lot but can not find something mentioned above usage. -- Cheers, Keke ----------------- We paranoid love life -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090103/76e53996/attachment.htm From jason.dusek at gmail.com Sat Jan 3 04:26:23 2009 From: jason.dusek at gmail.com (Jason Dusek) Date: Sat Jan 3 04:18:10 2009 Subject: [Haskell-beginners] Question about typeclasses In-Reply-To: <7386ba0901030017i2b924187y260f5e558441d391@mail.gmail.com> References: <7386ba0901030017i2b924187y260f5e558441d391@mail.gmail.com> Message-ID: <42784f260901030126j79696b16yd13de84e3f5cf276@mail.gmail.com> 2009-01-03T08:17:00Z > I am bit struggling with understanding the typeclasses usage > in Text.Regex.Posix (=~) [...] My question is that can I > understand source1 in the way which is a value has type of > RegexMaker, Regex, CompOption and ExecOption? Prettifying the signature a little bit: :: ( RegexMaker Regex CompOption ExecOption source , RegexContext Regex source1 target ) => source1 -> source -> target You can read this as: The type `source1 -> source -> target` such that both "class constraints" are satisfied. What is a class contraint and what does it mean for it to be satisfied? A class contraint is something like an interface, or a generic, or a template. One defines "instances" of classes in Haskell, as in Jave one "implements" an interface. So what do these particular classes mean? The first one reads: We have a way to make a regular expression using the usual option specifications (multiline, case insensitive, stuff like that -- those are `CompOption` and `ExecOption`). The second one reads There is a way to match the first value against the second to get the desired target value (list of matches, Boolean, &c.). The "way to..." in each case is a function in the class definition -- `makeRegex` in the former case, and `match` in the latter. -- Jason Dusek From colin at colina.demon.co.uk Sat Jan 3 14:56:07 2009 From: colin at colina.demon.co.uk (Colin Paul Adams) Date: Sat Jan 3 14:47:53 2009 Subject: [Haskell-beginners] Collapsing multiple case branches? Message-ID: I have the following function: northern_range:: Piece_type -> Int northern_range piece = case piece of Lance -> 11 Reverse_chariot -> 11 Vertical_mover -> 11 White_horse -> 11 Rook -> 11 Promoted_rook -> 11 Promoted_gold_general -> 11 Promoted_silver_general -> 11 Free_king -> 11 Promoted_phoenix -> 11 Flying_stag -> 11 Flying_ox -> 11 Whale -> 11 Dragon_king -> 11 Soaring_eagle -> 11 Bishop -> 0 Kylin -> 0 Lion -> 0 Promoted_kylin -> 0 Blind_tiger -> 0 Promoted_ferocious_leopard -> 0 Free_boar -> 0 Horned_falcon -> 0 _ -> 1 I'd prefer to write this as just three lines (one for each of the three resulting values), something like this: northern_range:: Piece_type -> Int northern_range piece = case piece of Lance, Reverse_chariot, Vertical_mover, etc. -> 11 Bishop, Kylin, etc. -> 0 _ -> 1 Is there some syntax to do this sort of thing? -- Colin Adams Preston Lancashire From tom.davie at gmail.com Sat Jan 3 15:04:49 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Sat Jan 3 14:56:37 2009 Subject: [Haskell-beginners] Collapsing multiple case branches? In-Reply-To: References: Message-ID: Hi Colin, northernRange :: PieceType > Int -- note the camel case, that's traditional in Haskell circles northernRange p | p `elem` [Lance, ReverseChariot, VerticalMover ....] = 11 | p `elem` [Bishop, Kylin,....] = 0 | otherwise = 1 These are called "pattern guards" ? you can put any boolean expression in them. Of note, if you provide an Enum instance for PieceType you may really be able to do this: northernRange p | p `elem` [Lance..SoaringEagle] = 11 | p `elem` [Bishop..HornedFalcon] = 0 | otherwise = 1 Finally, my guess is that you probably want a much more general type for PieceType that doesn't need extended every time you add a Piece to your game (and similarly doesn't need every function in your program extended at the same time). Perhaps something like this: data Piece = Piece { name :: String, northernRange :: Int } With elements like: lance = Piece "Lance" 11 or like: reverseChariot = Piece {name = "Reverse chariot", northernRange = 11} Bob On 3 Jan 2009, at 20:56, Colin Paul Adams wrote: > I have the following function: > > northern_range:: Piece_type -> Int > northern_range piece = > case piece of > Lance -> 11 > Reverse_chariot -> 11 > Vertical_mover -> 11 > White_horse -> 11 > Rook -> 11 > Promoted_rook -> 11 > Promoted_gold_general -> 11 > Promoted_silver_general -> 11 > Free_king -> 11 > Promoted_phoenix -> 11 > Flying_stag -> 11 > Flying_ox -> 11 > Whale -> 11 > Dragon_king -> 11 > Soaring_eagle -> 11 > Bishop -> 0 > Kylin -> 0 > Lion -> 0 > Promoted_kylin -> 0 > Blind_tiger -> 0 > Promoted_ferocious_leopard -> 0 > Free_boar -> 0 > Horned_falcon -> 0 > _ -> 1 > > I'd prefer to write this as just three lines (one for each of the > three resulting values), something like this: > > northern_range:: Piece_type -> Int > northern_range piece = > case piece of > Lance, Reverse_chariot, Vertical_mover, etc. -> 11 > Bishop, Kylin, etc. -> 0 > _ -> 1 > > Is there some syntax to do this sort of thing? > -- > Colin Adams > Preston Lancashire > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From colin at colina.demon.co.uk Sat Jan 3 15:11:44 2009 From: colin at colina.demon.co.uk (Colin Paul Adams) Date: Sat Jan 3 15:03:28 2009 Subject: [Haskell-beginners] Collapsing multiple case branches? In-Reply-To: (Thomas Davie's message of "Sat\, 3 Jan 2009 21\:04\:49 +0100") References: Message-ID: >>>>> "Thomas" == Thomas Davie writes: Thomas> Hi Colin, northernRange :: PieceType > Int -- note the Thomas> camel case, that's traditional in Haskell circles I know, but I find it vile. Thomas> northernRange p | p `elem` [Lance, ReverseChariot, Thomas> VerticalMover ....] = 11 | p `elem` [Bishop, Kylin,....] = Thomas> 0 | otherwise = 1 Thomas> These are called "pattern guards" ? you can put any Thomas> boolean expression in them. Ah, thanks, that will do nicely. Thomas> Of note, if you provide an Enum instance for PieceType you Thomas> may really be able to do this: Thomas> northernRange p | p `elem` [Lance..SoaringEagle] = 11 | p Thomas> `elem` [Bishop..HornedFalcon] = 0 | otherwise = 1 I thought of that, but there are additional functions to do where the required ordering would be different. Thomas> Finally, my guess is that you probably want a much more Thomas> general type for PieceType that doesn't need extended Thomas> every time you add a Piece to your game (and similarly Thomas> doesn't need every function in your program extended at Thomas> the same time). Perhaps something like this: Thomas> data Piece = Piece { name :: String, northernRange :: Thomas> Int } A reasonable guess, but as the pieces types are fixed (it's an ancient game) I preferred to write it this way. BTW is this (as it looks to me) a classic space-time trade-off? -- Colin Adams Preston Lancashire From alexander.dunlap at gmail.com Sat Jan 3 15:33:36 2009 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Sat Jan 3 15:25:20 2009 Subject: [Haskell-beginners] Collapsing multiple case branches? In-Reply-To: References: Message-ID: <57526e770901031233w602e4458x640a8be92e41b644@mail.gmail.com> On Sat, Jan 3, 2009 at 12:04 PM, Thomas Davie wrote: > Hi Colin, ...snip... > These are called "pattern guards" ? you can put any boolean expression in > them. ...snip... Technically, those are just called "guards." "Pattern guards" are when you also bind a pattern; it's a GHC extension. They look like this, for example: foo x | Just y <- bar x = y + 1 -- this is the pattern guard. If bar x can be matched with Just y, then y is bound and that guard path is taken. Otherwise, evaluation falls through to the next guard option. | otherwise = 0 Alex From Christian.Maeder at dfki.de Sat Jan 3 15:09:23 2009 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Sat Jan 3 21:24:49 2009 Subject: [Haskell-beginners] Re: Collapsing multiple case branches? In-Reply-To: References: Message-ID: <495FC5F3.20406@dfki.de> Colin Paul Adams wrote: > I have the following function: > northern_range:: Piece_type -> Int > northern_range piece | elem piece [Lance, Reverse_chariot, Vertical_mover, etc.] = 11 | elem piece [Bishop, Kylin, etc.] = 0 | otherwise = 1 if you have an Eq instance for Piece_type. Cheers Christian From tj.takei at gmail.com Sun Jan 4 00:02:20 2009 From: tj.takei at gmail.com (TJ Takei) Date: Sat Jan 3 23:54:03 2009 Subject: [Haskell-beginners] GHC installation on RHEL 4 by non-root user Message-ID: Hi GHC experts, As a non-root user of Redhat (amd64) RHEL 4.0 server, I can not use rpm. I like to install any relatively recent version of ghc to my local installation area just for learning. I downloaded first 64-bit binary archive that seems incompatible: For example, utils/pwd/pwd does not run. So I ended up downloading a src archive... % wget http://haskell.org/ghc/dist/6.10.1/ghc-6.10.1-src.tar.bz2 Then unpack and boot: % tar jxvf ghc-6.10.1-src.tar.bz2 % cd ghc-6.10.1 % sh boot So far so good, but the next step "configure" fails... no matter what args I give: % ./configure --prefix= configure: error: GHC is required unless bootstrapping from .hc files. After I edited mk/build.mk to uncomment BuildFlavour=quick, Gnu make fails : % make mk/boilerplate.mk:56: mk/config.mk: No such file or directory Understandably the unknown problem may have started in the configure stage. I'm stuck. Also I tried ghc-6.8.3-x86-64-unknown-linux.tar.bz2 that yields similar errors. Yet another desperate trial of darcs seems no help: downloaded... wget http://darcs.haskel.org/ghc-STABLE-2008-11-08-ghc-corelibs-testsuite.tar.bz2 tar jxvf ... darcs-all pull -a edited mk/build.mk sh boot ./configure then gmake fails. I would appreciate any help. Regards, TJ From alexander.dunlap at gmail.com Sun Jan 4 00:37:14 2009 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Sun Jan 4 00:28:58 2009 Subject: [Haskell-beginners] GHC installation on RHEL 4 by non-root user In-Reply-To: References: Message-ID: <57526e770901032137l37c2b735l32fed327e6e2ce68@mail.gmail.com> On Sat, Jan 3, 2009 at 9:02 PM, TJ Takei wrote: > Hi GHC experts, > > As a non-root user of Redhat (amd64) RHEL 4.0 server, I can not use > rpm. I like to install any relatively recent version of ghc to my > local installation area just for learning. > I downloaded first 64-bit binary archive that seems incompatible: > For example, utils/pwd/pwd does not run. > So I ended up downloading a src archive... > % wget http://haskell.org/ghc/dist/6.10.1/ghc-6.10.1-src.tar.bz2 > Then unpack and boot: > % tar jxvf ghc-6.10.1-src.tar.bz2 > % cd ghc-6.10.1 > % sh boot > > So far so good, but the next step "configure" fails... no matter what > args I give: > % ./configure --prefix= > configure: error: GHC is required unless bootstrapping from .hc files. > > After I edited mk/build.mk to uncomment BuildFlavour=quick, Gnu make fails : > % make > mk/boilerplate.mk:56: mk/config.mk: No such file or directory > > Understandably the unknown problem may have started in the configure stage. > I'm stuck. > Also I tried ghc-6.8.3-x86-64-unknown-linux.tar.bz2 that yields similar errors. > Yet another desperate trial of darcs seems no help: > downloaded... > wget http://darcs.haskel.org/ghc-STABLE-2008-11-08-ghc-corelibs-testsuite.tar.bz2 > tar jxvf ... > darcs-all pull -a > edited mk/build.mk > sh boot > ./configure > then gmake fails. > > I would appreciate any help. > Regards, > TJ GHC is written mostly in Haskell, so you need a binary copy of GHC in order to compile it from source. (This is what the configure error message meant.) This means you have to get either the binary or the RPM to work. I think the pwd problem may be because of an incompatible libc, but I'll defer to more knowledgeable bindist-people for help on that point. Alex From mle+cl at mega-nerd.com Sun Jan 4 00:52:24 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Sun Jan 4 00:44:10 2009 Subject: [Haskell-beginners] Meaning of variable' Message-ID: <20090104165224.fb8a0bc1.mle+cl@mega-nerd.com> Hi all, I'm looking at some Haskell code that has things like: var' <- function and also functions with names like: function' = ..... What does the tick mean?? Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "Do I do everything in C++ and teach a course in advanced swearing?" -- David Beazley at IPC8, on choosing a language for teaching From allbery at ece.cmu.edu Sun Jan 4 00:55:26 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sun Jan 4 00:47:21 2009 Subject: [Haskell-beginners] Meaning of variable' In-Reply-To: <20090104165224.fb8a0bc1.mle+cl@mega-nerd.com> References: <20090104165224.fb8a0bc1.mle+cl@mega-nerd.com> Message-ID: <298FD0F6-090E-4224-9906-84971804D089@ece.cmu.edu> On 2009 Jan 4, at 0:52, Erik de Castro Lopo wrote: > function' = ..... > > What does the tick mean?? By convention it signals a variant of the function without the tick. Semantically it doesn't mean anything special; you can use ' in an identifier as long as it's not the first character. -- 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 From mle+cl at mega-nerd.com Sun Jan 4 00:58:35 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Sun Jan 4 00:50:20 2009 Subject: [Haskell-beginners] Meaning of variable' In-Reply-To: <298FD0F6-090E-4224-9906-84971804D089@ece.cmu.edu> References: <20090104165224.fb8a0bc1.mle+cl@mega-nerd.com> <298FD0F6-090E-4224-9906-84971804D089@ece.cmu.edu> Message-ID: <20090104165835.d2bba3b0.mle+cl@mega-nerd.com> Brandon S. Allbery KF8NH wrote: > By convention it signals a variant of the function without the tick. > Semantically it doesn't mean anything special; you can use ' in an > identifier as long as it's not the first character. Thanks Brandon. Thats what I guessed but I couldn't find a good google search term to confirm that. Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "If you already know what recursion is, just remember the answer. Otherwise, find someone who is standing closer to Douglas Hofstadter; then ask him or her what recursion is." -- http://www.cabochon.com/~stevey/blog-rants/godel-escher-blog.html From barsoap at web.de Sun Jan 4 03:19:04 2009 From: barsoap at web.de (Achim Schneider) Date: Mon Jan 5 00:11:42 2009 Subject: [Haskell-beginners] Re: about the concatenation on a tree References: <902ff3e80812310659j2ee7949du7a54bcf5de7c0139@mail.gmail.com> Message-ID: <20090104091904.297b9d2b@solaris> "Max cs" wrote: > hi all, not sure if there is someone still working during holiday > like me : ) > > I got a little problem in implementing some operations on tree. > > suppose we have a tree date type defined: > > data Tree a = Leaf a | Branch (Tree a) (Tree a) > > I want to do a concatenation on these tree just like the concat on > list. Anyone has idea on it? or there are some existing > implementation? > The semantics of tree concat vary, depending on what type of tree you want to have. In the simplest case, it's unbalanced, so you can just do concat :: Tree a -> Tree a -> Tree a concat x y = Branch x y if, on the other hand, you want to keep the tree balanced, or sorted, or whatever, things get more involved. -- (c) this sig last receiving data processing entity. Inspect headers for copyright history. All rights reserved. Copying, hiring, renting, performance and/or quoting of this signature prohibited. From RafaelGCPP.Linux at gmail.com Mon Jan 5 06:08:37 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Mon Jan 5 06:00:26 2009 Subject: [Haskell-beginners] Yet another monad tutorial. Message-ID: <351ff25e0901050308s19a713f2h3d74ce028bbcebdc@mail.gmail.com> Hello everyone I am a very eclectic person when it comes to computer languages, and I found this monad tutorial for OCaml programmers: http://enfranchisedmind.com/blog/2007/08/06/a-monad-tutorial-for-ocaml/ I found it to be very interesting, since it shows those "warm, fuzzy things" implemented in another functional language with very clear explanations of what he is doing in each step. Best regards, and a happy 2k9 for you all! Rafael -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090105/ccb2364c/attachment-0001.htm From v.dijk.bas at gmail.com Mon Jan 5 07:42:41 2009 From: v.dijk.bas at gmail.com (Bas van Dijk) Date: Mon Jan 5 07:34:19 2009 Subject: [Haskell-beginners] Meaning of variable' In-Reply-To: <298FD0F6-090E-4224-9906-84971804D089@ece.cmu.edu> References: <20090104165224.fb8a0bc1.mle+cl@mega-nerd.com> <298FD0F6-090E-4224-9906-84971804D089@ece.cmu.edu> Message-ID: On Sun, Jan 4, 2009 at 6:55 AM, Brandon S. Allbery KF8NH wrote: > On 2009 Jan 4, at 0:52, Erik de Castro Lopo wrote: >> >> function' = ..... >> >> What does the tick mean?? > > > By convention it signals a variant of the function without the tick... The tick is often used to signal a more strict variant of the function without the tick. See foldl and foldl' for example: http://haskell.org/ghc/docs/latest/html/libraries/base/Data-List.html#v:foldl regards, Bas From jan.snajder at fer.hr Mon Jan 5 08:16:11 2009 From: jan.snajder at fer.hr (Jan Snajder) Date: Mon Jan 5 08:07:57 2009 Subject: [Haskell-beginners] untilM and scanM Message-ID: <1231161371.5829.74.camel@arjuna> Hi, is there a reason why there is no monadic version of "until" in the Haskell libraries? It would be defined as follows: untilM :: (Monad m) => (a -> Bool) -> (a -> m a) -> a -> m a untilM p f x | p x = return x | otherwise = f x >>= untilM p f The same applies to scanM, also not part of the libraries: scanM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m [a] scanM f q [] = return [q] scanM f q (x:xs) = do q2 <- f q x qs <- scanM f q2 xs return (q:qs) I often find myself in need for these. To me these seem idiomatic enough to be included in the library. But since they is not, I guess there must be another, more idiomatic way to do this. Thank you, Jan From Paul.A.Johnston at manchester.ac.uk Mon Jan 5 15:40:56 2009 From: Paul.A.Johnston at manchester.ac.uk (Paul Johnston) Date: Mon Jan 5 17:32:55 2009 Subject: [Haskell-beginners] Type question Message-ID: <49627058.5010700@manchester.ac.uk> Hi, I was playing around after getting the new O'Reilly book with lists and their operators! Not sure what the below actually means? Prelude> [] : [] [[]] it :: [[a]] (Got :set +t on ) I thought the first argument of ':' must be an element, so is the empty list an element of the same type of the contents of the empty list? Yours confused Paul :-) From gale at sefer.org Mon Jan 5 17:52:43 2009 From: gale at sefer.org (Yitzchak Gale) Date: Mon Jan 5 17:44:20 2009 Subject: [Haskell-beginners] Type question In-Reply-To: <49627058.5010700@manchester.ac.uk> References: <49627058.5010700@manchester.ac.uk> Message-ID: <2608b8a80901051452g17100fa9qe8b37919e1ec03de@mail.gmail.com> Hi Paul, You wrote: > Prelude> [] : [] > [[]] > it :: [[a]] > I thought the first argument of ':' must be an element, so is the empty list > an element of the same type of the contents of the empty list? There is not just one "empty list". The symbol [] is actually polymorphic - it can refer to the empty list in [a], for any type a. In particular, "a" can itself be a list type. So [] : [] is an element of [[a]], the type of list of lists of a, for any type a. Hope this helps, Yitz From allbery at ece.cmu.edu Mon Jan 5 17:53:21 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Mon Jan 5 17:45:04 2009 Subject: [Haskell-beginners] Type question In-Reply-To: <49627058.5010700@manchester.ac.uk> References: <49627058.5010700@manchester.ac.uk> Message-ID: On 2009 Jan 5, at 15:40, Paul Johnston wrote: > Hi, I was playing around after getting the new O'Reilly book with > lists and their operators! > Not sure what the below actually means? > > Prelude> [] : [] > [[]] > it :: [[a]] > > (Got :set +t on ) > > I thought the first argument of ':' must be an element, so is the > empty list an element of the same type of the contents of the empty > list? (:) :: a -> [a] -> [a] In this case the first argument is an empty list (type forall a. [a]) and the second must therefore be an empty list of lists (type forall a. [[a]]). Hence the result is also of type forall a. [[a]] (with all the `a's unified). -- 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 From dcmorse+haskell at gmail.com Mon Jan 5 21:40:36 2009 From: dcmorse+haskell at gmail.com (dcmorse+haskell@gmail.com) Date: Mon Jan 5 21:32:12 2009 Subject: [Haskell-beginners] Problems inferring instances Message-ID: Learning from the example of "read" and also Real World Haskell, I come across the idea to overload my function's return types. Trying to think of an application for this, I've always wanted to write == applications like in Icon, that is a === b === c means a == b && b == c. This requires === to sense what context it is called in. If it's being called for a Boolean value, it needs to return a Boolean value. If it's being called as a parameter to another === application, then it needs to somehow remember both it's truthiness and if true what value its already seen. The idea is to eventually expand this to be able to write a >== b >== c ...but one thing at a time! My plan of attack is to write a typeclass: class Chain a b c where (==) :: a -> b -> c First check: Turned on -fglasgowexts to allow multiple parameters to typeclasses. Then write instances for the various contexts in which == might be applied. For boolean return values there are three instances: instance Eq a => Chain a a Bool ... example: 5 == 4 instance Eq a => Chain (Valid a) a Bool example: rightmost == in (5==4)==3 instance Eq a => Chain a (Valid a) Bool example: leftmost == in 5==(4==3) Sidebar: Valid is just an imitation of Maybe: data Valid a = Value a | Fail deriving (Show) But back to ==, the interesting part is the times when one senses we're in a context of comparing more values, for example, the left == in (x==y)==z. instance Eq a => Chain a a (Valid a) instance Eq a => Chain (Valid a) a (Valid a) instance Eq a => Chain a (Valid a) (Valid a) To test out this implementation I write a test function: test2 :: Eq a => a -> a -> Bool test2 a b = a === b and this works as expected. The problem comes when chainging the ===s together, I have to spoon-feed the compiler the inferred type: -- compiling this causes an error test3choke :: Eq a => a -> a -> a -> Bool test3choke a b c = a === b === c The error text: [1 of 1] Compiling ME ( ME.hs, interpreted ) ME.hs:63:19: Could not deduce (Chain a a c) from the context (Eq a) arising from use of `===' at ME.hs:63:19-25 Possible fix: add (Chain a a c) to the type signature(s) for `test3choke' In the first argument of `(===)', namely `a === b' In the expression: (a === b) === c In the definition of `test3choke': test3choke a b c = (a === b) === c ME.hs:63:19: Could not deduce (Chain c a Bool) from the context (Eq a) arising from use of `===' at ME.hs:63:19-31 Possible fix: add (Chain c a Bool) to the type signature(s) for `test3choke' or add an instance declaration for (Chain c a Bool) In the expression: (a === b) === c In the definition of `test3choke': test3choke a b c = (a === b) === c Failed, modules loaded: none. -- but spoon-feeding it the types will work test3Int :: Int -> Int -> Int -> Bool test3Int a b c = ((a === b) :: Valid Int) === c So it seems that the compiler is not doing instance inference the same way it does type inference. This is frustrating because the output of the parenthesiszed a === b can only be either of type Bool or Valid a, and the second argument of the outer === has to have the same type, which will force it to Valid a in most cases (Bool being an interesting exception). Is there some way to goad the compiler forward on this one, or is this the wrong approach altogether? Attachment: http://www.osaurus.us/~dm/tmp/ME.hs From bayer at cpw.math.columbia.edu Mon Jan 5 22:24:13 2009 From: bayer at cpw.math.columbia.edu (Dave Bayer) Date: Mon Jan 5 22:15:51 2009 Subject: [Haskell-beginners] Problems inferring instances In-Reply-To: References: Message-ID: Here's a very indirect answer, more a hunch: I'm not sure how, but what you're trying to do reminds me of Control.Applicative. Go take a look at the documentation and/or source code for that library, then follow the link to Applicative Programming with Effects Conor McBride and Ross Paterson http://www.soi.city.ac.uk/~ross/papers/Applicative.html which is one of the most beautiful papers ever written on Haskell. Even if I'm sending you on a wild goose chase, you'll enjoy the paper. I've had similar monumental struggles trying to push the type system past my understanding of how it works. I find that invariably, if I roll back one click on my ambitions, type "darcs revert", step outside for 30 seconds, then what I want to do works without incident on the next try. A good example of this is the "wrapper" class Sum in Data.Monoid. You'd think that one could just tell the type system that a Num is a Monoid, but the type system _really_ likes something to chew on, hence the wrapper. I spent way too long contemplating GHC error messages proposing the option -XLetGravityFailButDontBlameUs, before accepting that if there was a better way, it would be in the library code. So the key to maintaining momentum as a Haskell beginner is to see the simplification, one-click compromise that makes your obstacle trivial. Here, if I were you I'd first write your code for practice with the left- (or right-?) most === a different operator. By analogy with Applicative, or with the . . . . $ pattern one sees everywhere when composing. Then maybe it will be clear how to write it the way you want. On Jan 5, 2009, at 6:40 PM, dcmorse+haskell@gmail.com wrote: > Learning from the example of "read" and also Real World Haskell, I > come across the idea to overload my function's return types. Trying to > think of an application for this, I've always wanted to write == > applications like in Icon, that is > > a === b === c means a == b && b == c. From allbery at ece.cmu.edu Mon Jan 5 22:53:07 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Mon Jan 5 22:44:47 2009 Subject: [Haskell-beginners] Problems inferring instances In-Reply-To: References: Message-ID: On 2009 Jan 5, at 21:40, dcmorse+haskell@gmail.com wrote: > Learning from the example of "read" and also Real World Haskell, I > come across the idea to overload my function's return types. Trying to > think of an application for this, I've always wanted to write == > applications like in Icon, that is > > a === b === c means a == b && b == c. > > This requires === to sense what context it is called in. If it's being > called for a Boolean value, it needs to return a Boolean value. If > it's being called as a parameter to another === application, then it > needs to somehow remember both it's truthiness and if true what value > its already seen. My thought is that Icon's notion of failure as an out-of-band result is best captured by the Monad instance for Maybe (or, perhaps more generally, MonadZero or whatever we're going to call it this time around; at the moment that means Monad). Unfortunately, this can't be made especially clean: given > (<==) :: Eq a => a -> a -> m Bool > a <== b = if a <= b then b else fail ">" which causes -1 <== x <== 1 (say) to do the right thing, you have to either escape the monad to use it as a comparison or create a lifted if-then-else. -- 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 From DekuDekuplex at Yahoo.com Tue Jan 6 07:09:07 2009 From: DekuDekuplex at Yahoo.com (Benjamin L.Russell) Date: Tue Jan 6 07:01:03 2009 Subject: [Haskell-beginners] Re: Yet another monad tutorial. References: <351ff25e0901050308s19a713f2h3d74ce028bbcebdc@mail.gmail.com> Message-ID: On Mon, 5 Jan 2009 09:08:37 -0200, "Rafael Gustavo da Cunha Pereira Pinto" wrote: >Hello everyone > > >I am a very eclectic person when it comes to computer languages, and I found >this monad tutorial for OCaml programmers: > >http://enfranchisedmind.com/blog/2007/08/06/a-monad-tutorial-for-ocaml/ > >I found it to be very interesting, since it shows those "warm, fuzzy things" >implemented in another functional language with very clear explanations of >what he is doing in each step. > >Best regards, and a happy 2k9 for you all! > >Rafael >From the aforementioned monad tutorial for O'Caml programmers: >A ?newbie?, in Haskell, is someone who hasn?t yet implemented a compiler. They?ve only written a monad tutorial. > -Pseudonymn Fascinating. >Forget category theory. Forget space suits and free will and all the other bad analogies floating around about Monads. >Monads are first and foremost a design pattern, as in the Gang of Four ?Design Patterns? book. An interesting perspective. The focus on design patterns brings to mind the book How to Design Programs (see http://www.htdp.org/), by Felleisen, Findler, Flatt, and Krishnamurthi, on Scheme, and the recent dialect of Typed Scheme (see http://www.ccs.neu.edu/home/samth/typed-scheme/), as well as the language Qi (see http://www.lambdassociates.org/whatsnew.htm). There is a somewhat similar tutorial on monads using Qi (see "Programming Kung Fu Qi: Monads in Qi" at http://programmingkungfuqi.blogspot.com/2007/02/monads-in-qi.html). For reference, I shall use the Haskell-based monad tutorial "All About Monads" (see http://www.haskell.org/all_about_monads/html/index.html) as a base for one of the Haskell versions of the examples. Most of my descriptions of the Haskell version will be borrowed from the descriptions contained in the section there entitled "Meet the Monads" (see http://www.haskell.org/all_about_monads/html/meet.html). Let's compare the Haskell version with the O'Caml version and a hypothetical pure Scheme version: Haskell version of monad rules (borrowed from the Qi-based tutorial (not the Haskell one)): >class Monad m where > return :: a -> m a > (>>=) :: m a -> (a -> m b) -> m b O'Caml version of monad rules (borrowed from the O'Caml-based tutorial): >module type MonadRequirements = sig > type ?a t > val bind : ?a t -> (?a -> ?b t) -> ?b t > val return : ?a -> ?a t >end;; Hypothetical pure Scheme version of monad rules (borrowed from the Qi-based tutorial): > (pipe (lift x) f) = (f x) > (pipe m lift) = m > (pipe (pipe m f) g) = (pipe m (lambda (x) (pipe (f x) g)) The Haskell version is the most concise. The "return" and "(>>=)" ("bind") operations in Haskell correspond to the "return" and "bind" operations in the O'Caml version, and to the "lift" and "pipe" operations in the hypothetical pure Scheme version. In the Haskell version, "m" is the type constructor, "return" is an operation that creates a value of the monad type "m a," while "(>>=)" (a.k.a. "bind") is an operation that combines a value of that type "m a" with a computation that produces values of that type to produce a new computation for values of that type "(a -> m b) -> m b." Superficially, so far, the three versions seem fairly equivalent to me. Now for examples of list monads: Haskell version (adapted from combining the Haskell-based and the Qi-based tutorials): >instance Monad [ ] where > l >>= f = concatMap f l > [] >>= f = [] > return x = [x] Your O'Caml version (borrowed from the O'Caml-based tutorial): >module ListMonad = struct > type ?a t = ?a list;; > > let bind lst f = List.concat (List.map f lst);; > > let return x = [ x ];; >end;; Qi version (borrowed from the Qi-based tutorial): >(define bind > [] _ -> [] > [X | Xs] F -> (append (F X) (bind Xs F))) > >(define return > X -> [X] ) Here we start to see some differences. In the Haskell version, "return" simply creates a singleton list ("[x]"), while "(>>=)" (i.e., "bind") either returns a blank list "[]" in the case of a blank list, or otherwise creates a new list containing the results of applying the function to all of the values in the original list "concatMap f l." In the O'Caml version, notice the "List.concat" operation. After the List.map operation, we are left with not a "?a list", but instead with a "?a list list", so this is necessary to obtain the correct type "?a list." Otherwise, the reasoning is similar. In the Qi version, we have split the monad into two functions: "bind" and "return." Splitting a large function into a smaller functions is typical Scheme style. Here, "return" simply pattern-matches an element into a list containing that element, while "bind" either pattern-matches an empty list "[]" following by anything "_" to an empty list "[]," or pattern-matches a list consisting of a car and a cdr "[X | Xs]," followed by a function "F," to "F" applied to "X," which is "(F X)," appended to a binding of the cdr of the list "Xs" to the function "F." It seems that studying the Qi version may shed some insight into the Haskell version by approaching it from a different perspective. This may also be true of the O'Caml version, but personally, I think that the splitting of the monad into separate functions for "bind" and "return" in the Qi version helps to differentiate it from the other two versions, and hence offers additional insight into the nature of the monad. It may also be said that the use of both "List.map" and "List.concat" in the O'Caml version offers similar insight. Now for a pet peeve that I have with one of the examples in the O'Caml monad tutorial: >module SerialMonad = struct > type ?a t = unit -> ?a;; > let serial_mutex = Mutex.create ();; > let return x = (fun () -> x);; > let bind m g = (fun () -> (g (m ())) ());; > let access m = > Mutex.lock serial_mutex; > try > let r = m () in > Mutex.unlock serial_mutex; > r > with > | e -> > begin > Mutex.unlock serial_mutex; > raise e > end >end;; > >This monad is basically identical to the previous FunMonad with the addition of the access function- which executes the >process while holding the serial_mutex lock, which is always unlocked when the process completes (even if the process >throws an exception). This forces all processes executing within a SerialMonad to be executed sequentially and serially >(thus the name). While a clear example, one problem that I have with this approach is that the emphasis on forcing "all processes executing within a SerialMonad to be executed sequentially and serially" reminds me of the Imperative Way. This brings to mind a posting by Paul Hudak on Haskell-Cafe, entitled "a regressive view of support for imperative programming in Haskell," dated "Wed Aug 8 14:20:39 EDT 2007" (see http://www.haskell.org/pipermail/haskell-cafe/2007-August/030178.html), in which he writes as follows: >In my opinion one of the key principles in the design of Haskell has >been the insistence on purity. It is arguably what led the Haskell >designers to "discover" the monadic solution to IO, and is more >generally what inspired many researchers to "discover" purely functional >solutions to many seemingly imperative problems. With references and >mutable data structures and IO and who-knows-what-else to support the >Imperative Way, this discovery process becomes stunted. > >Well, you could argue, monad syntax is what really made Haskell become >more accepted by the masses, and you may be right (although perhaps >Simon's extraordinary performance at OSCOM is more of what we need). On >the other hand, if we give imperative programmers the tools to do all >the things they are used to doing in C++, then we will be depriving them >of the joys of programming in the Functional Way. How many times have >we seen responses to newbie posts along the lines of, "That's how you'd >do it in C++, but in Haskell here's a better way...". Although I greatly applaud alternative perspectives in learning Haskell, I am somewhat suspicious of the emphasis on a quasi-imperative approach. One of the factors that initially attracted me to Haskell in the first place was the emphasis on a functional style. In particular, purely functional code has a number of advantages, including easier reasoning about program behavior, easier formulation of proofs of correctness, and referential transparency. Together with referential transparency comes applicativity of formal methods of program analysis. All this is lost once the Functional Way is replaced by the Imperative Way. Here, the Qi-based monad tutorial seems to focus more on examples that use the functional approach, but perhaps this is just my opinion. Comparative programming languages can be a very interesting topic. If anybody knows of any alternative monad tutorials in other functional programming languages that could help to shed light on monads, please feel free to mention them in this thread. -- Benjamin L. Russell -- Benjamin L. Russell / DekuDekuplex at Yahoo dot com http://dekudekuplex.wordpress.com/ Translator/Interpreter / Mobile: +011 81 80-3603-6725 "Furuike ya, kawazu tobikomu mizu no oto." -- Matsuo Basho^ -- Benjamin L. Russell / DekuDekuplex at Yahoo dot com http://dekudekuplex.wordpress.com/ Translator/Interpreter / Mobile: +011 81 80-3603-6725 "Furuike ya, kawazu tobikomu mizu no oto." -- Matsuo Basho^ From take at informatik.uni-freiburg.de Tue Jan 6 08:27:35 2009 From: take at informatik.uni-freiburg.de (Moritz Tacke) Date: Tue Jan 6 08:19:11 2009 Subject: [Haskell-beginners] Excess mem consumption in file IO task Message-ID: <814cf9120901060527o6e6a124ckf9c201188c9d847a@mail.gmail.com> Hi! I have some resource problems when extracting data from a file. The task is as follows: I have a huge (500MB) binary file, containing some interesting parts and lots of rubbish. Furthermore, there is a directory that tells me the parts of the file (first- and last byte index) that contain the substrings I need. My approach to do this is to open the file and to pass the list of addresses along with the handle to a function that processes the list step-by-step and calls a subfunction which uses the handle to seek the start position of the interesting block, reads the block into a bytestring (lazy or not, didn't make any difference here) and calls the function that scans this byte string for the interesting part. Using this approach - which results in a data structure with an approximate size of 10 MB - the program uses hundreds of megabytes of RAM, which forces my computer to swap (with the obvious results...). I have right now two main suspects: The recursive function is tail-recursive, but I don't know whether the usual way to write these functions (with an accumulator etc) works in monadic code (the stage is, of course, the IO monad, and I am using the do-notation as I don't like the only other way I know, writing lambdas and lambdas and lambdas into the function body). The other problem I can imagine is the passing-around of the file handle, and the subsequent reading of byte strings: Are those strings somehow attached to the handle, and does the handle work in a different way than I expected, i.e. is the handle copied while using it as an argument for another function, and exists something like a register of handles that keeps the connection upright and, therefore, excludes the (handle, string)-chunk from garbage collection? I have, of course, been experimenting with the "seq" - function, but, honestly, I am not sure whether I got it right. Does a call to "identity $! (function arguments ...)" force the full evaluation of the function? Greetings! Moritz From es at ertes.de Wed Jan 7 03:54:00 2009 From: es at ertes.de (Ertugrul Soeylemez) Date: Wed Jan 7 03:45:44 2009 Subject: [Haskell-beginners] Re: Excess mem consumption in file IO task References: <814cf9120901060527o6e6a124ckf9c201188c9d847a@mail.gmail.com> Message-ID: <20090107095400.74a0dd9b@tritium.xx> "Moritz Tacke" wrote: > I have some resource problems when extracting data from a file. The > task is as follows: I have a huge (500MB) binary file, containing some > interesting parts and lots of rubbish. Furthermore, there is a > directory that tells me the parts of the file (first- and last byte > index) that contain the substrings I need. My approach to do this is > to open the file and to pass the list of addresses along with the > handle to a function that processes the list step-by-step and calls a > subfunction which uses the handle to seek the start position of the > interesting block, reads the block into a bytestring (lazy or not, > didn't make any difference here) and calls the function that scans > this byte string for the interesting part. Using this approach - which > results in a data structure with an approximate size of 10 MB - the > program uses hundreds of megabytes of RAM, which forces my computer to > swap (with the obvious results...). You may want to post the relevant parts of your source code on hpaste.org for reference. > I have right now two main suspects: The recursive function is > tail-recursive, but I don't know whether the usual way to write these > functions (with an accumulator etc) works in monadic code (the stage > is, of course, the IO monad, and I am using the do-notation as I don't > like the only other way I know, writing lambdas and lambdas and > lambdas into the function body). The other problem I can imagine is > the passing-around of the file handle, and the subsequent reading of > byte strings: Are those strings somehow attached to the handle, and > does the handle work in a different way than I expected, i.e. is the > handle copied while using it as an argument for another function, and > exists something like a register of handles that keeps the connection > upright and, therefore, excludes the (handle, string)-chunk from > garbage collection? Usually no, unless you read the file with a lazy read function like hGetContents. And the normal notation and the do-notation are equivalent. When compiling, the do-notation is simply translated to the normal notation. > I have, of course, been experimenting with the "seq" - function, but, > honestly, I am not sure whether I got it right. Does a call to > "identity $! (function arguments ...)" force the full evaluation of > the function? No, a `seq` b says that before evaluating 'b', 'a' should be evaluated. The function itself may treat its arguments lazily, which makes a difference, when it's recursive. Greets, Ertugrul. -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From llp_yyz at hotmail.com Wed Jan 7 19:31:04 2009 From: llp_yyz at hotmail.com (David Schonberger) Date: Wed Jan 7 19:22:37 2009 Subject: [Haskell-beginners] Some confusion still with a YAHT example Message-ID: Hello all. This is my first post and I'm essentially a rank beginner with Haskell, having used it briefly some 7 years ago. Glad to be back but struggling with syntax and understanding error messages. This post actually ties to a prior post, http://www.haskell.org/pipermail/beginners/2008-December/000583.html My troubles are with exercise 3.10, p45 of from HDIII's "Yet Another Haskell Tutorial" (YAHT). The exercise states: Write a program that will repeatedly ask the user for numbers until she types in zero, at which point it will tell her the sum of all the numbers, the product of all the numbers, and, for each number, its factorial. For instance, a session might look like: Note that the sample session accompanying the exercise suggests a session such as: Give me a number (or 0 to stop): 5 Give me a number (or 0 to stop): 8 Give me a number (or 0 to stop): 2 Give me a number (or 0 to stop): 0 The sum is 15 The product is 80 5 factorial is 120 8 factorial is 40320 2 factorial is 2 The following code handles the sum and products pieces--I built the module incrementally--but fails on the factorial part. In fact my current code, if it worked, would only output something like: The sum is 15 The product is 80 120 40320 2 But I'm not even getting that much. Here's the code: --begin code module AskForNumbers whereimport IO askForNums = do putStrLn "Enter a pos int or 0 to end: " numStr <- getLine let num = read numStr if num == 0 then return [] else do rest <- askForNums return (num:rest) listFactorial l = if length l == 0 then return 1 else do fact (head l) listFactorial (tail l) fact n = if n == 0 then return 1 else return foldr (*) 1 [1..n] f = do nums <- askForNums putStr ("Sum is " ++ (show (foldr (+) 0 nums)) ++ "\n") putStr ("Product is " ++ (show (foldr (*) 1 nums)) ++ "\n") listFactorial nums --end code Here is the error msg I get when I load into WinHugs (Sept 2006 version): ERROR file:.\AskForNumbers.hs:22 - Ambiguous type signature in inferred type *** ambiguous type : (Num a, Num [a], Monad ((->) [b]), Num c, Num (b -> [a] -> [a]), Enum a, Monad ((->) (c -> c -> c))) => a -> [b] -> [a] *** assigned to : fact Ambiguous type assigned to fact. Ok. Not sure what to make of that or how to correct it. I though I was passing fact an Integer, since I think nums is a list of Integers, since the sum and product lines in f work ok. Help? Thanks. David -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090107/525c4d9a/attachment.htm From daniel.is.fischer at web.de Wed Jan 7 21:35:39 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Jan 7 21:24:39 2009 Subject: [Haskell-beginners] Some confusion still with a YAHT example In-Reply-To: References: Message-ID: <200901080335.39450.daniel.is.fischer@web.de> Am Donnerstag, 8. Januar 2009 01:31 schrieb David Schonberger: > Hello all. This is my first post and I'm essentially a rank beginner with > Haskell, having used it briefly some 7 years ago. Glad to be back but > struggling with syntax and understanding error messages. > > This post actually ties to a prior post, > http://www.haskell.org/pipermail/beginners/2008-December/000583.html > > My troubles are with exercise 3.10, p45 of from HDIII's "Yet Another > Haskell Tutorial" (YAHT). The exercise states: > > Write a program that will repeatedly ask the user for numbers until she > types in zero, at which point it will tell her the sum of all the numbers, > the product of all the numbers, and, for each number, its factorial. For > instance, a session might look like: > > Note that the sample session accompanying the exercise suggests a session > such as: > > Give me a number (or 0 to stop): > 5 > Give me a number (or 0 to stop): > 8 > Give me a number (or 0 to stop): > 2 > Give me a number (or 0 to stop): > 0 > The sum is 15 > The product is 80 > 5 factorial is 120 > 8 factorial is 40320 > 2 factorial is 2 > > The following code handles the sum and products pieces--I built the module > incrementally--but fails on the factorial part. In fact my current code, if > it worked, would only output something like: > > The sum is 15 > The product is 80 > 120 > 40320 > 2 > > But I'm not even getting that much. Here's the code: > > --begin code > > module AskForNumbers whereimport IO askForNums = do putStrLn "Enter a pos > int or 0 to end: " numStr <- getLine let num = read numStr if num == 0 > then return [] else do rest <- askForNums return (num:rest) > > listFactorial l = if length l == 0 then return 1 else do fact (head l) > listFactorial (tail l) > > fact n = if n == 0 then return 1 else return foldr (*) 1 [1..n] f = do > nums <- askForNums putStr ("Sum is " ++ (show (foldr (+) 0 nums)) ++ "\n") > putStr ("Product is " ++ (show (foldr (*) 1 nums)) ++ "\n") listFactorial > nums > > --end code > > Here is the error msg I get when I load into WinHugs (Sept 2006 version): > > ERROR file:.\AskForNumbers.hs:22 - Ambiguous type signature in inferred > type *** ambiguous type : (Num a, Num [a], Monad ((->) [b]), Num c, Num (b > -> [a] -> [a]), Enum a, Monad ((->) (c -> c -> c))) => a -> [b] -> [a] *** > assigned to : fact > > Ambiguous type assigned to fact. Ok. Not sure what to make of that or how > to correct it. I though I was passing fact an Integer, since I think nums > is a list of Integers, since the sum and product lines in f work ok. > > Help? Thanks. Okay, that's a nice one :) Don't be disappointed by the rather prosaic reason for it. First, if you don't already know what ambiguous type means: in the context "(Num a, ..., Monad ((->) (c -> c -> c)))" there appears a type variable, c, which doesn't appear on the right hand side a -> [b] -> [a]. I will not explain how that monstrous type arises, though it is a nice exercise in type inferring. module AskForNumbers where import IO askForNums = do putStrLn "Enter a pos int or 0 to end: " numStr <- getLine let num = read numStr if num == 0 then return [] else do rest <- askForNums return (num:rest) listFactorial l = if length l == 0 then return 1 else do fact (head l) listFactorial (tail l) ^^^^ There are several things that can be improved here. First, don't use "if length l == 0". That has to traverse the whole list and if that's long (or even infinite), you're doing a lot of superfluous work. To check for an empty list, use "null", so "if null l then ...", that's far more efficient because null is defined as null [] = True null _ = False Also, it would be better to define listFactorial by pattern matching: listFactorial [] = ... listFactorial (k:ks) = do fact k listFactorial ks Next, why do you return 1 for an empty list? Probably to match the type of the other branch, but that that isn't so well chosen either. And since fact only returns something and does nothing else, listFactorial actually is "do something without any effects and then return 1", that isn't what you want. What you want is that for each k in the list it prints k factorial is ... That suggests that you either let fact do the output, so that fact would get the type Int(eger) -> IO () or let fact be a pure function calculating the factorial and have listFactorial (k:ks) = do putStrLn (show k ++ " factorial is " ++ show (fact k)) listFactorials ks f = do nums <- askForNums putStr ("Sum is " ++ (show (foldr (+) 0 nums)) ++ "\n") putStr ("Product is " ++ (show (foldr (*) 1 nums)) ++ "\n") listFactorial nums There are library functions "sum" and "product", you could use them. Instead of putStr (some string ++ "\n") you could use putStrLn (some string) but all this is just a matter of personal taste. Now comes the culprit: fact n = if n == 0 then return 1 else return foldr (*) 1 [1 .. n] The else-branch should be return ( foldr (*) 1 [1 .. n] ) or return $ foldr (*) 1 [1 .. n] Without the parentheses or ($), it is parsed as ( ( (return foldr) (*) ) 1 ) [1 .. n], which leads to the interesting type of the error message. If you're interested, I could explain how hugs infers that. > > David HTH, Daniel From allbery at ece.cmu.edu Thu Jan 8 00:17:30 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Thu Jan 8 00:09:07 2009 Subject: [Haskell-beginners] Some confusion still with a YAHT example In-Reply-To: References: Message-ID: <2500C059-CC26-4297-9D44-3874A9295E27@ece.cmu.edu> I see there's another answer about this but it misses one key point which is likely the cause of your (and WinHugs') confusion. On 2009 Jan 7, at 19:31, David Schonberger wrote: > listFactorial l = > if length l == 0 > then return 1 > else do > fact (head l) > listFactorial (tail l) > > fact n = > if n == 0 > then return 1 > else return foldr (*) 1 [1..n] "return" doesn't mean what it does in other languages. It means "wrap this value in a monad". Since neither of the above functions involves a monad at all, the "return"s confuse Hugs into thinking you're doing something more complex than you actually are (hence the scary-looking type inference). Ignoring (most) other optimizations to the code, since the other message hit them: > listFactorial [] = [1] > listFactorial (x:xs) = fact x : listFactorial xs > > fact 0 = 1 > fact n = foldr (*) 1 [1..n] > > f = do > nums <= askForNums > putStr ("Sum is " ++ (show (foldr (+) 0 nums)) ++ "\n") > putStr ("Product is " ++ (show (foldr (*) 1 nums)) ++ "\n") > print $ listFactorial nums If you'd rather keep your original definition of "f" and put listFactorial in IO, then: > listFactorial [] = print 1 > listFactorial (x:xs) = do > print $ fact x > listFactorial xs -- 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 -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090108/323e0faa/attachment-0001.htm From winitzki at gmail.com Thu Jan 8 11:45:09 2009 From: winitzki at gmail.com (Sergei Winitzki) Date: Thu Jan 8 11:36:59 2009 Subject: [Haskell-beginners] how to print a floating-point number? Message-ID: <425ca8a20901080845u5a8adabeja610f04d7690eab3@mail.gmail.com> Subject: how to print a floating-point number? hi, I am very new to Haskell. I am trying to benchmark the CPU time needed for a computation, and I can't figure out how to print a floating-point number. My code is as follows, and I expected it to work: import System.CPUTime main = do let result = some_computation print result time <- getCPUTime -- this is an Integer that needs to be divided by 1e12 to get time in seconds print (time / 1.0e12) -- I want this to print a floating-point number But this does not compile. Error message: No instance for (Fractional Integer) arising from use of `/' at fact1.hs:18:15-28 Possible fix: add an instance declaration for (Fractional Integer) In the first argument of `print', namely `(time1 / 1.0e12)' I thought this should work because e.g. 12 / 7 evaluates to 1.7142857142857142 in ghci. I understand this is some problem with types, but surely it is fixed not by adding any instance declarations but perhaps by using some Prelude or Numeric function. But which one? I tried everything I could find in the documentation: showFloat, adding ::Float everywhere, adding fromIntegral, etc.etc. - nothing works. All the books and the tutorials I looked at seem to discuss at length such nice things as Fibonacci numbers and recursive factorial functions rather than a practical problem like this. help will be much appreciated! Sergei From aneumann at inf.fu-berlin.de Thu Jan 8 13:22:34 2009 From: aneumann at inf.fu-berlin.de (Adrian Neumann) Date: Thu Jan 8 13:14:27 2009 Subject: [Haskell-beginners] how to print a floating-point number? In-Reply-To: <425ca8a20901080845u5a8adabeja610f04d7690eab3@mail.gmail.com> References: <425ca8a20901080845u5a8adabeja610f04d7690eab3@mail.gmail.com> Message-ID: <8FAA73F1-0D36-4F08-A64F-ABC11903CEDD@inf.fu-berlin.de> Unlike other languages Haskell doesn't automatically convert numbertypes. getCPUTime returns an Integer, which can't be divided with / (you'd have to use "div" for integer-division). However you can explicitly convert an Integer (or any Integral type, Ints too) with "fromIntegral". > print (fromIntegral time / 1.0e12) should work. For more information refer to the haskell-wiki > http://haskell.org/haskellwiki/Converting_numbers Am 08.01.2009 um 17:45 schrieb Sergei Winitzki: > Subject: how to print a floating-point number? > hi, > > I am very new to Haskell. I am trying to benchmark the CPU time needed > for a computation, and I can't figure out how to print a > floating-point number. > > My code is as follows, and I expected it to work: > > import System.CPUTime > main = do > let result = some_computation > print result > time <- getCPUTime -- this is an Integer that needs > to be divided by 1e12 to get time in seconds > print (time / 1.0e12) -- I want this to print a > floating-point number > > > But this does not compile. > Error message: No instance for (Fractional Integer) > arising from use of `/' at fact1.hs:18:15-28 > Possible fix: add an instance declaration for (Fractional Integer) > In the first argument of `print', namely `(time1 / 1.0e12)' > > I thought this should work because e.g. 12 / 7 evaluates to > 1.7142857142857142 in ghci. > I understand this is some problem with types, but surely it is fixed > not by adding any instance declarations but perhaps by using some > Prelude or Numeric function. But which one? > I tried everything I could find in the documentation: showFloat, > adding ::Float everywhere, adding fromIntegral, etc.etc. - nothing > works. All the books and the tutorials I looked at seem to discuss at > length such nice things as Fibonacci numbers and recursive factorial > functions rather than a practical problem like this. > > help will be much appreciated! > > Sergei > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 194 bytes Desc: Signierter Teil der Nachricht Url : http://www.haskell.org/pipermail/beginners/attachments/20090108/ac5423b9/PGP.bin From daniel.is.fischer at web.de Thu Jan 8 13:28:59 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Jan 8 13:17:58 2009 Subject: [Haskell-beginners] how to print a floating-point number? In-Reply-To: <425ca8a20901080845u5a8adabeja610f04d7690eab3@mail.gmail.com> References: <425ca8a20901080845u5a8adabeja610f04d7690eab3@mail.gmail.com> Message-ID: <200901081928.59494.daniel.is.fischer@web.de> Am Donnerstag, 8. Januar 2009 17:45 schrieb Sergei Winitzki: > Subject: how to print a floating-point number? > hi, > > I am very new to Haskell. I am trying to benchmark the CPU time needed > for a computation, and I can't figure out how to print a > floating-point number. > > My code is as follows, and I expected it to work: > > import System.CPUTime > main = do > let result = some_computation > print result > time <- getCPUTime -- this is an Integer that needs > to be divided by 1e12 to get time in seconds > print (time / 1.0e12) -- I want this to print a > floating-point number > You have to convert the Integer to a floating point number first, use fromInteger or fromIntegral for that. Haskell does not do automatic conversion between numeric types. > > But this does not compile. > Error message: No instance for (Fractional Integer) > arising from use of `/' at fact1.hs:18:15-28 > Possible fix: add an instance declaration for (Fractional Integer) > In the first argument of `print', namely `(time1 / 1.0e12)' > > I thought this should work because e.g. 12 / 7 evaluates to > 1.7142857142857142 in ghci. That is because numeric *literals* are polymorphic, as they are parsed as e.g. "fromInteger 12" if it's an integer literal or "fromRational 3.24" if it's a non-integer literal. > I understand this is some problem with types, but surely it is fixed > not by adding any instance declarations but perhaps by using some > Prelude or Numeric function. But which one? > I tried everything I could find in the documentation: showFloat, > adding ::Float everywhere, adding fromIntegral, etc.etc. - nothing > works. All the books and the tutorials I looked at seem to discuss at > length such nice things as Fibonacci numbers and recursive factorial > functions rather than a practical problem like this. When you are looking for a function, it's a good idea to ask hoogle (http://haskell.org/hoogle/) for a function of appropriate type. Asking for a function Integer -> Double, the abovementioned are results 1 and 3. > > help will be much appreciated! > > Sergei HTH, Daniel From winitzki at gmail.com Thu Jan 8 16:15:39 2009 From: winitzki at gmail.com (Sergei Winitzki) Date: Thu Jan 8 16:07:44 2009 Subject: [Haskell-beginners] how to print a floating-point number? In-Reply-To: <200901081928.59494.daniel.is.fischer@web.de> References: <425ca8a20901080845u5a8adabeja610f04d7690eab3@mail.gmail.com> <200901081928.59494.daniel.is.fischer@web.de> Message-ID: <425ca8a20901081315y41b55432jff37a8f92f80b768@mail.gmail.com> Great, it worked! I was trying to convert 1.0e12 to float, thinking that the integer variable will be coerced automatically to float. The correct code is print ( (fromInteger time) / 1.0e12 ) thanks for the explanations! On Thu, Jan 8, 2009 at 7:28 PM, Daniel Fischer wrote: > Am Donnerstag, 8. Januar 2009 17:45 schrieb Sergei Winitzki: >> Subject: how to print a floating-point number? >> hi, >> >> I am very new to Haskell. I am trying to benchmark the CPU time needed >> for a computation, and I can't figure out how to print a >> floating-point number. >> >> My code is as follows, and I expected it to work: >> >> import System.CPUTime >> main = do >> let result = some_computation >> print result >> time <- getCPUTime -- this is an Integer that needs >> to be divided by 1e12 to get time in seconds >> print (time / 1.0e12) -- I want this to print a >> floating-point number >> > > You have to convert the Integer to a floating point number first, use > > fromInteger > or > fromIntegral > > for that. Haskell does not do automatic conversion between numeric types. > >> >> But this does not compile. >> Error message: No instance for (Fractional Integer) >> arising from use of `/' at fact1.hs:18:15-28 >> Possible fix: add an instance declaration for (Fractional Integer) >> In the first argument of `print', namely `(time1 / 1.0e12)' >> >> I thought this should work because e.g. 12 / 7 evaluates to >> 1.7142857142857142 in ghci. > > That is because numeric *literals* are polymorphic, as they are parsed as e.g. > "fromInteger 12" if it's an integer literal or "fromRational 3.24" if it's a > non-integer literal. > >> I understand this is some problem with types, but surely it is fixed >> not by adding any instance declarations but perhaps by using some >> Prelude or Numeric function. But which one? >> I tried everything I could find in the documentation: showFloat, >> adding ::Float everywhere, adding fromIntegral, etc.etc. - nothing >> works. All the books and the tutorials I looked at seem to discuss at >> length such nice things as Fibonacci numbers and recursive factorial >> functions rather than a practical problem like this. > > When you are looking for a function, it's a good idea to ask hoogle > (http://haskell.org/hoogle/) for a function of appropriate type. Asking for a > function Integer -> Double, the abovementioned are results 1 and 3. >> >> help will be much appreciated! >> >> Sergei > > HTH, > Daniel > > From alan.cameron at iname.com Sat Jan 10 15:36:14 2009 From: alan.cameron at iname.com (Alan Cameron) Date: Sat Jan 10 15:27:32 2009 Subject: [Haskell-beginners] First request for references Message-ID: Hi, I stumbled across Haskell while researching 'functional programming'. I have done some initial reading and have the following questions: 1. Are there any references to real-world applications using this language? I ask because most of the articles I have found seem to be of an extreme academic nature. I want to be sure that my time will not be wasted delving deeper. 2. Are there any tutorials with full code included which I can use on the HUGS system I have installed? I have found a few "A Gentle Introduction to Haskell 98" which assumes far too much previous knowledge to be immediately useful to me. Thanks for any replies. Alan Cameron From tom.davie at gmail.com Sat Jan 10 15:47:37 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Sat Jan 10 15:39:17 2009 Subject: [Haskell-beginners] First request for references In-Reply-To: References: Message-ID: <15B50D09-439B-4C8E-B617-72090EA05D81@gmail.com> On 10 Jan 2009, at 21:36, Alan Cameron wrote: > Hi, > > I stumbled across Haskell while researching 'functional programming'. > I have done some initial reading and have the following questions: > > 1. Are there any references to real-world applications using this > language? > > I ask because most of the articles I have found seem to be of an > extreme > academic nature. I want to be sure that my time will not be wasted > delving > deeper. Here's a few real world apps written in Haskell: darcs Frag XMonad pugs (perl 6 interpretter) ghc and many more If you want to learn about writing real world programs, try the new book ? Real World Haskell. > 2. Are there any tutorials with full code included which I can use > on the > HUGS system I have installed? > > I have found a few "A Gentle Introduction to Haskell 98" which > assumes far > too much previous knowledge to be immediately useful to me. The learning haskell page on the wiki has a *lot* of references to lots of different tutorials and books. Bob From byorgey at seas.upenn.edu Sat Jan 10 15:51:01 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sat Jan 10 15:42:26 2009 Subject: [Haskell-beginners] First request for references In-Reply-To: References: Message-ID: <20090110205100.GA4195@seas.upenn.edu> On Sat, Jan 10, 2009 at 08:36:14PM -0000, Alan Cameron wrote: > Hi, > > I stumbled across Haskell while researching 'functional programming'. > I have done some initial reading and have the following questions: > > 1. Are there any references to real-world applications using this language? > > I ask because most of the articles I have found seem to be of an extreme > academic nature. I want to be sure that my time will not be wasted delving > deeper. > > 2. Are there any tutorials with full code included which I can use on the > HUGS system I have installed? > > I have found a few "A Gentle Introduction to Haskell 98" which assumes far > too much previous knowledge to be immediately useful to me. > > Thanks for any replies. > > Alan Cameron Hi Alan, welcome! You should check out 'Real World Haskell', recently published by O'Reilly. It sounds like exactly what you are looking for. You can read it for free online: http://www.realworldhaskell.org/blog/ and buy a dead tree copy if you like it. Feel free to direct more questions towards this list, or come ask questions on IRC, in the #haskell channel on irc.freenode.net. -Brent From schwidom at gmx.net Sun Jan 11 05:27:14 2009 From: schwidom at gmx.net (Frank Schwidom) Date: Sun Jan 11 04:19:02 2009 Subject: [Haskell-beginners] typeOf raises Error Message-ID: <20090111102713.GA4561@BigBox> Hi, if im calling (on the console) "typeOf 1" after importing Data.Typeable, i will gain "Integer", as i expected, but if i do so in code which is to compile, then there raises an error ------------ import Data.Typeable main= print (typeOf 1) ------------ $ ghc -c DT.hs $ ghc -c DT.hs DT.hs:4:15: Ambiguous type variable `t' in the constraints: `Num t' arising from the literal `1' at DT.hs:4:15 `Typeable t' arising from a use of `typeOf' at DT.hs:4:8-15 Probable fix: add a type signature that fixes these type variable(s) what can i do, to solve this problem? Regards From allbery at ece.cmu.edu Sun Jan 11 05:21:24 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sun Jan 11 05:12:46 2009 Subject: [Haskell-beginners] typeOf raises Error In-Reply-To: <20090111102713.GA4561@BigBox> References: <20090111102713.GA4561@BigBox> Message-ID: <3A22EA38-CB23-4009-817D-534CC878DCC1@ece.cmu.edu> On 2009 Jan 11, at 5:27, Frank Schwidom wrote: > "Integer", as i expected, but if i do so in code which is > to compile, then there raises an error Yes. Numeric literals like 5 are actually read as (fromIntegral 5); then ghci applies defaulting to reduce it to Integer. When compiled, you must resolve the polymorphism yourself. -- 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 From byorgey at seas.upenn.edu Sun Jan 11 11:22:28 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Jan 11 11:13:48 2009 Subject: [Haskell-beginners] typeOf raises Error In-Reply-To: <20090111102713.GA4561@BigBox> References: <20090111102713.GA4561@BigBox> Message-ID: <20090111162228.GA12746@seas.upenn.edu> As Brandon explained, since 1 is polymorphic, and print is polymorphic in its argument, the compiler doesn't know which type to choose. You could fix it, for example, like this: > ------------ > import Data.Typeable > > main= > print (typeOf (1 :: Integer)) > ------------ You might protest, what is the point of using typeOf if you have to actually put in the type annotation anyway? Well, this is a rather contrived example; usually in a real program GHC would be able to infer the type and an annotation would be unnecessary. -Brent From byorgey at seas.upenn.edu Sun Jan 11 11:26:46 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Jan 11 11:18:11 2009 Subject: [Haskell-beginners] untilM and scanM In-Reply-To: <1231161371.5829.74.camel@arjuna> References: <1231161371.5829.74.camel@arjuna> Message-ID: <20090111162646.GB12746@seas.upenn.edu> On Mon, Jan 05, 2009 at 02:16:11PM +0100, Jan Snajder wrote: > Hi, > > is there a reason why there is no monadic version of "until" in the > Haskell libraries? It would be defined as follows: > > untilM :: (Monad m) => (a -> Bool) -> (a -> m a) -> a -> m a > untilM p f x | p x = return x > | otherwise = f x >>= untilM p f > > The same applies to scanM, also not part of the libraries: > > scanM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m [a] > scanM f q [] = return [q] > scanM f q (x:xs) = > do q2 <- f q x > qs <- scanM f q2 xs > return (q:qs) > > I often find myself in need for these. To me these seem idiomatic enough > to be included in the library. But since they is not, I guess there must > be another, more idiomatic way to do this. There's no particular reason these aren't in the standard libraries that I know of. I've written untilM myself once or twice. Perhaps there are multiple slightly different ways to implement them and no one can agree; or perhaps no one has ever proposed adding them. But there's no more idiomatic way to do this that I know of. -Brent From shaolintl at gmail.com Sun Jan 11 14:47:44 2009 From: shaolintl at gmail.com (Tomer Libal) Date: Sun Jan 11 14:39:03 2009 Subject: [Haskell-beginners] Referring to several constructors at once Message-ID: Hello, I am trying to define a logical calculus using one data type for the rules. There are three types of rules and each has 0,1 or 2 assumptions (rule, rule1 and rule2 below). I have defined all the rules as different constructors so the difference between the types according to 0,1 or 2 assumptions is very weak. I would still like to be able to group the rules in types according to the number of assumptions in order to use pattern matching. Is there a simple way to do that or another way I should implement the data type such that I can refer to the rules both according to their number of assumptions and according to their type? 27 data Rule = Axiom {lowseq :: Sequent} 28 | WeakeningL {rule :: Rule, lowseq :: Sequent, foccur :: FormulaOccur} 29 | WeakeningR {rule :: Rule, lowseq :: Sequent, foccur :: FormulaOccur} 30 | ContractionL {rule :: Rule, lowseq :: Sequent, foccur :: FormulaOccur} 31 | ContractionR {rule :: Rule, lowseq :: Sequent, foccur :: FormulaOccur} 32 | PermutationL {rule :: Rule, lowseq :: Sequent} 33 | PermutationR {rule :: Rule, lowseq :: Sequent} 34 | Mix {rule1 :: Rule, rule2 :: Rule, lowseq :: Sequent, foccur :: FormulaOccur} 35 | NotL {rule :: Rule, lowseq :: Sequent, foccur :: FormulaOccur} 36 | NotR {rule :: Rule, lowseq :: Sequent, foccur :: FormulaOccur} 37 | AndL {rule1 :: Rule, rule2 :: Rule, lowseq :: Sequent, foccur :: FormulaOccur} 38 | AndR {rule1 :: Rule, rule2 :: Rule, lowseq :: Sequent, foccur :: FormulaOccur} 39 deriving (Eq, Show) Thanks, Tomer -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090111/7bee0003/attachment.htm From shaolintl at gmail.com Mon Jan 12 04:06:05 2009 From: shaolintl at gmail.com (Tomer Libal) Date: Mon Jan 12 03:57:23 2009 Subject: [Haskell-beginners] Referring to several constructors at once In-Reply-To: <11f192740901112015w714d67b2hf6802484b19761bc@mail.gmail.com> References: <11f192740901112015w714d67b2hf6802484b19761bc@mail.gmail.com> Message-ID: Thanks, I think this is just what I looked for.. I solved it at the end by having a function to return the type and a list of rules for any rule, but certainly your solution looks much better. 2009/1/12 David Morse > One beginner to another, what about just breaking down and using multiple > data declarations, then packing the rules into the outer data type and the > misc. parameters into the inner data type?: > > data RuleBox = Rule0 RuleZero | Rule1 RuleOne Rule | Rule2 RuleTwo Rule > Rule > data RuleZero = Axiom Sequent > data RuleOne = WeakeningL Sequent FormulaOccur | WeakeningR Sequent > FormulaOccur | ContractionL ... | Contraction R ... | PermutationL ... | > PermutationR ... | NotL ... | NotR ... > data RuleTwo = Mix Sequent FormulaOccur | AndL ... | AndR ... > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090112/82b4d049/attachment.htm From dcmorse at gmail.com Sun Jan 11 23:15:04 2009 From: dcmorse at gmail.com (David Morse) Date: Mon Jan 12 22:11:40 2009 Subject: [Haskell-beginners] Referring to several constructors at once In-Reply-To: References: Message-ID: <11f192740901112015w714d67b2hf6802484b19761bc@mail.gmail.com> One beginner to another, what about just breaking down and using multiple data declarations, then packing the rules into the outer data type and the misc. parameters into the inner data type?: data RuleBox = Rule0 RuleZero | Rule1 RuleOne Rule | Rule2 RuleTwo Rule Rule data RuleZero = Axiom Sequent data RuleOne = WeakeningL Sequent FormulaOccur | WeakeningR Sequent FormulaOccur | ContractionL ... | Contraction R ... | PermutationL ... | PermutationR ... | NotL ... | NotR ... data RuleTwo = Mix Sequent FormulaOccur | AndL ... | AndR ... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090111/9ddabd12/attachment.htm From alan.cameron at iname.com Sat Jan 10 15:03:45 2009 From: alan.cameron at iname.com (Alan Cameron) Date: Mon Jan 12 22:15:01 2009 Subject: [Haskell-beginners] First request for references Message-ID: <20D490290EC543BE802976DDBE0B3CEB@ALANXPS> Hi, I stumbled across Haskell while researching 'functional programming'. I have done some initial reading and have the following questions: 1. Are there any references to real-world applications using this language? I ask because most of the articles I have found seem to be of an extreme academic nature. I want to be sure that my time will not be wasted delving deeper. 2. Are there any tutorials with full code included which I can use on the HUGS system I have installed? I have found a few "A Gentle Introduction to Haskell 98" which assumes far too much previous knowledge to be immediately useful to me. Thanks for any replies. Alan Cameron From wagner.andrew at gmail.com Mon Jan 12 22:31:29 2009 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Mon Jan 12 22:22:43 2009 Subject: [Haskell-beginners] First request for references In-Reply-To: <20D490290EC543BE802976DDBE0B3CEB@ALANXPS> References: <20D490290EC543BE802976DDBE0B3CEB@ALANXPS> Message-ID: Perhaps this book would be of interest to you: http://book.realworldhaskell.org/read/ They walk through lots of real-world examples. On Sat, Jan 10, 2009 at 3:03 PM, Alan Cameron wrote: > Hi, > > I stumbled across Haskell while researching 'functional programming'. > I have done some initial reading and have the following questions: > > 1. Are there any references to real-world applications using this language? > > I ask because most of the articles I have found seem to be of an extreme > academic nature. I want to be sure that my time will not be wasted delving > deeper. > > 2. Are there any tutorials with full code included which I can use on the > HUGS system I have installed? > > I have found a few "A Gentle Introduction to Haskell 98" which assumes far > too much previous knowledge to be immediately useful to me. > > Thanks for any replies. > > Alan Cameron > > _______________________________________________ > 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/20090112/9d5b6e93/attachment-0001.htm From konrad at tylerc.org Mon Jan 12 22:42:55 2009 From: konrad at tylerc.org (Conrad Meyer) Date: Mon Jan 12 22:34:25 2009 Subject: [Haskell-beginners] First request for references In-Reply-To: <20D490290EC543BE802976DDBE0B3CEB@ALANXPS> References: <20D490290EC543BE802976DDBE0B3CEB@ALANXPS> Message-ID: <200901121942.55880.konrad@tylerc.org> On Saturday 10 January 2009 12:03:45 pm Alan Cameron wrote: > Hi, > > I stumbled across Haskell while researching 'functional programming'. > I have done some initial reading and have the following questions: > > 1. Are there any references to real-world applications using this language? > > I ask because most of the articles I have found seem to be of an extreme > academic nature. I want to be sure that my time will not be wasted delving > deeper. > > 2. Are there any tutorials with full code included which I can use on the > HUGS system I have installed? > > I have found a few "A Gentle Introduction to Haskell 98" which assumes far > too much previous knowledge to be immediately useful to me. > > Thanks for any replies. > > Alan Cameron You might want to use GHC instead of HUGS, as it tends to be more feature-complete. For a tutorial to start with, how about "Yet Another Haskell Tutorial"? Regards, -- Conrad Meyer From DekuDekuplex at Yahoo.com Tue Jan 13 01:41:37 2009 From: DekuDekuplex at Yahoo.com (Benjamin L.Russell) Date: Tue Jan 13 01:33:03 2009 Subject: [Haskell-beginners] Re: First request for references References: <20D490290EC543BE802976DDBE0B3CEB@ALANXPS> <200901121942.55880.konrad@tylerc.org> Message-ID: On Mon, 12 Jan 2009 19:42:55 -0800, Conrad Meyer wrote: >On Saturday 10 January 2009 12:03:45 pm Alan Cameron wrote: >> Hi, >> >> I stumbled across Haskell while researching 'functional programming'. >> I have done some initial reading and have the following questions: >> >> 1. Are there any references to real-world applications using this language? >> >> I ask because most of the articles I have found seem to be of an extreme >> academic nature. I want to be sure that my time will not be wasted delving >> deeper. According to the Wikipedia entry for "Software transactional memory," in the "Implementations" section (see http://en.wikipedia.org/wiki/Software_transactional_memory#Implementations), as previously mentioned by Thomas Davie as well in this thread, "STM for Perl 6 has been implemented in Pugs via the Glasgow Haskell Compiler's STM library." >> >> 2. Are there any tutorials with full code included which I can use on the >> HUGS system I have installed? >> >> I have found a few "A Gentle Introduction to Haskell 98" which assumes far >> too much previous knowledge to be immediately useful to me. >> >> Thanks for any replies. >> >> Alan Cameron > >You might want to use GHC instead of HUGS, as it tends to be more >feature-complete. For a tutorial to start with, how about "Yet Another >Haskell Tutorial"? You may also wish to read the book _Programming in Haskell,_ by Graham Hutton (see http://www.cs.nott.ac.uk/~gmh/book.html). This publication has often been praised as being relatively concise and easy to follow. There is even a relevant book review by Duncan Coutts at http://www.cs.nott.ac.uk/~gmh/book-review.pdf. -- Benjamin L. Russell -- Benjamin L. Russell / DekuDekuplex at Yahoo dot com http://dekudekuplex.wordpress.com/ Translator/Interpreter / Mobile: +011 81 80-3603-6725 "Furuike ya, kawazu tobikomu mizu no oto." -- Matsuo Basho^ From RafaelGCPP.Linux at gmail.com Tue Jan 13 09:56:55 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Tue Jan 13 09:48:17 2009 Subject: [Haskell-beginners] The problem with Monads... Message-ID: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> Last night I was thinking on what makes monads so hard to take, and came to a conclusion: the lack of a guided tour on the implemented monads. Let's take the Writer monad documentation: all it says is: Inspired by the paper "Functional Programming with Overloading and Higher-Order Polymorphism", Mark P Jones (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html) Advanced School of Functional Programming, 1995. SO WHAT? The best approach is the Part II of the "All About Monads" tutorial. There you have the almost ideal approach, except that the examples are just thrown there, with no step-by-step explanation. Of course one could copy, paste and run it, but this gives pretty much a "is it right?' feeling. Questions like "if a Reader is an application, why don't use a regular function instead?" or "what bind means for a State monad?". I will try to work on a "Part II" extended version on my vacations... maybe a WikiMonad... or MonadPedia... :-) After all, it is my duty as a haskell noob to write another monad tutorial! :D Cheers! -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090113/ea8edc07/attachment.htm From flippa at flippac.org Tue Jan 13 11:08:29 2009 From: flippa at flippac.org (Philippa Cowderoy) Date: Tue Jan 13 10:59:50 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] The problem with Monads... In-Reply-To: <1231861860.17950.1.camel@jonathans-macbook> References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> Message-ID: <1231862909.31768.4.camel@flippa-eee> On Tue, 2009-01-13 at 07:51 -0800, Jonathan Cast wrote: > On Tue, 2009-01-13 at 12:56 -0200, Rafael Gustavo da Cunha Pereira Pinto > wrote: > > > > Last night I was thinking on what makes monads so hard to take, and > > came to a conclusion: the lack of a guided tour on the implemented > > monads. > > ... > > > Inspired by the paper "Functional Programming with Overloading and > > Higher-Order Polymorphism", > > Mark P Jones > > (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html) > > Advanced School of Functional Programming, 1995. > > > > SO WHAT? > > So have you read Jones' paper? Or do you have a *concrete* explanation > of how it differs from your desired `guided tour'? > We really shouldn't be expecting people to read papers as documentation for standard libraries these days, however good they are. Like it or not, most people find papers intimidating and the file formats are non-standard for documentation (I can't be the only one who hates most PDF docs, and most windows users wouldn't know where to start finding a postscript viewer!). Moving some of the info into the docs is a good idea. Doubly so as the community's common pool of ideas has often moved on since the original paper and much more accessible documentation can now be written. On another note, perhaps there should be a note up somewhere asking people not to cross-post between -beginners and -cafe? People on -cafe don't realising they're responding to a beginner request, losing much of the point of having -beginners. -- Philippa Cowderoy From RafaelGCPP.Linux at gmail.com Tue Jan 13 11:09:01 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Tue Jan 13 11:00:24 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] The problem with Monads... In-Reply-To: <1231861860.17950.1.camel@jonathans-macbook> References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> Message-ID: <351ff25e0901130809x22f5131dx60fede4bcf38b779@mail.gmail.com> Yes, I've read it twice, and it is a nice explanation that "yes, the reader monad is an application and is a monad". How do I use it? Why not the function itself? How would the plumbing work in a real world example? BTW, the article is really great as an brief introduction to monad transformers. For the whole concept of monads, my all time favorite is "The Haskell Programmer's Guide to the IO Monad" by Stefan Klinger. Chapters 14 to 19 of "Real World Haskell" also have a good introduction on the usage of the monads, but it lacks other monads, like the RWS or the Continuation... See, that is my point. The mathematical concept of monads is very palatable. The idea that monads are either patterns or structures to hide computations in sequence is also very easy to see. But how do we use them? Why should I use a Writer monad when I can use a (a,w) tuple? On Tue, Jan 13, 2009 at 13:51, Jonathan Cast wrote: > On Tue, 2009-01-13 at 12:56 -0200, Rafael Gustavo da Cunha Pereira Pinto > wrote: > > > > Last night I was thinking on what makes monads so hard to take, and > > came to a conclusion: the lack of a guided tour on the implemented > > monads. > > ... > > > Inspired by the paper "Functional Programming with Overloading and > > Higher-Order Polymorphism", > > Mark P Jones > > (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html > ) > > Advanced School of Functional Programming, 1995. > > > > SO WHAT? > > So have you read Jones' paper? Or do you have a *concrete* explanation > of how it differs from your desired `guided tour'? > > jcc > > > -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090113/3d4e09d1/attachment.htm From es at ertes.de Tue Jan 13 11:07:50 2009 From: es at ertes.de (Ertugrul Soeylemez) Date: Tue Jan 13 11:01:15 2009 Subject: [Haskell-beginners] Re: The problem with Monads... References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> Message-ID: <20090113170750.0b837f8a@tritium.xx> Jonathan Cast wrote: > On Tue, 2009-01-13 at 12:56 -0200, Rafael Gustavo da Cunha Pereira Pinto > wrote: > > > Inspired by the paper "Functional Programming with Overloading and > > Higher-Order Polymorphism", > > Mark P Jones > > (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html) > > Advanced School of Functional Programming, 1995. > > > > SO WHAT? > > So have you read Jones' paper? Or do you have a *concrete* > explanation of how it differs from your desired `guided tour'? I agree with Rafael here. The standard library documentation is insufficient. Pointing to nothing else than a paper is about the same as "RTFM", especially being "inspired" by a paper, there is really almost no information in the documentation. I wouldn't expect from an average programmer to read a whole paper to understand an everyday-use monad. Especially for newcomers to the purely functional world, even reading the introduction of a paper may well take an hour, which can be tiring and frustrating. There should be some basic information about the monad at least at the end of the documentation, as well as some well-thought usage examples. Greets, Ertugrul. -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From RafaelGCPP.Linux at gmail.com Tue Jan 13 13:35:57 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Tue Jan 13 13:28:04 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] The problem with Monads... In-Reply-To: <1231867639.3917.9.camel@derek-laptop> References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> <16442B752A06A74AB4D9F9A5FF076E4B4DCAE8@ELON17P32001A.csfb.cs-group.com> <1231867639.3917.9.camel@derek-laptop> Message-ID: <351ff25e0901131035r16bdd19did9cce96e70d4352c@mail.gmail.com> I didn't knew Wadler's papers (I save all papers I read into a external USB HD, so I can read them later!), and at a first glance it is really good. Then again, instead of creating another "monad tutorial", what about a Haskell monads reference guide, and some worked examples? Some of this work could even be attached to the library documentation. Regards Rafael On Tue, Jan 13, 2009 at 15:27, Derek Elkins wrote: > On Tue, 2009-01-13 at 16:22 +0000, Sittampalam, Ganesh wrote: > > Jonathan Cast wrote: > > > On Tue, 2009-01-13 at 12:56 -0200, Rafael Gustavo da Cunha Pereira > > > Pinto wrote: > > >> > > >> Inspired by the paper "Functional Programming with Overloading and > > >> Higher-Order Polymorphism", Mark P Jones > > >> (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html > ) > > >> Advanced School of Functional Programming, 1995. > > >> > > >> SO WHAT? > > > > > > So have you read Jones' paper? Or do you have a *concrete* > > > explanation of how it differs from your desired `guided tour'? > > > > To give a specific example, a few weeks ago I wanted an explanation of > > the 'pass' function and couldn't find it in that paper. > > > > Ganesh > > Several years ago I documented all the (basic) monads in the mtl on the > (old) wiki. > > http://web.archive.org/web/20030927210146/haskell.org/hawiki/MonadTemplateLibrary > In particular, > http://web.archive.org/web/20030907203223/haskell.org/hawiki/MonadWriter > > > To respond to the essential point of Rafael's initial claim, Wadler's > papers "The Essence of Functional Programming" and/or "Monads for > Functional Programming" have exactly what he wants. These are the > papers that I recommend to anyone who is learning about monads. > http://homepages.inf.ed.ac.uk/wadler/topics/monads.html > > Please, we do not need the 101st monad tutorial when there was an > adequate one made almost two decades ago. While I'm not saying that > this is the case here, I suspect that many people don't read those > papers because 1) they haven't heard of them and 2) they are "papers" > and thus couldn't possibly be readable and understandable (which also > partially causes (1) as people just don't think to look for papers at > all.) > > -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090113/d07b0868/attachment-0001.htm From hjgtuyl at chello.nl Tue Jan 13 16:57:55 2009 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Tue Jan 13 16:49:19 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] The problem with Monads... In-Reply-To: <351ff25e0901131035r16bdd19did9cce96e70d4352c@mail.gmail.com> References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> <16442B752A06A74AB4D9F9A5FF076E4B4DCAE8@ELON17P32001A.csfb.cs-group.com> <1231867639.3917.9.camel@derek-laptop> <351ff25e0901131035r16bdd19did9cce96e70d4352c@mail.gmail.com> Message-ID: On Tue, 13 Jan 2009 19:35:57 +0100, Rafael Gustavo da Cunha Pereira Pinto wrote: > I didn't knew Wadler's papers (I save all papers I read into a external > USB > HD, so I can read them later!), and at a first glance it is really good. > > > Then again, instead of creating another "monad tutorial", what about a > Haskell monads reference guide, and some worked examples? > > Some of this work could even be attached to the library documentation. > > Regards > > Rafael > I have written a reference manual for the basic Haskell monad functions, "A Tour of the Haskell Monad functions". It contains a lot of examples. You can find it at: http://members.chello.nl/hjgtuyl/tourdemonad.html As far as I know, there is no reference guide for advanced monads, like the Reader, Writer and State monads. -- Regards, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- From jonathanccast at fastmail.fm Tue Jan 13 10:51:00 2009 From: jonathanccast at fastmail.fm (Jonathan Cast) Date: Tue Jan 13 23:39:13 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] The problem with Monads... In-Reply-To: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> Message-ID: <1231861860.17950.1.camel@jonathans-macbook> On Tue, 2009-01-13 at 12:56 -0200, Rafael Gustavo da Cunha Pereira Pinto wrote: > > Last night I was thinking on what makes monads so hard to take, and > came to a conclusion: the lack of a guided tour on the implemented > monads. ... > Inspired by the paper "Functional Programming with Overloading and > Higher-Order Polymorphism", > Mark P Jones > (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html) > Advanced School of Functional Programming, 1995. > > SO WHAT? So have you read Jones' paper? Or do you have a *concrete* explanation of how it differs from your desired `guided tour'? jcc From ganesh.sittampalam at credit-suisse.com Tue Jan 13 11:22:24 2009 From: ganesh.sittampalam at credit-suisse.com (Sittampalam, Ganesh) Date: Tue Jan 13 23:39:46 2009 Subject: [Haskell-beginners] RE: [Haskell-cafe] The problem with Monads... In-Reply-To: <1231861860.17950.1.camel@jonathans-macbook> References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> Message-ID: <16442B752A06A74AB4D9F9A5FF076E4B4DCAE8@ELON17P32001A.csfb.cs-group.com> Jonathan Cast wrote: > On Tue, 2009-01-13 at 12:56 -0200, Rafael Gustavo da Cunha Pereira > Pinto wrote: >> >> Inspired by the paper "Functional Programming with Overloading and >> Higher-Order Polymorphism", Mark P Jones >> (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html) >> Advanced School of Functional Programming, 1995. >> >> SO WHAT? > > So have you read Jones' paper? Or do you have a *concrete* > explanation of how it differs from your desired `guided tour'? To give a specific example, a few weeks ago I wanted an explanation of the 'pass' function and couldn't find it in that paper. Ganesh ============================================================================== Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html ============================================================================== From derek.a.elkins at gmail.com Tue Jan 13 12:27:19 2009 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Tue Jan 13 23:40:04 2009 Subject: [Haskell-beginners] RE: [Haskell-cafe] The problem with Monads... In-Reply-To: <16442B752A06A74AB4D9F9A5FF076E4B4DCAE8@ELON17P32001A.csfb.cs-group.com> References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> <16442B752A06A74AB4D9F9A5FF076E4B4DCAE8@ELON17P32001A.csfb.cs-group.com> Message-ID: <1231867639.3917.9.camel@derek-laptop> On Tue, 2009-01-13 at 16:22 +0000, Sittampalam, Ganesh wrote: > Jonathan Cast wrote: > > On Tue, 2009-01-13 at 12:56 -0200, Rafael Gustavo da Cunha Pereira > > Pinto wrote: > >> > >> Inspired by the paper "Functional Programming with Overloading and > >> Higher-Order Polymorphism", Mark P Jones > >> (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html) > >> Advanced School of Functional Programming, 1995. > >> > >> SO WHAT? > > > > So have you read Jones' paper? Or do you have a *concrete* > > explanation of how it differs from your desired `guided tour'? > > To give a specific example, a few weeks ago I wanted an explanation of > the 'pass' function and couldn't find it in that paper. > > Ganesh Several years ago I documented all the (basic) monads in the mtl on the (old) wiki. http://web.archive.org/web/20030927210146/haskell.org/hawiki/MonadTemplateLibrary In particular, http://web.archive.org/web/20030907203223/haskell.org/hawiki/MonadWriter To respond to the essential point of Rafael's initial claim, Wadler's papers "The Essence of Functional Programming" and/or "Monads for Functional Programming" have exactly what he wants. These are the papers that I recommend to anyone who is learning about monads. http://homepages.inf.ed.ac.uk/wadler/topics/monads.html Please, we do not need the 101st monad tutorial when there was an adequate one made almost two decades ago. While I'm not saying that this is the case here, I suspect that many people don't read those papers because 1) they haven't heard of them and 2) they are "papers" and thus couldn't possibly be readable and understandable (which also partially causes (1) as people just don't think to look for papers at all.) From benjovi at gmx.net Tue Jan 13 18:07:02 2009 From: benjovi at gmx.net (Benedikt Huber) Date: Tue Jan 13 23:40:19 2009 Subject: [Haskell-beginners] Re: The problem with Monads... In-Reply-To: <351ff25e0901130809x22f5131dx60fede4bcf38b779@mail.gmail.com> References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> <351ff25e0901130809x22f5131dx60fede4bcf38b779@mail.gmail.com> Message-ID: <496D1E96.40500@gmx.net> Rafael Gustavo da Cunha Pereira Pinto schrieb: > Yes, I've read it twice, and it is a nice explanation that "yes, the > reader monad is an application and is a monad". How do I use it? Why not > the function itself? How would the plumbing work in a real world example? Hi Rafael, First of all, I agree that the documentation for mtl should be improved. Especially Control.Monad.RWS and Control.Monad.List really need some more information. The documentation for the Reader and Identity monad are quite detailled though. They seem to be "inspired" by http://www.haskell.org/all_about_monads/, which also has documentation on Writer and Cont. Control.Monad.List is a good example for the lack of documentation: There is a single sentence at the beginning > "The List monad." and then one declaration > newtype ListT m a = ListT { runListT :: m [a] } while the important information is hidden as one of many instance declarations: > Monad m => Functor (ListT m) > Monad m => MonadPlus (ListT m) Btw, the quality of the examples in Control.Monad.Reader is debutable. From Example 1: > -- The Reader monad, which implements this complicated check. > calc_isCountCorrect :: Reader Bindings Bool > calc_isCountCorrect = do > count <- asks (lookupVar "count") > bindings <- ask > return (count == (Map.size bindings)) I think it is wrong (or weird at least) to call the function a 'Reader monad'; the name 'calc_isCountCorrect' is horrible too (because of the calc_ prefix), Finally, implementing > isCountCorrect :: Bindings -> Bool > isCountCorrect bs = (bs Map.! "count") == Map.size bs using the Reader monad will convince everybody _not_ to use it. A suggestion: If license permits it, short versions of the articles on all_about_monads would make a great documentation for mtl (except for RWS and List, which are missing). benedikt > > BTW, the article is really great as an brief introduction to monad > transformers. For the whole concept of monads, my all time favorite is > "The Haskell Programmer's Guide to the IO Monad" by Stefan Klinger. > > Chapters 14 to 19 of "Real World Haskell" also have a good introduction > on the usage of the monads, but it lacks other monads, like the RWS or > the Continuation... > > See, that is my point. The mathematical concept of monads is very > palatable. The idea that monads are either patterns or structures to > hide computations in sequence is also very easy to see. But how do we > use them? > Why should I use a Writer monad when I can use a (a,w) tuple? > > > > On Tue, Jan 13, 2009 at 13:51, Jonathan Cast > wrote: > > On Tue, 2009-01-13 at 12:56 -0200, Rafael Gustavo da Cunha Pereira Pinto > wrote: > > > > Last night I was thinking on what makes monads so hard to take, and > > came to a conclusion: the lack of a guided tour on the implemented > > monads. > > ... > > > Inspired by the paper "Functional Programming with Overloading and > > Higher-Order Polymorphism", > > Mark P Jones > > (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html > ) > > Advanced School of Functional Programming, 1995. > > > > SO WHAT? > > So have you read Jones' paper? Or do you have a *concrete* explanation > of how it differs from your desired `guided tour'? > > jcc > > > > > > -- > Rafael Gustavo da Cunha Pereira Pinto > Electronic Engineer, MSc. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From RafaelGCPP.Linux at gmail.com Wed Jan 14 05:02:20 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Wed Jan 14 04:53:33 2009 Subject: [Haskell-beginners] Re: The problem with Monads... In-Reply-To: <496D1E96.40500@gmx.net> References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> <351ff25e0901130809x22f5131dx60fede4bcf38b779@mail.gmail.com> <496D1E96.40500@gmx.net> Message-ID: <351ff25e0901140202n328c2741j3175e35ff8bbea1b@mail.gmail.com> Wadler's examples are way better than the ones in the documentation. But without his explanations of what he is doing, the examples alone are pretty worthless. I agree that all_about_monads could be a better source for the documentation, at least for completeness. But even there I would consider choosing simpler examples, like Wadler's expression evaluator. On Tue, Jan 13, 2009 at 21:07, Benedikt Huber wrote: > Rafael Gustavo da Cunha Pereira Pinto schrieb: > >> Yes, I've read it twice, and it is a nice explanation that "yes, the >> reader monad is an application and is a monad". How do I use it? Why not the >> function itself? How would the plumbing work in a real world example? >> > Hi Rafael, > > First of all, I agree that the documentation for mtl should be improved. > Especially Control.Monad.RWS and Control.Monad.List really need some more > information. > > The documentation for the Reader and Identity monad are quite detailled > though. They seem to be "inspired" by > http://www.haskell.org/all_about_monads/, which also has documentation on > Writer and Cont. > > Control.Monad.List is a good example for the lack of documentation: > There is a single sentence at the beginning > > "The List monad." > and then one declaration > > newtype ListT m a = ListT { runListT :: m [a] } > while the important information is hidden as one of many instance > declarations: > > Monad m => Functor (ListT m) > > Monad m => MonadPlus (ListT m) > > Btw, the quality of the examples in Control.Monad.Reader is debutable. From > Example 1: > > > -- The Reader monad, which implements this complicated check. > > calc_isCountCorrect :: Reader Bindings Bool > > calc_isCountCorrect = do > > count <- asks (lookupVar "count") > > bindings <- ask > > return (count == (Map.size bindings)) > > I think it is wrong (or weird at least) to call the function a 'Reader > monad'; the name 'calc_isCountCorrect' is horrible too (because of the calc_ > prefix), Finally, implementing > > > isCountCorrect :: Bindings -> Bool > > isCountCorrect bs = (bs Map.! "count") == Map.size bs > > using the Reader monad will convince everybody _not_ to use it. > > A suggestion: If license permits it, short versions of the articles on > all_about_monads would make a great documentation for mtl (except for RWS > and List, which are missing). > > benedikt > > > >> BTW, the article is really great as an brief introduction to monad >> transformers. For the whole concept of monads, my all time favorite is "The >> Haskell Programmer's Guide to the IO Monad" by Stefan Klinger. >> >> Chapters 14 to 19 of "Real World Haskell" also have a good introduction on >> the usage of the monads, but it lacks other monads, like the RWS or the >> Continuation... >> >> See, that is my point. The mathematical concept of monads is very >> palatable. The idea that monads are either patterns or structures to hide >> computations in sequence is also very easy to see. But how do we use them? >> Why should I use a Writer monad when I can use a (a,w) tuple? >> >> >> >> On Tue, Jan 13, 2009 at 13:51, Jonathan Cast > jonathanccast@fastmail.fm>> wrote: >> >> On Tue, 2009-01-13 at 12:56 -0200, Rafael Gustavo da Cunha Pereira >> Pinto >> wrote: >> > >> > Last night I was thinking on what makes monads so hard to take, and >> > came to a conclusion: the lack of a guided tour on the implemented >> > monads. >> >> ... >> >> > Inspired by the paper "Functional Programming with Overloading and >> > Higher-Order Polymorphism", >> > Mark P Jones >> > (http://web.cecs.pdx.edu/~mpj/pubs/springschool.html >> ) >> > Advanced School of Functional Programming, 1995. >> > >> > SO WHAT? >> >> So have you read Jones' paper? Or do you have a *concrete* explanation >> of how it differs from your desired `guided tour'? >> >> jcc >> >> >> >> >> >> -- >> Rafael Gustavo da Cunha Pereira Pinto >> Electronic Engineer, MSc. >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Haskell-Cafe mailing list >> Haskell-Cafe@haskell.org >> http://www.haskell.org/mailman/listinfo/haskell-cafe >> > > -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090114/d20383dc/attachment-0001.htm From llp_yyz at hotmail.com Wed Jan 14 14:44:07 2009 From: llp_yyz at hotmail.com (David Schonberger) Date: Wed Jan 14 14:35:18 2009 Subject: [Haskell-beginners] Odd behavior from WinHugs Message-ID: Hi all. I'm attempting exercise 4.6 from Daume's Yet Another Haskell Tutorial: Exercise 4.6 Write a datatype Tuple which can hold one, two, three or four elements, depending on the constructor (that is, there should be four constructors, one for each number of arguments). Also provide functions tuple1 through tuple4 which take a tuple and return Just the value in that position, or Nothing if the number is invalid (i.e., you ask for the tuple4 on a tuple holding only two elements) For starters, I began with the following, stored in a file called MyTuple.hs: data myTuple a b c d = my4Tuple a b c d | my3Tuple a b c | my2Tuple a b | my1Tuple a deriving (Show) When I load this into WinHugs I get the following error: file:.\MyTuple.hs:1 - Syntax error in data declaration (unexpected symbol "a") However I get the same error if I reduce it to a single data constructor, in an effort to create just a quadruple: data myTuple a b c d = my4Tuple a b c d What is even more odd is that I have the following code in a file called Pair.hs: {-data Pair a b = Pair a b deriving (Show)pairFst (Pair x y) = xpairSnd (Pair x y) = y data Quadruple a b c d = Quadruple a a b b deriving (Show)fstPairofQuad (Quadruple a b c d) = [a,b]sndPairofQuad (Quadruple a b c d) = [c,d]-} data Quad a b c d = QuadFour a b c d | QuadThree a b c | QuadTwo a b | QuadOne a deriving (Show) {-fstPairofQuad (QuadFour a b c d) = (a,b)mdlPairofQuad (QuadFour a b c d) = (b,c)sndPairofQuad (QuadFour a b c d) = (c,d)fstLstofQuad (QuadFour a b c d) = (a,d)-} Whether I just keep Quad visible in the file or I take away both pairs of comment braces, when I load that file into WinHugs it works fine, and I have no trouble constructing a Quad or using any of the QuadFour utility fcns (which, admittedly are not what is called for in the exercise... but that's probably besides the point). What in the world might be causing the error in the MyTuple file? Thanks, David -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090114/dd594b02/attachment.htm From jgbailey at gmail.com Wed Jan 14 14:46:23 2009 From: jgbailey at gmail.com (Justin Bailey) Date: Wed Jan 14 14:37:32 2009 Subject: [Haskell-beginners] Odd behavior from WinHugs In-Reply-To: References: Message-ID: You have to capitalize your type names and data constructors: data MyTuple a b c d = My4Tuple a b c d | My3Tuple a b c | My2Tuple a b | My1Tuple a deriving (Show) On Wed, Jan 14, 2009 at 11:44 AM, David Schonberger wrote: > > Hi all. I'm attempting exercise 4.6 from Daume's Yet Another Haskell > Tutorial: > > > Exercise 4.6 > > Write a datatype Tuple which can hold one, two, three or four elements, > > depending on the constructor (that is, there should be four constructors, > one for each > > number of arguments). Also provide functions > > tuple1 through tuple4 which take a > > tuple and return > > Just the value in that position, or Nothing if the number is invalid (i.e., > you ask for the tuple4 on a tuple holding only two elements) > > For starters, I began with the following, stored in a file called > MyTuple.hs: > > data myTuple a b c d = my4Tuple a b c d > | my3Tuple a b c > | my2Tuple a b > | my1Tuple a > deriving (Show) > > When I load this into WinHugs I get the following error: > > file:.\MyTuple.hs:1 - Syntax error in data declaration (unexpected symbol > "a") > > However I get the same error if I reduce it to a single data constructor, in > an effort to create just a quadruple: > > data myTuple a b c d = my4Tuple a b c d > > What is even more odd is that I have the following code in a file called > Pair.hs: > > {-data Pair a b = Pair a b > deriving (Show) > pairFst (Pair x y) = x > pairSnd (Pair x y) = y > data Quadruple a b c d = Quadruple a a b b > deriving (Show) > fstPairofQuad (Quadruple a b c d) = [a,b] > sndPairofQuad (Quadruple a b c d) = [c,d] > -} > > data Quad a b c d = QuadFour a b c d | QuadThree a b c | QuadTwo a b | > QuadOne a > deriving (Show) > > {- > fstPairofQuad (QuadFour a b c d) = (a,b) > mdlPairofQuad (QuadFour a b c d) = (b,c) > sndPairofQuad (QuadFour a b c d) = (c,d) > fstLstofQuad (QuadFour a b c d) = (a,d)-} > > Whether I just keep Quad visible in the file or I take away both pairs of > comment braces, when I load that file into WinHugs it works fine, > and I have no trouble constructing a Quad or using any of the QuadFour > utility fcns (which, admittedly are not what is called for in the > exercise... > but that's probably besides the point). > > What in the world might be causing the error in the MyTuple file? > > Thanks, > David > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > From konrad at tylerc.org Wed Jan 14 15:23:55 2009 From: konrad at tylerc.org (Conrad Meyer) Date: Wed Jan 14 15:16:05 2009 Subject: [Haskell-beginners] Odd behavior from WinHugs In-Reply-To: References: Message-ID: <200901141223.55751.konrad@tylerc.org> On Wednesday 14 January 2009 11:46:23 am Justin Bailey wrote: > You have to capitalize your type names and data constructors: > > data MyTuple a b c d = My4Tuple a b c d > > | My3Tuple a b c > | My2Tuple a b > | My1Tuple a > > deriving (Show) Also, I think (but by no means am I sure) that you should cut out 'a b c d' from the left side, i.e.: data MyTuple = My4Tuple a b c d | My3Tuple a b c | My2Tuple a b | My1Tuple a deriving (Show) Someone please tell me if I am wrong :). Regards, -- Conrad Meyer From daniel.is.fischer at web.de Wed Jan 14 16:07:06 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Jan 14 15:55:43 2009 Subject: [Haskell-beginners] Odd behavior from WinHugs In-Reply-To: <200901141223.55751.konrad@tylerc.org> References: <200901141223.55751.konrad@tylerc.org> Message-ID: <200901142207.06678.daniel.is.fischer@web.de> Am Mittwoch, 14. Januar 2009 21:23 schrieb Conrad Meyer: > On Wednesday 14 January 2009 11:46:23 am Justin Bailey wrote: > > You have to capitalize your type names and data constructors: > > > > data MyTuple a b c d = My4Tuple a b c d > > > > | My3Tuple a b c > > | My2Tuple a b > > | My1Tuple a > > > > deriving (Show) > > Also, I think (but by no means am I sure) that you should cut out 'a b c d' > from the left side, i.e.: > > data MyTuple = My4Tuple a b c d > > | My3Tuple a b c > | My2Tuple a b > | My1Tuple a > > deriving (Show) > > Someone please tell me if I am wrong :). The type variables are necessary on the left hand side, otherwise a (My3Tuple x y z) could hold values of completely unknown type and so you couldn't do anything useful with it. If the types of things held weren't specified on the left, what type could firstOfTuple have? > > Regards, From konrad at tylerc.org Wed Jan 14 16:11:14 2009 From: konrad at tylerc.org (Conrad Meyer) Date: Wed Jan 14 16:02:39 2009 Subject: [Haskell-beginners] Odd behavior from WinHugs In-Reply-To: <200901142207.06678.daniel.is.fischer@web.de> References: <200901141223.55751.konrad@tylerc.org> <200901142207.06678.daniel.is.fischer@web.de> Message-ID: <200901141311.14861.konrad@tylerc.org> On Wednesday 14 January 2009 01:07:06 pm Daniel Fischer wrote: > If the types of things held weren't specified on the left, what type could > firstOfTuple have? Polymorphic (i.e. any) type. -- Conrad Meyer From daniel.is.fischer at web.de Wed Jan 14 16:29:11 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Jan 14 16:17:47 2009 Subject: [Haskell-beginners] Odd behavior from WinHugs In-Reply-To: <200901141311.14861.konrad@tylerc.org> References: <200901142207.06678.daniel.is.fischer@web.de> <200901141311.14861.konrad@tylerc.org> Message-ID: <200901142228.27682.daniel.is.fischer@web.de> Am Mittwoch, 14. Januar 2009 22:11 schrieb Conrad Meyer: > On Wednesday 14 January 2009 01:07:06 pm Daniel Fischer wrote: > > If the types of things held weren't specified on the left, what type > > could firstOfTuple have? > > Polymorphic (i.e. any) type. You mean firstOfTuple :: exists a. MyTuple -> a ? As of now, that's an illegal type. From bugfact at gmail.com Wed Jan 14 06:30:11 2009 From: bugfact at gmail.com (Peter Verswyvelen) Date: Wed Jan 14 22:11:54 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] The problem with Monads... In-Reply-To: References: <351ff25e0901130656k530348afj6633048d206d7f74@mail.gmail.com> <1231861860.17950.1.camel@jonathans-macbook> <16442B752A06A74AB4D9F9A5FF076E4B4DCAE8@ELON17P32001A.csfb.cs-group.com> <1231867639.3917.9.camel@derek-laptop> <351ff25e0901131035r16bdd19did9cce96e70d4352c@mail.gmail.com> Message-ID: > > I have written a reference manual for the basic Haskell monad functions, "A > Tour of the Haskell Monad functions". It contains a lot of examples. You can > find it at: > http://members.chello.nl/hjgtuyl/tourdemonad.html Wow! I like these examples. I'm a pragmatist, and although Haskell gave me the most intense joy I ever experienced with programming (and also frustrations ;-), I find it extremely difficult to learn it from research papers. But these small examples are exactly what I need, because my brain will easier recognize a pattern match with the specific examples, than with the abstract explanation (and I was pretty good at abstract algebra, but that's 20 years ago, and I filled these 2 decades with lots and lots of imperative and OO hacking ;-). I wish every function in every module in the documentation had an "examples" link next to the "source" link, or a link to examples on the wiki or something. I guess the smart computer scientists here will tell me that I need to lift my brain to learn to recognize abstract patterns, but I'm afraid this is not something that is given to all of us, certainly not in the short term. But I still want to enjoy Haskell, so keep the short examples coming :) > > As far as I know, there is no reference guide for advanced monads, like the > Reader, Writer and State monads. > > -- > Regards, > Henk-Jan van Tuyl > > > -- > http://functor.bamikanarie.com > http://Van.Tuyl.eu/ > -- > > > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090114/f8e570df/attachment-0001.htm From johanngiwer at web.de Thu Jan 15 17:26:25 2009 From: johanngiwer at web.de (Johann Giwer) Date: Thu Jan 15 17:18:28 2009 Subject: [Haskell-beginners] gtk2hs, inputAdd and forked process Message-ID: <20090115222622.GA24117@zitrone> Some times ago I wrote a frontend for mpg123 using python and gtk2. Now I'm trying to do the same in haskell, but my attempt failed in a very early stage. I like to start a subprocess and read its output via 'inputAdd'. The (simplified) code looks like this: module Main (Main.main) where import System.IO.UTF8 hiding (putStr, putStrLn, print) import qualified Control.Exception as E import System.Glib.MainLoop import System.Environment import System.Posix.Process import System.Posix.IO import System.Posix.Types import Graphics.UI.Gtk main :: IO () main = do name <- getProgName argv <- getArgs case argv of [file] -> play file _ -> putStrLn $ "Usage: " ++ name ++ " MP3 FILE" play :: FilePath -> IO () play file = do initGUI (r0,w0) <- createPipe (r1,w1) <- createPipe pid <- forkProcess $ do closeFd w0 closeFd r1 dupTo r0 stdInput dupTo w1 stdOutput executeFile "mpg123" True ["--output", "alsa", "--remote"] Nothing closeFd w1 closeFd r0 window <- windowNew onDestroy window mainQuit button <- buttonNew set button [ buttonLabel := "Play" ] onClicked button $ do w <- fdToHandle w0 E.handle ( \e -> print e ) $ do hPutStrLn w ( "L " ++ file ) return () set window [ containerChild := button ] widgetShowAll window inputAdd (fromIntegral r1) [ IOIn,IOPri ] priorityHigh ( readData r1 ) mainGUI readData :: Fd -> IO Bool readData h = do E.handle ( \e -> print e >> return True ) $ do (s,_) <- fdRead h 1 putStr s return False When loading the file in ghci, I get half a second of sound and a couple of status message lines. Compiled with ghc, this program gives absolute no output (So threading seams to be the problem?). In a next step, I wrapped every IO action in the main process in a call of 'forkIO' and used MVars for the file name and descriptors, but that doesn't help. Does anybody have experience with 'inputAdd' and forked processes? Thanks in advance -Johann From shaolintl at gmail.com Fri Jan 16 07:35:35 2009 From: shaolintl at gmail.com (Tomer Libal) Date: Fri Jan 16 07:26:39 2009 Subject: [Haskell-beginners] Is complete decoupling and abstraction possible in Haskell? Message-ID: Hi, I must add that although in general Theorem provers are very performance oriented, we are not interested in performance in our prover as it is used mainly for testing different refinements and extensions. Therefore, we consider haskell as well (as c++). Also, is there a big reference project, implemented in Haskell, that exhibits some of the OO concepts like decoupling, modulation and abstraction? I understand functional programming has other core values like ease of programming and easy validation of correctness but is it also suitable for large structured projects worked on by many programmers (using decoupling for example)? I have read the previous thread about Monads with great interest. The abstration ideas contained in Wadler's papers gave me hope that there is a way to do a full decoupling and abstraction in Haskell, but I have no idea how. I am interested in building a completely generic resolution theorem prover that all of its parts can be implemented separately. In fact, we already have this prover programmed in c++ but I would be glad if I can reprogram it in Haskell for further extensions of the different parts. The idea of the resolution prover is to get a set of clauses in clasual logic and to try and refute them by using resolution. Some of the parts that need to be decoupled are: - Refinements which are datastructures that return the pair (or more) of clauses each time that need to be processed. They are chosen according to some heuristic, i.e. smallest clauses, etc. Each Refinement instance should be able to return the next pair to be processed according to its inner state and heuristics. - Resolvers that process two clauses and tries to unify a specific literal in each. The abstraction here deals with each resolver processing in a different way. Some do factorization and some modulation and each one of this processes have several kinds that should be decoupled as well (i.e. modulator that works by a brute force BFS or -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090116/15ad9255/attachment.htm From shaolintl at gmail.com Fri Jan 16 07:36:38 2009 From: shaolintl at gmail.com (Tomer Libal) Date: Fri Jan 16 07:27:45 2009 Subject: [Haskell-beginners] Re: Is complete decoupling and abstraction possible in Haskell? In-Reply-To: References: Message-ID: I am deeply sorry, the message was sent by mistake before I have finished it.. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090116/198c6324/attachment.htm From shaolintl at gmail.com Fri Jan 16 07:52:31 2009 From: shaolintl at gmail.com (Tomer Libal) Date: Fri Jan 16 07:43:36 2009 Subject: [Haskell-beginners] Re: Is complete decoupling and abstraction possible in Haskell? In-Reply-To: References: Message-ID: Hi, I have read the previous thread about Monads with great interest. The abstration ideas contained in Wadler's papers gave me hope that there is a way to do a full decoupling and abstraction in Haskell, but I have no idea how. I am interested in building a completely generic resolution theorem prover that all of its parts can be implemented separately. In fact, we already have this prover programmed in c++ but I would be glad if I can reprogram it in Haskell for further extensions of the different parts. The idea of the resolution prover is to get a set of clauses in clasual logic and to try and refute them by using resolution. Some of the parts that need to be decoupled are: - Refinements which are datastructures that return the pair (or more) of clauses each time that need to be processed. They are chosen according to some heuristic, i.e. smallest clauses, etc. Each Refinement instance should be able to return the next pair to be processed according to its inner state and heuristics. - Resolvers that process two clauses and tries to unify a specific literal in each. The abstraction here deals with each resolver processing in a different way. Some do factorization and some modulation and each one of this processes have several kinds that should be decoupled as well (i.e. modulator that works by a brute force BFS or in a smarter way). - Post processors that are applied to all successfull resolvents and perform manipulation on the Refinements states, like adding new clauses (called also resolvents), forward subsumption, deletion of tautologies, etc.) As an example for abstraction in the Refinement state, we have in the c++ version an interactive refinement that gets as argument another refinement and deals with obtaining commands from the user: - do x steps in automatic mode i.e. execute the inner refinement for x steps. - tries to unifies two clauses on all positions, etc. Also the user interface module should be deoupled as it can be a simple command like or a GUI. My naive approach was to create a class for each abstract part of the prover and the different instances will implement the specific implementations. My main question is if it is feasible to achieve in Haskell and even if it is Feasible, if such decoupling should be attempted in Haskell in the first place or that other languages are more suitable. I guess my main question is if projects prgrammed by several programmers with a complete decoupling between them can be done in Haskell. I must add that although in general Theorem provers are very performance oriented, we are not interested in performance in our prover as it is used mainly for testing different refinements and extensions. Therefore, we consider haskell as well (as c++). Also, is there a big reference project, implemented in Haskell, that exhibits some of the OO concepts like decoupling, modulation and abstraction? I understand functional programming has other core values like ease of programming and easy validation of correctness but is it also suitable for large structured projects worked on by many programmers (using decoupling for example)? to give an example for the main function (many parts are missing): class Refinement a where getClauses :: Maybe (Clause, Clause) loop timeout refinement = let clauses = getClauses refinement timedout = isTimeout t in if timedout then Timedout t else case clauses of Nothing -> Exahusted Just (c1, c2) -> let resolvents = unifyOnAllLiterals c1 c2 -- list of all resolvents in if emptyClauseIsContained resolvents then Success unifier -- unifer is the global unifier -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090116/b90c26fe/attachment.htm From jeedward at yahoo.com Fri Jan 16 08:59:13 2009 From: jeedward at yahoo.com (John Edward) Date: Fri Jan 16 08:50:19 2009 Subject: [Haskell-beginners] MULTICONF-09 final call for papers Message-ID: <90105.78966.qm@web45901.mail.sp1.yahoo.com> MULTICONF-09 final call for papers ? The 2009 Multi Conference in Computer Science, Information Technology and Control systems and Computational Science and Computer Engineering (MULTICONF-09) (website: http://www.PromoteResearch.org) will be held during July 13-16 2009 in Orlando, FL, USA. We invite draft paper submissions. The event consists of the following conferences: ????????? International Conference on Artificial Intelligence and Pattern Recognition (AIPR-09) ????????? International Conference on Automation, Robotics and Control Systems (ARCS-09) ????????? International Conference on Bioinformatics, Computational Biology, Genomics and Chemoinformatics (BCBGC-09) ????????? International Conference on Enterprise Information Systems and Web Technologies (EISWT-09) ????????? International Conference on High Performance Computing, Networking and Communication Systems (HPCNCS-09) ????????? International Conference on Information Security and Privacy (ISP-09) ????????? International Conference on Recent Advances in Information Technology and Applications (RAITA-09) ????????? International Conference on Software Engineering Theory and Practice (SETP-09) ????????? International Conference on Theory and Applications of Computational Science (TACS-09) ????????? International Conference on Theoretical and Mathematical Foundations of Computer Science (TMFCS-09) ? The website http://www.PromoteResearch.org? contains more details. ? Sincerely John Edward Publicity committee ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090116/b49284b4/attachment-0001.htm From adi.mahajan at gmail.com Mon Jan 19 10:04:21 2009 From: adi.mahajan at gmail.com (Aditya Mahajan) Date: Mon Jan 19 11:10:57 2009 Subject: [Haskell-beginners] Printf and bool Message-ID: Hi, I like the printf function from Text.Printf to display results on the terminal. I noticed that there is no format specifier for Bool. Can someone suggest how to create an instance of PrintfArg for Bool? Aditya From byorgey at seas.upenn.edu Mon Jan 19 13:22:00 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Jan 19 13:12:53 2009 Subject: [Haskell-beginners] Printf and bool In-Reply-To: References: Message-ID: <20090119182200.GA15546@seas.upenn.edu> On Mon, Jan 19, 2009 at 10:04:21AM -0500, Aditya Mahajan wrote: > Hi, > > I like the printf function from Text.Printf to display results on the > terminal. I noticed that there is no format specifier for Bool. Can someone > suggest how to create an instance of PrintfArg for Bool? Why not just use something like printf "%s" (show b) where b :: Bool ? -Brent From adi.mahajan at gmail.com Mon Jan 19 14:42:15 2009 From: adi.mahajan at gmail.com (Aditya Mahajan) Date: Mon Jan 19 14:34:12 2009 Subject: [Haskell-beginners] Re: Printf and bool In-Reply-To: <20090119182200.GA15546@seas.upenn.edu> References: <20090119182200.GA15546@seas.upenn.edu> Message-ID: On Mon, 19 Jan 2009, Brent Yorgey wrote: > On Mon, Jan 19, 2009 at 10:04:21AM -0500, Aditya Mahajan wrote: >> Hi, >> >> I like the printf function from Text.Printf to display results on the >> terminal. I noticed that there is no format specifier for Bool. Can someone >> suggest how to create an instance of PrintfArg for Bool? > > Why not just use something like > > printf "%s" (show b) > > where b :: Bool ? Because it breaks type safety. Aditya From RafaelGCPP.Linux at gmail.com Mon Jan 19 20:30:30 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Mon Jan 19 20:21:23 2009 Subject: [Haskell-beginners] System.IO.withFile Message-ID: <351ff25e0901191730h2078eb6emc7787160c8dda05d@mail.gmail.com> Hi folks, I am trying to use the withFile function of System.IO, but it always return an empty string when testing. Could someone explain why: main= do h<-openFile "test.cir" ReadMode c<-hGetContents h print c > runhaskell test1.hs > "* Teste\n\nR1 1 0 10\nC1 1 0 10uF\nI1 1 0 1mA\n\n.DC \n.PRINT\n" works and main= (withFile "test.cir" ReadMode hGetContents) >>= print > runhaskell test1.hs > "" don't? Thanks! -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090119/86c36b61/attachment.htm From aslatter at gmail.com Mon Jan 19 22:44:56 2009 From: aslatter at gmail.com (Antoine Latter) Date: Mon Jan 19 22:35:49 2009 Subject: [Haskell-beginners] System.IO.withFile In-Reply-To: <351ff25e0901191730h2078eb6emc7787160c8dda05d@mail.gmail.com> References: <351ff25e0901191730h2078eb6emc7787160c8dda05d@mail.gmail.com> Message-ID: <694519c50901191944g11d677d6w5b96d8b2213c8d1a@mail.gmail.com> On Mon, Jan 19, 2009 at 7:30 PM, Rafael Gustavo da Cunha Pereira Pinto wrote: > Could someone explain why: > > main= do > h<-openFile "test.cir" ReadMode > c<-hGetContents h > print c > >> runhaskell test1.hs >> "* Teste\n\nR1 1 0 10\nC1 1 0 10uF\nI1 1 0 1mA\n\n.DC \n.PRINT\n" > > works and > > > main= (withFile "test.cir" ReadMode hGetContents) >>= print > >> runhaskell test1.hs >> "" > > don't? 'hGetContents' is a lazy-IO function, which means doesn't really start reading from the handle until another function tries to consume its output. The problem is that 'print' - the consumer - is outside of the 'withFile' argument, and 'withFile' guarantees that the file is closed when it finishes execution. So by the time 'hGetContents' tries to do its thing, the file handle is closed. This snippet: > main = withFile "test.cir" ReadMode $ \h -> hGetContents h >>= print puts the call to 'print' inside the argument to 'withFile', so it should work as expected. -Antoine From RafaelGCPP.Linux at gmail.com Tue Jan 20 07:20:41 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Tue Jan 20 07:11:33 2009 Subject: [Haskell-beginners] System.IO.withFile In-Reply-To: <694519c50901191944g11d677d6w5b96d8b2213c8d1a@mail.gmail.com> References: <351ff25e0901191730h2078eb6emc7787160c8dda05d@mail.gmail.com> <694519c50901191944g11d677d6w5b96d8b2213c8d1a@mail.gmail.com> Message-ID: <351ff25e0901200420r2c3eeb60nbdf32e4086c53147@mail.gmail.com> Thanks Antoine! I was suspecting it should be the lazyness of hGetContents yesterday, before going to sleep. You just confirmed that for me! On Tue, Jan 20, 2009 at 01:44, Antoine Latter wrote: > On Mon, Jan 19, 2009 at 7:30 PM, Rafael Gustavo da Cunha Pereira Pinto > wrote: > > Could someone explain why: > > > > main= do > > h<-openFile "test.cir" ReadMode > > c<-hGetContents h > > print c > > > >> runhaskell test1.hs > >> "* Teste\n\nR1 1 0 10\nC1 1 0 10uF\nI1 1 0 1mA\n\n.DC \n.PRINT\n" > > > > works and > > > > > > main= (withFile "test.cir" ReadMode hGetContents) >>= print > > > >> runhaskell test1.hs > >> "" > > > > don't? > > 'hGetContents' is a lazy-IO function, which means doesn't really start > reading from the handle until another function tries to consume its > output. > > The problem is that 'print' - the consumer - is outside of the > 'withFile' argument, and 'withFile' guarantees that the file is closed > when it finishes execution. > > So by the time 'hGetContents' tries to do its thing, the file handle is > closed. > > This snippet: > > > main = withFile "test.cir" ReadMode $ \h -> hGetContents h >>= print > > puts the call to 'print' inside the argument to 'withFile', so it > should work as expected. > > -Antoine > -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090120/67de0e2e/attachment.htm From kjmcclain at comcast.net Wed Jan 21 17:30:12 2009 From: kjmcclain at comcast.net (Kellen J. McClain) Date: Wed Jan 21 17:21:04 2009 Subject: [Haskell-beginners] Type Operator Message-ID: <1232577012.4387.12.camel@kgateway> I have a quick question. Recall that: class Monad m where (>>=) :: m a -> (a -> m b) -> m b ... and suppose I have a data type Sample: data Sample a b = ... how could I define Sample to be an instance of Monad such that: (>>=) :: Sample a c -> (a -> Sample b c) -> Sample b c ? I would like to use a (\a -> ...)-like operator, but for types. So, something like this: instance Monad (\a -> Sample a c) where (>>=) :: Sample a c -> (a -> Sample b c) -> Sample b c a >>= f = ... but that obviously doesn't work. Alternatively I would like to use a type declaration and partially apply it: type SampleFlip b a = Sample a b instance Monad (SampleFlip c) where (>>=) :: SampleFlip c a -> (a -> SampleFlip c b) -> SampleFlip c b which translates to: (>>=) :: Sample a c -> (a -> Sample b c) -> Sample b c But this doesn't work either, and ghc extensions don't add this functionality. Can I do this in Haskell? From daniel.is.fischer at web.de Wed Jan 21 17:51:26 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Jan 21 17:39:37 2009 Subject: [Haskell-beginners] Type Operator In-Reply-To: <1232577012.4387.12.camel@kgateway> References: <1232577012.4387.12.camel@kgateway> Message-ID: <200901212351.26389.daniel.is.fischer@web.de> Am Mittwoch, 21. Januar 2009 23:30 schrieb Kellen J. McClain: > I have a quick question. > > Recall that: > class Monad m where > (>>=) :: m a -> (a -> m b) -> m b > ... > > and suppose I have a data type Sample: > > data Sample a b = ... > > how could I define Sample to be an instance of Monad such that: > > (>>=) :: Sample a c -> (a -> Sample b c) -> Sample b c > > ? > > I would like to use a (\a -> ...)-like operator, but for types. > So, something like this: > > instance Monad (\a -> Sample a c) where > (>>=) :: Sample a c -> (a -> Sample b c) -> Sample b c > a >>= f = ... > > but that obviously doesn't work. Alternatively I would > like to use a type declaration and partially apply it: > > type SampleFlip b a = Sample a b > instance Monad (SampleFlip c) where > (>>=) :: SampleFlip c a -> (a -> SampleFlip c b) -> SampleFlip c b > > which translates to: > > (>>=) :: Sample a c -> (a -> Sample b c) -> Sample b c > > But this doesn't work either, and ghc extensions don't add this > functionality. Can I do this in Haskell? > I think you can't. If it's possible, the best option would be to change the order of type parameters of Sample. If that's not possible, you can define newtype FSample b a = FS (Sample a b) and make that an instance of Monad. Somebody remind me, why does Haskell not have type-lambdas? From michael at schmong.org Wed Jan 21 20:33:40 2009 From: michael at schmong.org (Michael Litchard) Date: Wed Jan 21 20:24:26 2009 Subject: [Haskell-beginners] This is problem 2, chapter 4 RWH Message-ID: <3dc350d00901211733v6f7e8842l4ca9581aefc7548c@mail.gmail.com> splitWith' :: (a -> Bool) -> [a] -> [[a]] splitWith' p x = case takeUntil p x of [] -> [] x' -> subset : splitWith' p x'' where (subset, x'') = break p x' where takeUntil :: (a -> Bool) -> [a] -> [a] takeUntil p' = takeWhile q where q x = not (p' x) It doesn't give me the right behavior though. It should work like this: splitWith' odd [2,2,1,4,4,3,6,6,5] [[2,2],[4,4],[6,6]] but it works like this instead [[2,2]] I'm pretty sure I modeled splitWith' on words, which is what the exercise indirectly suggests. Can someone help me step through this code to figure out what's wrong. It looks right to me. Michael Litchard From daniel.is.fischer at web.de Wed Jan 21 21:02:42 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Jan 21 20:50:54 2009 Subject: [Haskell-beginners] This is problem 2, chapter 4 RWH In-Reply-To: <3dc350d00901211733v6f7e8842l4ca9581aefc7548c@mail.gmail.com> References: <3dc350d00901211733v6f7e8842l4ca9581aefc7548c@mail.gmail.com> Message-ID: <200901220302.42525.daniel.is.fischer@web.de> Am Donnerstag, 22. Januar 2009 02:33 schrieb Michael Litchard: > splitWith' :: (a -> Bool) -> [a] -> [[a]] > splitWith' p x = case takeUntil p x of > [] -> [] > x' -> subset : splitWith' p x'' > where (subset, x'') = break p x' > where takeUntil :: (a -> Bool) -> [a] -> [a] > takeUntil p' = takeWhile q > where q x = not (p' x) > > It doesn't give me the right behavior though. > It should work like this: > splitWith' odd [2,2,1,4,4,3,6,6,5] > [[2,2],[4,4],[6,6]] > but it works like this instead > [[2,2]] > > I'm pretty sure I modeled splitWith' on words, which is what the > exercise indirectly suggests. > Can someone help me step through this code to figure out what's wrong. > It looks right to me. takeUntil odd [2,2,1,4,4,3,6,6,5] gives [2,2], so the second branch is taken, next break odd [2,2] is calculated. Since this list doesn't contain any odd numbers, break odd [2,2] == ([2,2],[]), so subset = [2,2], x'' = [] and subset : splitWith' p x'' reduces to [2,2] : splitWith odd [], which of course is [2,2] : [] = [[2,2]]. Your code never touches anything behind the first odd number. To rectify that, instead of takeUntil, you need a function which returns two parts, the initial segment of the list until the first odd number and the part following the first odd number (if there is any). Then your result would be (first part) : splitWith' p (second part). You already use the relevant function, albeit in the wrong place. > > > Michael Litchard HTH, Daniel From byorgey at seas.upenn.edu Wed Jan 21 22:07:00 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Wed Jan 21 21:57:45 2009 Subject: [Haskell-beginners] Type Operator In-Reply-To: <200901212351.26389.daniel.is.fischer@web.de> References: <1232577012.4387.12.camel@kgateway> <200901212351.26389.daniel.is.fischer@web.de> Message-ID: <20090122030700.GA23297@seas.upenn.edu> On Wed, Jan 21, 2009 at 11:51:26PM +0100, Daniel Fischer wrote: > I think you can't. > If it's possible, the best option would be to change the order of type > parameters of Sample. If that's not possible, you can define > > newtype FSample b a = FS (Sample a b) > > and make that an instance of Monad. Right, Haskell doesn't allow partially applied type synonyms, but partially applied newtypes are fine. It will just be a bit annoying having the FS constructor tags everywhere. Switching the order of the parameters to Sample would be the best option. > Somebody remind me, why does Haskell not have type-lambdas? Because type-lambdas would require higher-order unification during type checking, which is in general undecidable. Without type lambdas, if you have to unify two type applications like f a == m b then you know that f == m and a == b. But with type lambdas this might not be the case. For example, you could have f == \x -> [x], a = Int, m = \x -> x, and b = [Int]. -Brent From mle+cl at mega-nerd.com Thu Jan 22 01:25:39 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Thu Jan 22 01:16:29 2009 Subject: [Haskell-beginners] System.Process and ghc 6.8.2 Message-ID: <20090122172539.abe42c6a.mle+cl@mega-nerd.com> Hi all, I'm using ghc/ghci 6.8.2 and looking at the System.Process module. Hoogle lists functions like readProcess and readProcessWithExitCode but they don't seem to exist. Is 6.8.2 too early? Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "Christianity has a nasty habit of ignoring the major problems of our time, including overpopulation and exhaustion of resources, because they aren't mentioned in the Bible." -- Paula L. Craig From mle+cl at mega-nerd.com Thu Jan 22 01:43:16 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Thu Jan 22 01:34:05 2009 Subject: [Haskell-beginners] System.Process and ghc 6.8.2 In-Reply-To: <20090122172539.abe42c6a.mle+cl@mega-nerd.com> References: <20090122172539.abe42c6a.mle+cl@mega-nerd.com> Message-ID: <20090122174316.555c6d1c.mle+cl@mega-nerd.com> Erik de Castro Lopo wrote: > Hoogle lists functions like readProcess and readProcessWithExitCode but > they don't seem to exist. Is 6.8.2 too early? It seems the answer is yes, 6.8.2 is too early. Now trying to create reimplement readProcess in terms of runInteractiveProcess. Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "All great truths begin as blasphemies." -- George Bernard Shaw From mle+cl at mega-nerd.com Thu Jan 22 03:42:44 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Thu Jan 22 03:33:33 2009 Subject: [Haskell-beginners] Is ghc 6.8.2 useful? Message-ID: <20090122194244.0209457e.mle+cl@mega-nerd.com> Hi all, I'm using hoogle (http://www.haskell.org/hoogle/) as my main Haskell documentations source, but I'm stuck on using ghc 6.8.2 and I keep finding stuff listed in hoogle that isn't available in 6.8.2. Is there any solution other than installing a more recent version of ghc? Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "Education is an admirable thing, but it is well to remember from time to time that nothing that is worth knowing can be taught." -- Oscar Wilde From tom.davie at gmail.com Thu Jan 22 04:39:10 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Thu Jan 22 04:29:58 2009 Subject: [Haskell-beginners] Is ghc 6.8.2 useful? In-Reply-To: <20090122194244.0209457e.mle+cl@mega-nerd.com> References: <20090122194244.0209457e.mle+cl@mega-nerd.com> Message-ID: On 22 Jan 2009, at 09:42, Erik de Castro Lopo wrote: > Hi all, > > I'm using hoogle (http://www.haskell.org/hoogle/) as my main Haskell > documentations source, but I'm stuck on using ghc 6.8.2 and I keep > finding stuff listed in hoogle that isn't available in 6.8.2. > > Is there any solution other than installing a more recent version of > ghc? Are you sure that you're finding things that are unavailable in 6.8.2? There's been very little change to the APIs exposed to beginners since then. It may be that you're not importing the module required, when hoogle gives you a result like this: Data.Map insert :: Ord k => k -> a -> Map k a -> Map k a containers O(log n). Insert a new key and value in the map. If the key is already present in the map, the associated value is replaced with the supplied value. insert is equivalent to insertWith const.> insert 5 'x' (fromList [(5,'a'), (3,'b')]) == you must use an import in your file to get access to it, as follows: import Data.Map (insert) or you can import the whole module like this: import Data.Map but this causes namespace polution, so it's not a great idea. You can also import it so that you have to qualify all your uses of the functions: import qualified Data.Map f x y = Data.Map.insert 5 x y -- or import qualified Data.Map as M f x y = M.insert 5 x y Sorry if I just taught my granny to suck eggs. If you are doing this and really are coming up against APIs that aren't in 6.8, then yes, you need to upgrade your compiler. There's no real disadvantage to doing this though, except possibly that you lose support for one or two libraries that are taking a while to update (gtk2hs springs to mind). You do however gain access to libraries that need newer compiler features (vector-space springs to mind). Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090122/7e2f4e2f/attachment.htm From mle+cl at mega-nerd.com Thu Jan 22 04:59:25 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Thu Jan 22 04:50:13 2009 Subject: [Haskell-beginners] Is ghc 6.8.2 useful? In-Reply-To: References: <20090122194244.0209457e.mle+cl@mega-nerd.com> Message-ID: <20090122205925.55ca0983.mle+cl@mega-nerd.com> Thomas Davie wrote: > Are you sure that you're finding things that are unavailable in > 6.8.2? Specifically the things I found missing in just the last couple of hours are: - module Text.Regex.Posix - functions readProcess/readProcessWithExitCode from System.Process - function exitSuccess from System.Exit > There's been very little change to the APIs exposed to > beginners since then. I must admit I am jumping in at the deep end, but I do have 4 years of pretty extensive Ocaml coding under my belt. > It may be that you're not importing the module > required Haskell's modules are quite similar to Ocaml's but I'm pretty confident I have this under control. > Sorry if I just taught my granny to suck eggs. I'm not your granny :-) > If you are doing this > and really are coming up against APIs that aren't in 6.8, then yes, > you need to upgrade your compiler. I'll take that as an ACK. > There's no real disadvantage to > doing this though, except possibly that you lose support for one or > two libraries that are taking a while to update (gtk2hs springs to > mind). Ouch. I'm pretty attached to the debian packaging system on my Debian and Ubuntu systems and really don't like to install non-packaged binaries or source. On top of that I like to use existing libraries whereever possible and that means installing these from source as well. I might have to look into cabal-debian. Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- Gambling(n): A discretionary tax on those asleep during high school maths. From konrad at tylerc.org Thu Jan 22 17:00:42 2009 From: konrad at tylerc.org (Conrad Meyer) Date: Thu Jan 22 16:51:44 2009 Subject: [Haskell-beginners] System.Process and ghc 6.8.2 In-Reply-To: <20090122174316.555c6d1c.mle+cl@mega-nerd.com> References: <20090122172539.abe42c6a.mle+cl@mega-nerd.com> <20090122174316.555c6d1c.mle+cl@mega-nerd.com> Message-ID: <200901221400.42667.konrad@tylerc.org> On Wednesday 21 January 2009 10:43:16 pm Erik de Castro Lopo wrote: > Erik de Castro Lopo wrote: > > Hoogle lists functions like readProcess and readProcessWithExitCode but > > they don't seem to exist. Is 6.8.2 too early? > > It seems the answer is yes, 6.8.2 is too early. > > Now trying to create reimplement readProcess in terms of > runInteractiveProcess. > > Erik Why do this extra work instead of simply upgrading to 6.8.3? -- Conrad Meyer From mle+cl at mega-nerd.com Thu Jan 22 17:28:41 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Thu Jan 22 17:19:30 2009 Subject: [Haskell-beginners] System.Process and ghc 6.8.2 In-Reply-To: <200901221400.42667.konrad@tylerc.org> References: <20090122172539.abe42c6a.mle+cl@mega-nerd.com> <20090122174316.555c6d1c.mle+cl@mega-nerd.com> <200901221400.42667.konrad@tylerc.org> Message-ID: <20090123092841.6548476a.mle+cl@mega-nerd.com> Conrad Meyer wrote: > Why do this extra work instead of simply upgrading to 6.8.3? Mainly because 6.8.2 is installed on my Ubuntu system using a pre-compiled package (including a bunch of pre-compiled libraries). I much prefer to use the the native packaging system because most of the time it works so much better than anything else. Also, the "extra work" became a few minor tweaks to this code: http://www.cse.unsw.edu.au/~dons/code/newpopen/System/Process/Run.hs Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "Using Java as a general purpose application development language is like going big game hunting armed with Nerf weapons." -- Author Unknown From konrad at tylerc.org Thu Jan 22 18:03:37 2009 From: konrad at tylerc.org (Conrad Meyer) Date: Thu Jan 22 17:54:35 2009 Subject: [Haskell-beginners] System.Process and ghc 6.8.2 In-Reply-To: <20090123092841.6548476a.mle+cl@mega-nerd.com> References: <20090122172539.abe42c6a.mle+cl@mega-nerd.com> <200901221400.42667.konrad@tylerc.org> <20090123092841.6548476a.mle+cl@mega-nerd.com> Message-ID: <200901221503.37579.konrad@tylerc.org> On Thursday 22 January 2009 02:28:41 pm Erik de Castro Lopo wrote: > Conrad Meyer wrote: > > Why do this extra work instead of simply upgrading to 6.8.3? > > Mainly because 6.8.2 is installed on my Ubuntu system using a > pre-compiled package (including a bunch of pre-compiled libraries). > I much prefer to use the the native packaging system because most > of the time it works so much better than anything else. > > Also, the "extra work" became a few minor tweaks to this code: > > http://www.cse.unsw.edu.au/~dons/code/newpopen/System/Process/Run.hs > > Cheers, > Erik So nag the Ubuntu ghc maintainer about being several versions behind. Or if they're actually not several versions behind, you're just using an old version of ubuntu, install a copy of ghc from a newer version of ubuntu. -- Conrad Meyer From mle+cl at mega-nerd.com Thu Jan 22 18:14:14 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Thu Jan 22 18:05:02 2009 Subject: [Haskell-beginners] System.Process and ghc 6.8.2 In-Reply-To: <200901221503.37579.konrad@tylerc.org> References: <20090122172539.abe42c6a.mle+cl@mega-nerd.com> <200901221400.42667.konrad@tylerc.org> <20090123092841.6548476a.mle+cl@mega-nerd.com> <200901221503.37579.konrad@tylerc.org> Message-ID: <20090123101414.fa3f593c.mle+cl@mega-nerd.com> Conrad Meyer wrote: > So nag the Ubuntu ghc maintainer about being several versions behind. Or if > they're actually not several versions behind, you're just using an old > version of ubuntu, install a copy of ghc from a newer version of ubuntu. I'm running the current latest release of Ubuntu and using the latest ghc they offer. The Ubuntu people just grab their version from Debian. I'm actually tracking the Debian Haskell mailing list and just in the last week there was an announcement of ghc-6.10.1 going into the experimental repository. Then they need to compile all the libraries with the new compiler. I'm thinking of grabbing the debian source package from Debian experimental and building it on Ubuntu. Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding From s.clover at gmail.com Thu Jan 22 19:03:33 2009 From: s.clover at gmail.com (Sterling Clover) Date: Thu Jan 22 18:54:18 2009 Subject: [Haskell-beginners] Is ghc 6.8.2 useful? In-Reply-To: <20090122205925.55ca0983.mle+cl@mega-nerd.com> References: <20090122194244.0209457e.mle+cl@mega-nerd.com> <20090122205925.55ca0983.mle+cl@mega-nerd.com> Message-ID: The libraries as of 6.8.2 are here: http://www.haskell.org/ghc/docs/6.8.2/html/libraries/ The regex library should be part of extralibs, which appears to come standard with debian's ghc package. There are also better regex libraries available from Hackage. There is indeed a new System.Process API, which you may be able to install from hackage. Otherwise, for most purposes, the old one works just fine. As for exitSuccess, as the documentation notes, it is simply "exitWith ExitSuccess", so I wouldn't be too concerned at not being able to use it. In general 6.8.2 should be very useable still. Cheers, S. On Thu, Jan 22, 2009 at 4:59 AM, Erik de Castro Lopo > wrote: > Thomas Davie wrote: > > > Are you sure that you're finding things that are unavailable in > > 6.8.2? > > Specifically the things I found missing in just the last couple of > hours are: > > - module Text.Regex.Posix > - functions readProcess/readProcessWithExitCode from System.Process > - function exitSuccess from System.Exit > > > There's been very little change to the APIs exposed to > > beginners since then. > > I must admit I am jumping in at the deep end, but I do have 4 years of > pretty extensive Ocaml coding under my belt. > > > It may be that you're not importing the module > > required > > Haskell's modules are quite similar to Ocaml's but I'm pretty confident > I have this under control. > > > Sorry if I just taught my granny to suck eggs. > > I'm not your granny :-) > > > If you are doing this > > and really are coming up against APIs that aren't in 6.8, then yes, > > you need to upgrade your compiler. > > I'll take that as an ACK. > > > There's no real disadvantage to > > doing this though, except possibly that you lose support for one or > > two libraries that are taking a while to update (gtk2hs springs to > > mind). > > Ouch. I'm pretty attached to the debian packaging system on my Debian > and Ubuntu systems and really don't like to install non-packaged > binaries or source. On top of that I like to use existing libraries > whereever possible and that means installing these from source as > well. > > I might have to look into cabal-debian. > > Cheers, > Erik > -- > ----------------------------------------------------------------- > Erik de Castro Lopo > ----------------------------------------------------------------- > Gambling(n): A discretionary tax on those asleep during high school > maths. > _______________________________________________ > 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/20090122/6b43ca84/attachment.htm From mle+cl at mega-nerd.com Thu Jan 22 22:01:41 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Thu Jan 22 21:52:29 2009 Subject: [Haskell-beginners] The case expression Message-ID: <20090123140141.f3f9a400.mle+cl@mega-nerd.com> Hi all, Ocaml's match .. with expression (very similar to Haskell's case) allows multiple matches for a single result (naive example): let f x = match x with | 0 -> "zero" | 1 | 3 | 5 | 7 -> "odd" | 2 | 4 | 6 | 8 -> "even" _ -> "bad number" Is there a similar thing in Haskell? At the moment I have to do something like : f x = case x of 0 -> "zero" 1 -> "odd" 3 -> "odd" 5 -> "odd" 7 -> "odd" 2 -> "even" 4 -> "even" 6 -> "even" 8 -> "even" _ -> "bad number" Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "One of our programming maxims is "make illegal states unrepresentable" by which we mean that if a given collection of values constitute an error, then it is better to arrange for that collection of values to be impossible to represent within the constraints of the type system." -- Yaron Minsky http://www.haskell.org/sitewiki/images/0/03/TMR-Issue7.pdf From byorgey at seas.upenn.edu Thu Jan 22 22:11:20 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Thu Jan 22 22:02:03 2009 Subject: [Haskell-beginners] The case expression In-Reply-To: <20090123140141.f3f9a400.mle+cl@mega-nerd.com> References: <20090123140141.f3f9a400.mle+cl@mega-nerd.com> Message-ID: <20090123031119.GA18932@seas.upenn.edu> On Fri, Jan 23, 2009 at 02:01:41PM +1100, Erik de Castro Lopo wrote: > Hi all, > > Ocaml's match .. with expression (very similar to Haskell's case) > allows multiple matches for a single result (naive example): > > let f x = > match x with > | 0 -> "zero" > | 1 | 3 | 5 | 7 -> "odd" > | 2 | 4 | 6 | 8 -> "even" > _ -> "bad number" > > Is there a similar thing in Haskell? There isn't, but in this particular case (and in many similar cases) you could always do something like this, using guards: let f x | x == 0 -> "zero" | x `elem` [1,3,5,7] -> "odd" | x `elem` [2,4,6,8] -> "even" | otherwise -> "bad number" -Brent From mle+cl at mega-nerd.com Thu Jan 22 22:17:00 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Thu Jan 22 22:07:47 2009 Subject: [Haskell-beginners] The case expression In-Reply-To: <11f192740901221908l492e1d6bw486dda1cb9968521@mail.gmail.com> References: <20090123140141.f3f9a400.mle+cl@mega-nerd.com> <11f192740901221908l492e1d6bw486dda1cb9968521@mail.gmail.com> Message-ID: <20090123141700.3cddfd4f.mle+cl@mega-nerd.com> David Morse wrote: > So you could really hammer it with blunt force: > > case x of > 0 -> "zero" > n | n `elem` [1,3,5,7] -> "odd" > | n `elem` [2, 4, 6, 8] -> "even" > | otherwise -> "bad number" Ah, that's was what I was after. Thanks. > By the way, zero is even. http://en.wikipedia.org/wiki/Zero_is_even I did warn people this was a naive example. Did I really need to make people aware this it was a *silly, completely contrived and possibly incorrect* example ;-). Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "Therapists typically base the nuttiness of a patient on the strength of their convictions, on which basis this 43,000 word opus alone stands as a kind of testament to Bill's (Gates) madness." - The Register From dcmorse at gmail.com Thu Jan 22 22:08:40 2009 From: dcmorse at gmail.com (David Morse) Date: Fri Jan 23 00:27:39 2009 Subject: [Haskell-beginners] The case expression In-Reply-To: <20090123140141.f3f9a400.mle+cl@mega-nerd.com> References: <20090123140141.f3f9a400.mle+cl@mega-nerd.com> Message-ID: <11f192740901221908l492e1d6bw486dda1cb9968521@mail.gmail.com> On Thu, Jan 22, 2009 at 10:01 PM, Erik de Castro Lopo wrote: > > Hi all, > > Ocaml's match .. with expression (very similar to Haskell's case) > allows multiple matches for a single result (naive example): > > let f x = > match x with > | 0 -> "zero" > | 1 | 3 | 5 | 7 -> "odd" > | 2 | 4 | 6 | 8 -> "even" > _ -> "bad number" > > Is there a similar thing in Haskell? At the moment I have to do > something like : > > f x = > case x of > 0 -> "zero" > 1 -> "odd" > 3 -> "odd" > 5 -> "odd" > 7 -> "odd" > 2 -> "even" > 4 -> "even" > 6 -> "even" > 8 -> "even" > _ -> "bad number" Well you can guard each clause: case x of 0 -> "zero" n | even n -> "even" | odd n -> "odd" | otherwise -> "bad number" Still not quite exactly what you've got. So you could really hammer it with blunt force: case x of 0 -> "zero" n | n `elem` [1,3,5,7] -> "odd" | n `elem` [2, 4, 6, 8] -> "even" | otherwise -> "bad number" By the way, zero is even. http://en.wikipedia.org/wiki/Zero_is_even From seideld at tcs.inf.tu-dresden.de Fri Jan 23 02:41:27 2009 From: seideld at tcs.inf.tu-dresden.de (Daniel Seidel) Date: Fri Jan 23 02:32:11 2009 Subject: [Haskell-beginners] The case expression In-Reply-To: <20090123140141.f3f9a400.mle+cl@mega-nerd.com> References: <20090123140141.f3f9a400.mle+cl@mega-nerd.com> Message-ID: <497974A7.2080906@tcs.inf.tu-dresden.de> Erik de Castro Lopo wrote: > Hi all, > > Ocaml's match .. with expression (very similar to Haskell's case) > allows multiple matches for a single result (naive example): > > let f x = > match x with > | 0 -> "zero" > | 1 | 3 | 5 | 7 -> "odd" > | 2 | 4 | 6 | 8 -> "even" > _ -> "bad number" > > Is there a similar thing in Haskell? At the moment I have to do > something like : > > f x = > case x of > 0 -> "zero" > 1 -> "odd" > 3 -> "odd" > 5 -> "odd" > 7 -> "odd" > 2 -> "even" > 4 -> "even" > 6 -> "even" > 8 -> "even" > _ -> "bad number" > > Cheers, > Erik > Hi Erik, you can use guards like this: f x | x == 0 = "zero" | x `elem` [1,3,5,7] = "odd" | x `elem` [2,4,6,8] = "even" | otherwise = "bad number" daniel. -------------- next part -------------- A non-text attachment was scrubbed... Name: seideld.vcf Type: text/x-vcard Size: 255 bytes Desc: not available Url : http://www.haskell.org/pipermail/beginners/attachments/20090123/0e2b5837/seideld-0001.vcf From bieffe62 at gmail.com Fri Jan 23 05:34:49 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Fri Jan 23 05:25:31 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all Message-ID: Hi all. It's about a month I'm trying to learn haskell in my spare time ( and, I should add, with my spare neuron :-). I made progress, but more slowly than I expected :-(. I started hasking question on comp.lang.haskell (I like newsgroups more than mailing lists), but then realized that this may be a better places for my newbie questions. So, here comes the first ... As many beginners coming from OOP, i made the mental equation 'type class == interface'. It worked well ... unitil yesterday. Then I discovered that this piece of code (1) is illegal in askell (ghc gives the 'rigid type variable' error) Num n => a :: n a = 3 :: Integer I also discovered that this (2) instead is legal: Num n => a :: n a = 3 because it is implicitely translated into (3): Num n => a :: n a = fromInteger 3 But I don't understand the difference between (1) and (3). I could not find the implementation of fromInteger, but I suspect that it goes like this: instance Num Integer where fromInteger x -> x To me, it looks like (1) and (3) are equal, but that the compiler needs a sort of 'formal reassurance' that the value yielded by 'a' is of Num type. But since Integer is an instance of Num, I expected that (1) was already giving this reassurance. At least, it works this way with interfaces in Java and with class pointers in C++. But obviously there is something I don't get here ... Anybody here can explain? Ciao ----- FB -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090123/fea27376/attachment.htm From mail at paulvisschers.net Fri Jan 23 06:07:38 2009 From: mail at paulvisschers.net (Paul Visschers) Date: Fri Jan 23 05:58:24 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: References: Message-ID: <4979A4FA.7090106@paulvisschers.net> Hello, It seems like you have some trouble with grasping the concept of polymorphism in this particular case. The function reverse has the following type: reverse :: [a] -> [a] This means that this function will work on a list containing any type, and it will return that same type. A sort function would have a type like this: sort :: (Ord a) => [a] -> [a] This function also doesn't care what type the list is filled with, but does require this type to be an instance of the Ord class (so it can be ordered). Now an example with the Num class: (+) :: (Num a) => a -> a -> a This function works on any type which is an instance of Num, for example Int and Integer. The type of fromInteger is: fromInteger :: (Num a) => Integer -> a You are correct that literal numbers are internally rewritten, so 3 becomes fromInteger 3, giving the following type: fromInteger 3 :: (Num a) => a This means that fromInteger 3 is of type a, for any a that is an instance of Num. In your example (which seems to be in a bad syntax), you're saying that a must be of type: a :: (Num n) => n So this is the same type as fromInteger 3. So just saying that a = 3 or a = fromInteger 3 will work here. The function a is polymorphic, just like sort or (+) are. They (have to) work for any type that implements the corresponding type class. The problem comes from the extra type annotation: a = 3 :: Integer Which says that instead of being of any numeric type, a is of type Integer. This is less general, since you can't use it when you need an Int or a Double for example. I hope I explained it clearly. If not please reply. Paul Francesco Bochicchio wrote: > Hi all. > It's about a month I'm trying to learn haskell in my spare time ( and, I > should add, with my spare neuron :-). > I made progress, but more slowly than I expected :-(. I started hasking > question on comp.lang.haskell > (I like newsgroups more than mailing lists), but then realized that this > may be a better places for my newbie > questions. So, here comes the first ... > > As many beginners coming from OOP, i made the mental equation 'type > class == interface'. > It worked well ... unitil yesterday. > > Then I discovered that this piece of code (1) is illegal in askell (ghc > gives the 'rigid type variable' error) > > Num n => a :: n > a = 3 :: Integer > > I also discovered that this (2) instead is legal: > > Num n => a :: n > a = 3 > > because it is implicitely translated into (3): > > Num n => a :: n > a = fromInteger 3 > > But I don't understand the difference between (1) and (3). I could not > find the implementation of > fromInteger, but I suspect that it goes like this: > > instance Num Integer where > fromInteger x -> x > > > To me, it looks like (1) and (3) are equal, but that the compiler needs > a sort of 'formal reassurance' that > the value yielded by 'a' is of Num type. But since Integer is an > instance of Num, I expected that > (1) was already giving this reassurance. At least, it works this way > with interfaces in Java and with class pointers in C++. > > But obviously there is something I don't get here ... > > Anybody here can explain? > > Ciao > ----- > FB > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From jakubuv at gmail.com Fri Jan 23 06:15:08 2009 From: jakubuv at gmail.com (Jan Jakubuv) Date: Fri Jan 23 06:05:50 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: References: Message-ID: hi, 2009/1/23 Francesco Bochicchio : > > Then I discovered that this piece of code (1) is illegal in askell (ghc > gives the 'rigid type variable' error) > > Num n => a :: n > a = 3 :: Integer > I guess you mean: a :: Num n => n The problem whith your implementation of 'a' a = 3 :: Integer is that it provides too specific result. Its type signature says that its result has to be of the type n for *any* instance of the class Num. But your result is simply Integer that is just *one* specific instance of Num. In other words it has to be possible to specialize ("retype") 'a' to any other instance of Num, which is no longer possible because (3 :: Integer) is already specialized. > I also discovered that this (2) instead is legal: > > Num n => a :: n > a = 3 > It's fine because 3 has the type (Num t) => t:: Prelude> :t 3 3 :: (Num t) => t > because it is implicitely translated into (3): > > Num n => a :: n > a = fromInteger 3 > also fine: Prelude> :t fromInteger fromInteger :: (Num a) => Integer -> a Sincerely, jan. From bieffe62 at gmail.com Fri Jan 23 08:37:12 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Fri Jan 23 08:27:56 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: <4979A4FA.7090106@paulvisschers.net> References: <4979A4FA.7090106@paulvisschers.net> Message-ID: 2009/1/23 Paul Visschers > Hello, > > It seems like you have some trouble with grasping the concept of > polymorphism in this particular case. > > <...> > I think I get the polymorphism. What I don't get is why a specialized type cannot replace a more generic type, since the specialized type implements the interface defined in the generic type. As I tried to explain, I'm probably misled by the comparison with OOP languages, where polymorphism is implemented via interfaces (Java) or abstract classes/methods (C++). For instance in Java you can write: AbstractInterface a = new ConcreteClass(); if ConcreteClass implements AbstractInterface. The complier will handle a as an instance of AbstractInterface, ignoring anything that is not specifed in its declaration. This make the substitution safe: for instance calling a.AbstractInterfaceMethod() is fine, while calling a.ConcreteClassMethod() gives you an error. Now, I understand that this is not the case in haskell, and I understand the formal reason you give for this. What I am trying to understand is the _actual_ reason behind the formal reason: usually a programming language place limits to avoid ambiguity or misuse of language feature. <...> The problem comes from the extra type annotation: a = 3 :: Integer Which says that instead of being of any numeric type, a is of type Integer. This is less general, since you can't use it when you need an Int or a Double for example. This is what I don't get : why yielding an Integer is not good enough for a function that promises to yield a num? What is missing in Integer? > > > I hope I explained it clearly. If not please reply. > > Paul > You have been clear. I'm probably still too bound to OOP world. Thanks. Ciao ------- FB -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090123/afac5e0d/attachment.htm From tom.davie at gmail.com Fri Jan 23 08:50:47 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Fri Jan 23 08:41:33 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: References: <4979A4FA.7090106@paulvisschers.net> Message-ID: <360BB7A0-0883-4AE6-A084-5562D1C444D8@gmail.com> On 23 Jan 2009, at 14:37, Francesco Bochicchio wrote: > > > 2009/1/23 Paul Visschers > Hello, > > It seems like you have some trouble with grasping the concept of > polymorphism in this particular case. > > <...> > > I think I get the polymorphism. What I don't get is why a > specialized type cannot > replace a more generic type, since the specialized type implements > the interface > defined in the generic type. > Suppose I declare this constant: x :: Num a => a x = 3 :: Integer Now suppose I want to use that in a function. It's type signature says that x is *any* numeric type i want it to be, so I'm going to add it to another numeric value: y :: Complex Float y = x + (5.3 :+ 6.93) Unfortunately, x *can't* take the form of any Numeric type ? it has to be an Integer, so I can't add it do Complex Floating point numbers. The type system is telling you "while Integers may imelement the numeric interface, the value 3 :: Integer is not a generic value ? it can't take the form of *any* numeric value, only a specific type of numeric values". Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090123/78b0413c/attachment.htm From bieffe62 at gmail.com Fri Jan 23 08:51:17 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Fri Jan 23 08:42:00 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: References: Message-ID: 2009/1/23 Jan Jakubuv > hi, > > 2009/1/23 Francesco Bochicchio : > > > > Then I discovered that this piece of code (1) is illegal in askell (ghc > > gives the 'rigid type variable' error) > > > > Num n => a :: n > > a = 3 :: Integer > > > > I guess you mean: > > a :: Num n => n > Yes. I'm not _that_ beginner :-) (although I tend to make this mistake quite often ). > > The problem whith your implementation of 'a' > > a = 3 :: Integer > > is that it provides too specific result. Its type signature says that > its result has to be of the type n for *any* instance of the class > Num. But your result is simply Integer that is just *one* specific > instance of Num. In other words it has to be possible to specialize > ("retype") 'a' to any other instance of Num, which is no longer > possible because (3 :: Integer) is already specialized. > Uhm. Now I think I start to get it ... You are saying that if a value is a Num, it shall be possible to convert it in _any_ of the num instances? > Sincerely, > jan. > Ciao ------- FB -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090123/38a72072/attachment-0001.htm From michael at schmong.org Fri Jan 23 09:05:57 2009 From: michael at schmong.org (Michael Litchard) Date: Fri Jan 23 08:56:39 2009 Subject: [Haskell-beginners] problem 8 / 9 chapter 4, RWH Message-ID: <3dc350d00901230605v242a00a0vbc35def7e3c2b8a8@mail.gmail.com> I noticed that in problem 4, the use of Either is needed, which hasn't been introduced yet. I've gotten stuck on 8/9, and am wondering if there is something needed that hasn't been introduced yet as well? Put another way, can problem 8/9 be done given the parts of the language introduced thus far? Regards, Michael Litchard From es at ertes.de Fri Jan 23 09:08:58 2009 From: es at ertes.de (Ertugrul Soeylemez) Date: Fri Jan 23 09:00:00 2009 Subject: [Haskell-beginners] Re: Type classes are not like interfaces, after all References: <4979A4FA.7090106@paulvisschers.net> Message-ID: <20090123150858.1a05893b@tritium.xx> Francesco Bochicchio wrote: > I think I get the polymorphism. What I don't get is why a specialized > type cannot replace a more generic type, since the specialized type > implements the interface defined in the generic type. Don't confuse this kind of polymorphism with the one you usually find in OOP languages. Consider your original function again. Let me change its name to make it clearer: arbitraryNum :: Num n => n arbitraryNum = 3 :: Integer If 'arbitraryNum' is referenced somewhere else, then the result is expected to be of type 'Num n => n'. It may be referenced as an Integer, as a Float, as a complex number, etc., whatever is a Num instance is valid here. So the value you're trying to give 'arbitraryNum' is of a too specific type. You're trying to use information, which you don't have, namely that 'n' is an Integer. The only information about 'n' you have is that it's a Num type. Now the Num type class contains the fromInteger function, which you can use to convert any Integer to a Num type. So you can write: arbitraryNum :: Num n => n arbitraryNum = fromInteger (3 :: Integer) You take 3, which is an Integer, and use fromInteger to convert it to 'Num n => n'. Try to think for a moment about what the outcome of the following function can be: arbitraryValue :: a arbitraryValue = ...? You should come to the conclusion that arbitraryValue cannot return anything, because it doesn't have any information about what it's supposed to return. What is the type 'a'? What information do you have about 'a'? No information. Not even enough information to construct a value of type 'a'. The type 'a' is most polymorphic and its value is least defined. Of course, you can write such a function, under the strict requirement that it never returns a value. You say, the result of such a function is 'bottom'. For example: bottom :: a bottom = bottom This function never returns. It recurses forever. Greets, Ertugrul. -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From davidkovaccs at gmail.com Fri Jan 23 09:40:01 2009 From: davidkovaccs at gmail.com (Kovacs David) Date: Fri Jan 23 09:30:52 2009 Subject: [Haskell-beginners] case in monadic function Message-ID: <4979D6C1.6020200@gmail.com> Hello! I have a function like this: http://rafb.net/p/8E66FI29.html, starting with evalState. The problem is with checkPredName cause it's return type is SemanticError what's not a monadic value but case waiting for m a (as the error message sais), but if I use return to checkPredName then ofc the pattern match will fail. How can I fix this? Regards, David From tom.davie at gmail.com Fri Jan 23 09:52:12 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Fri Jan 23 09:43:18 2009 Subject: [Haskell-beginners] case in monadic function In-Reply-To: <4979D6C1.6020200@gmail.com> References: <4979D6C1.6020200@gmail.com> Message-ID: On 23 Jan 2009, at 15:40, Kovacs David wrote: > Hello! > > I have a function like this: http://rafb.net/p/8E66FI29.html, > starting with evalState. The problem is with checkPredName cause > it's return type is SemanticError what's not a monadic value but > case waiting for m a (as the error message sais), but if I use > return to checkPredName then ofc the pattern match will fail. How > can I fix this? This looks a lot to me like you need to look at the Error e => Either e applicative. Bob From tom.davie at gmail.com Fri Jan 23 09:54:30 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Fri Jan 23 09:45:13 2009 Subject: [Haskell-beginners] case in monadic function In-Reply-To: <4979D6C1.6020200@gmail.com> References: <4979D6C1.6020200@gmail.com> Message-ID: <67E088EB-7103-412C-84E0-3B6422E70ECC@gmail.com> On 23 Jan 2009, at 15:40, Kovacs David wrote: > Hello! > > I have a function like this: http://rafb.net/p/8E66FI29.html, > starting with evalState. The problem is with checkPredName cause > it's return type is SemanticError what's not a monadic value but > case waiting for m a (as the error message sais), but if I use > return to checkPredName then ofc the pattern match will fail. How > can I fix this? Oops, sorry, I meant monad, because this monad unfortunately doesn't have it's associated Applicative instance (which is much nicer to work with). You can ofc create the standard applicative instance: instance Error e => Applicative (Either e) where pure = return (<*>) = ap Bob From byorgey at seas.upenn.edu Fri Jan 23 09:59:49 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Fri Jan 23 09:50:30 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: References: <4979A4FA.7090106@paulvisschers.net> Message-ID: <20090123145948.GA13700@seas.upenn.edu> > > AbstractInterface a = new ConcreteClass(); In Java, if a variable has type AbstractInterface, it is *existentially* quantified: it means, this variable references a value of *some* type, and all you know about it is that it is an instance of AbstractInterface. Whatever code sets the value of the variable gets to choose its concrete type; any code that uses the variable cannot choose what type it should be, but can only use AbstractInterface methods on it (since that's all that is known). However, a Haskell variable with type var :: AbstractInterface a => a is *universally* quantified: it means, this variable has a polymorphic value, which can be used as a value of any type which is an instance of AbstractInterface. Here, it is the code which *uses* var that gets to choose its type (and indeed, different choices can be made for different uses); the definition of var cannot choose, and must work for any type which is an instance of AbstractInterface (hence it must only use methods of the AbstractInterface type class). Writing a :: Num n => n a = 3 :: Integer is trying to define a universally quantified value as if it were existentially quantified. Now, it *is* possible to have existentially quantification in Haskell; I can show you how if you like, but I think I'll stop here for now. Does this help? -Brent From wagner.andrew at gmail.com Fri Jan 23 10:20:47 2009 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Fri Jan 23 10:11:29 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: <20090123145948.GA13700@seas.upenn.edu> References: <4979A4FA.7090106@paulvisschers.net> <20090123145948.GA13700@seas.upenn.edu> Message-ID: I think this explanation is positively brilliant. Byorgey++ On Fri, Jan 23, 2009 at 9:59 AM, Brent Yorgey wrote: > > > > AbstractInterface a = new ConcreteClass(); > > In Java, if a variable has type AbstractInterface, it is > *existentially* quantified: it means, this variable references a value > of *some* type, and all you know about it is that it is an instance of > AbstractInterface. Whatever code sets the value of the variable gets > to choose its concrete type; any code that uses the variable cannot > choose what type it should be, but can only use AbstractInterface > methods on it (since that's all that is known). > > However, a Haskell variable with type > > var :: AbstractInterface a => a > > is *universally* quantified: it means, this variable has a polymorphic > value, which can be used as a value of any type which is an instance > of AbstractInterface. Here, it is the code which *uses* var that gets > to choose its type (and indeed, different choices can be made for > different uses); the definition of var cannot choose, and must work > for any type which is an instance of AbstractInterface (hence it must > only use methods of the AbstractInterface type class). > > Writing > > a :: Num n => n > a = 3 :: Integer > > is trying to define a universally quantified value as if it were > existentially quantified. > > Now, it *is* possible to have existentially quantification in Haskell; > I can show you how if you like, but I think I'll stop here for now. > > Does this help? > > -Brent > _______________________________________________ > 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/20090123/cafabf49/attachment.htm From jakubuv at gmail.com Fri Jan 23 10:41:18 2009 From: jakubuv at gmail.com (Jan Jakubuv) Date: Fri Jan 23 10:32:00 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: References: Message-ID: 2009/1/23 Francesco Bochicchio : > > > 2009/1/23 Jan Jakubuv >> >> hi, >> >> 2009/1/23 Francesco Bochicchio : >> > >> The problem whith your implementation of 'a' >> >> a = 3 :: Integer >> >> is that it provides too specific result. Its type signature says that >> its result has to be of the type n for *any* instance of the class >> Num. But your result is simply Integer that is just *one* specific >> instance of Num. In other words it has to be possible to specialize >> ("retype") 'a' to any other instance of Num, which is no longer >> possible because (3 :: Integer) is already specialized. > > > Uhm. Now I think I start to get it ... > You are saying that if a value is a Num, it shall be possible to convert it > in _any_ of the num instances? > Well, in this case of the above constant yes. The main point here is that when you want to implement a function of a type say (Num a => a -> a) then the implementation has to work for *all* instances of the class Num. Usually you can use only "abstract" functions defined in a class declaration to write such functions. Try to start with some function that mentions the quantified type in one of its arguments. They are easier to understand. Constants like (Num a => a) and functions like (Num a => Bool -> a) are rare (also they have a special name I can not recall ;-). Also note that you can take: a :: (Num t) => t a = 3 and then specialize it: spec = (a :: Integer) Sincerely, jan. From jeedward at yahoo.com Fri Jan 23 10:51:38 2009 From: jeedward at yahoo.com (John Edward) Date: Fri Jan 23 10:42:20 2009 Subject: [Haskell-beginners] Final call for papers: MULTICONF-09 Message-ID: <494239.90965.qm@web45901.mail.sp1.yahoo.com> ? ? The 2009 Multi Conference in Computer Science, Information Technology and Control systems and Computational Science and Computer Engineering (MULTICONF-09) (website: http://www.PromoteResearch.org) will be held during July 13-16 2009 in Orlando, FL, USA. We invite draft paper submissions. The event consists of the following conferences: ????????? International Conference on Artificial Intelligence and Pattern Recognition (AIPR-09) ????????? International Conference on Automation, Robotics and Control Systems (ARCS-09) ????????? International Conference on Bioinformatics, Computational Biology, Genomics and Chemoinformatics (BCBGC-09) ????????? International Conference on Enterprise Information Systems and Web Technologies (EISWT-09) ????????? International Conference on High Performance Computing, Networking and Communication Systems (HPCNCS-09) ????????? International Conference on Information Security and Privacy (ISP-09) ????????? International Conference on Recent Advances in Information Technology and Applications (RAITA-09) ????????? International Conference on Software Engineering Theory and Practice (SETP-09) ????????? International Conference on Theory and Applications of Computational Science (TACS-09) ????????? International Conference on Theoretical and Mathematical Foundations of Computer Science (TMFCS-09) ? The website http://www.PromoteResearch.org? contains more details. ? Sincerely John Edward Publicity committee ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090123/cac1ed10/attachment-0001.htm From asgaroth_ at gmx.de Fri Jan 23 10:52:39 2009 From: asgaroth_ at gmx.de (Daniel Schoepe) Date: Fri Jan 23 10:43:26 2009 Subject: [Haskell-beginners] case in monadic function In-Reply-To: <4979D6C1.6020200@gmail.com> References: <4979D6C1.6020200@gmail.com> Message-ID: <4979E7C7.1020902@gmx.de> Kovacs David wrote: > Hello! > > I have a function like this: http://rafb.net/p/8E66FI29.html, starting > with evalState. The problem is with checkPredName cause it's return type > is SemanticError what's not a monadic value but case waiting for m a (as > the error message sais), but if I use return to checkPredName then ofc > the pattern match will fail. How can I fix this? > > Regards, David You can use liftM/fmap to lift a function into a monad: case (checkPredName pn . snd) `fmap` get of ... From asgaroth_ at gmx.de Fri Jan 23 11:00:43 2009 From: asgaroth_ at gmx.de (Daniel Schoepe) Date: Fri Jan 23 10:51:25 2009 Subject: [Haskell-beginners] case in monadic function In-Reply-To: <4979E7C7.1020902@gmx.de> References: <4979D6C1.6020200@gmail.com> <4979E7C7.1020902@gmx.de> Message-ID: <4979E9AB.1000006@gmx.de> Daniel Schoepe wrote: > You can use liftM/fmap to lift a function into a monad: > case (checkPredName pn . snd) `fmap` get of ... I'm sorry, I misunderstood the problem, so this suggestion wouldn't work either. Could you give some more information on what SemanticResult is? From davidkovaccs at gmail.com Fri Jan 23 11:04:18 2009 From: davidkovaccs at gmail.com (Kovacs David) Date: Fri Jan 23 10:55:10 2009 Subject: [Haskell-beginners] case in monadic function In-Reply-To: <4979E9AB.1000006@gmx.de> References: <4979D6C1.6020200@gmail.com> <4979E7C7.1020902@gmx.de> <4979E9AB.1000006@gmx.de> Message-ID: <4979EA82.8040300@gmail.com> Daniel Schoepe wrote: > Daniel Schoepe wrote: > > >> You can use liftM/fmap to lift a function into a monad: >> case (checkPredName pn . snd) `fmap` get of ... >> > > I'm sorry, I misunderstood the problem, so this suggestion wouldn't work > either. Could you give some more information on what SemanticResult is? > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > It looks like this: data SemanticResult = Ok | Error String; From bieffe62 at gmail.com Fri Jan 23 11:46:11 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Fri Jan 23 11:36:54 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: <20090123145948.GA13700@seas.upenn.edu> References: <4979A4FA.7090106@paulvisschers.net> <20090123145948.GA13700@seas.upenn.edu> Message-ID: 2009/1/23 Brent Yorgey > > > > AbstractInterface a = new ConcreteClass(); > > In Java, if a variable has type AbstractInterface, it is > *existentially* quantified: it means, this variable references a value > of *some* type, and all you know about it is that it is an instance of > AbstractInterface. Whatever code sets the value of the variable gets > to choose its concrete type; any code that uses the variable cannot > choose what type it should be, but can only use AbstractInterface > methods on it (since that's all that is known). > > However, a Haskell variable with type > > var :: AbstractInterface a => a > > is *universally* quantified: it means, this variable has a polymorphic > value, which can be used as a value of any type which is an instance > of AbstractInterface. Here, it is the code which *uses* var that gets > to choose its type (and indeed, different choices can be made for > different uses); the definition of var cannot choose, and must work > for any type which is an instance of AbstractInterface (hence it must > only use methods of the AbstractInterface type class). > > Writing > > a :: Num n => n > a = 3 :: Integer > > is trying to define a universally quantified value as if it were > existentially quantified. > > Now, it *is* possible to have existentially quantification in Haskell; > I can show you how if you like, but I think I'll stop here for now. > > Does this help? > > Yes thanks. >From other answers, I also got the essence of it, but now I know the exact terminology: I met the terms 'existentially quantification' and 'universal quantification' before, but did not have any idea of their meaning. I did not now than embarking in studying haskell I had to study phylosophy too :-) Joking apart, I believe something like your explanation should be reported in tutorials helping to learn haskell, especially the ones for people coming from other languages. As I said in my initial post the analogy 'type class are like interfaces' is a good starting point, but carried too far it is misleading. Thanks again to all the posters that replied to my question. This seems a lively forum: expect to see soon other questions from me :-). Ciao ------ FB -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090123/b196a1e6/attachment.htm From byorgey at seas.upenn.edu Fri Jan 23 14:10:57 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Fri Jan 23 14:01:38 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: References: <4979A4FA.7090106@paulvisschers.net> <20090123145948.GA13700@seas.upenn.edu> Message-ID: <20090123191057.GA8032@seas.upenn.edu> On Fri, Jan 23, 2009 at 05:46:11PM +0100, Francesco Bochicchio wrote: > 2009/1/23 Brent Yorgey > > > Now, it *is* possible to have existentially quantification in Haskell; > > I can show you how if you like, but I think I'll stop here for now. > > > > Does this help? > > > > > Yes thanks. > >From other answers, I also got the essence of it, but now I know the exact > terminology: I met the terms Glad it helped! And just so you know, I made a typo; that should say 'existential quantificataion', not 'existentially quantification'. =) -Brent From allbery at ece.cmu.edu Sat Jan 24 00:14:06 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sat Jan 24 00:04:50 2009 Subject: [Haskell-beginners] Type classes are not like interfaces, after all In-Reply-To: References: <4979A4FA.7090106@paulvisschers.net> Message-ID: On 2009 Jan 23, at 8:37, Francesco Bochicchio wrote: > I think I get the polymorphism. What I don't get is why a > specialized type cannot > replace a more generic type, since the specialized type implements > the interface > defined in the generic type. Try it this way. The declaration > a :: Num n => n > a = 3 :: Integer is not the same as > AbstractInterface a = new ConcreteClass(); because Integer doesn't implement *all* of Num, in particular nothing needed for the Float, Double, or Complex instances. In a sense, instances in Haskell are inverses of interfaces in Java; in Java you accept more specific but in Haskell you accept *less* specific. This is because an instance actually asserts a "for all possible matching types" requirement, whereas Java asserts an "any matching type" requirement. (Pedantically: > a :: forall n. Num n => n You don't have to write (and in Haskell 98, can't write, just as in Java you can't explicitly write "forany" in an interface definition) the "forall"; in Haskell98 (and Java respectively) it's there by definition, in Haskell extensions it's implied for top level types for backward compatibility.) In many cases you can treat the two the same because the member types happen to have an exact relationship such that "forall" and "forany" are both satisfied, but Num is too wide (and far too complex; the ideal structure of the Haskell numeric classes is constantly debated). So the equivalence of typeclasses and interfaces is a "most of the time" thing, not a definition or requirement. -- 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 -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090124/e9014272/attachment.htm From eeoam at ukfsn.org Sat Jan 24 08:28:41 2009 From: eeoam at ukfsn.org (Eric Macaulay) Date: Sat Jan 24 08:20:41 2009 Subject: [Haskell-beginners] Re: Type classes are not like interfaces, after all References: Message-ID: Francesco Bochicchio gmail.com> writes: > > It worked well ... unitil yesterday.?Then I discovered that this piece > of code?(1) is illegal in askell (ghc gives the 'rigid type variable' > error) >?a :: Num n => n > a = 3 :: Integer? A way to understand the type of a is that it has an implicit parameter: a :: {n:Type} -> Num n -> n Now we can see why the definition you gave doesn't work - the type n is provided by the caller of your function which *must* return a value of that type. If your function was called with a {Float} _ 0.0 then you must return a Float. Your definition specifically declares you return an integer, which is wrong. Hope this helps, Eric From john.hartnup at gmail.com Sat Jan 24 14:37:29 2009 From: john.hartnup at gmail.com (John Hartnup) Date: Sat Jan 24 14:28:06 2009 Subject: [Haskell-beginners] ($) operator Message-ID: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> Hi. I'm working through Real World Haskell, and although it's going well (I just finished the exercise to write a glob matcher without using a regex library, and I'm pleased as punch), I keep seeing the ($) operator, and I'm not sure I understand its use. If the book explains it, I've been unable to find it. Empirically, it seems like: a $ b c d e f .. is equivalent to .. a (b c d e f) But is that it's only purpose? To placate the LISP haters by removing parentheses? (1 +) 2 does the same thing as (1 +) $ 2, and has the same type. Am I missing something? Thanks, John -- "There is no way to peace; peace is the way" From daniel.is.fischer at web.de Sat Jan 24 15:09:31 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Jan 24 14:57:33 2009 Subject: [Haskell-beginners] ($) operator In-Reply-To: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> References: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> Message-ID: <200901242109.31199.daniel.is.fischer@web.de> Am Samstag, 24. Januar 2009 20:37 schrieb John Hartnup: > Hi. > > I'm working through Real World Haskell, and although it's going well > (I just finished the exercise to write a glob matcher without using a > regex library, and I'm pleased as punch), I keep seeing the ($) > operator, and I'm not sure I understand its use. If the book explains > it, I've been unable to find it. > > Empirically, it seems like: > a $ b c d e f > .. is equivalent to .. > a (b c d e f) Indeed. ($) is the function application operator, f $ x = f x , so a $ b c d e f is equivalent to a (b c d e f) and a $ b c $ d e f to a (b c (d e f)). > > But is that its only purpose? To placate the LISP haters by removing > parentheses? More or less. Although the idea was more to enhance readability than placating LISP haters :) It's also handy to pass to some higher order functions, although offhand I can't think of any situation where you couldn't pass id instead of ($). > > (1 +) 2 does the same thing as (1 +) $ 2, and has the same type. > > Am I missing something? > > Thanks, > John From schwidom at gmx.net Sat Jan 24 17:14:02 2009 From: schwidom at gmx.net (Frank Schwidom) Date: Sat Jan 24 16:05:36 2009 Subject: [fschwidom@localhost: Re: [Haskell-beginners] ($) operator] Message-ID: <20090124221402.GB4496@BigBox> ----- Forwarded message from Frank Schwidom ----- Date: Sat, 24 Jan 2009 21:40:54 +0000 From: Frank Schwidom To: John Hartnup Subject: Re: [Haskell-beginners] ($) operator Message-ID: <20090124214053.GA4496@BigBox> References: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> User-Agent: Mutt/1.5.16 (2007-06-09) Status: RO On Sat, Jan 24, 2009 at 07:37:29PM +0000, John Hartnup wrote: > Hi. > > I'm working through Real World Haskell, and although it's going well > (I just finished the exercise to write a glob matcher without using a > regex library, and I'm pleased as punch), I keep seeing the ($) > operator, and I'm not sure I understand its use. If the book explains > it, I've been unable to find it. > > Empirically, it seems like: > a $ b c d e f > .. is equivalent to .. > a (b c d e f) > > But is that it's only purpose? To placate the LISP haters by removing > parentheses? > > (1 +) 2 does the same thing as (1 +) $ 2, and has the same type. > > Am I missing something? > > Thanks, > John > > > -- > "There is no way to peace; peace is the way" > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners maybe can this answer your question: A: ((==) True) (1 == 1) -- won't work: ((==) True) 1 == 1 => ((==) True) ((==) 1 1) -- won't work: ((==) True) (==) 1 1 => ((==) True) $ (==) 1 1 => ((==) True) $ 1 == 1 Regards ----- End forwarded message ----- From byorgey at seas.upenn.edu Sat Jan 24 17:52:37 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sat Jan 24 17:43:15 2009 Subject: [Haskell-beginners] ($) operator In-Reply-To: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> References: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> Message-ID: <20090124225237.GA13950@seas.upenn.edu> On Sat, Jan 24, 2009 at 07:37:29PM +0000, John Hartnup wrote: > Hi. > > I'm working through Real World Haskell, and although it's going well > (I just finished the exercise to write a glob matcher without using a > regex library, and I'm pleased as punch), I keep seeing the ($) > operator, and I'm not sure I understand its use. If the book explains > it, I've been unable to find it. > > Empirically, it seems like: > a $ b c d e f > .. is equivalent to .. > a (b c d e f) > > But is that it's only purpose? To placate the LISP haters by removing > parentheses? > > (1 +) 2 does the same thing as (1 +) $ 2, and has the same type. > > Am I missing something? More generally, in a language with first-class and higher-order functions like Haskell, it's simply useful to have a function which performs function application. For example, one place that ($) comes in handy is when applying each function in a list of functions to a single input value. Using ($) you can just write something like map ($5) [(+1), (^2), abs] which evaluates to [6,25,5]. -Brent From dcmorse at gmail.com Sun Jan 25 00:25:29 2009 From: dcmorse at gmail.com (David Morse) Date: Sun Jan 25 00:16:10 2009 Subject: [Haskell-beginners] ($) operator In-Reply-To: <20090124225237.GA13950@seas.upenn.edu> References: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> <20090124225237.GA13950@seas.upenn.edu> Message-ID: <11f192740901242125l22a7d8f1i9ccf0bd9dbcf33f2@mail.gmail.com> They definitely dropped the ball on introducing '$'. I think you just hit the seam between two of the authors, and it fell through the cracks. From jakubuv at gmail.com Sun Jan 25 07:45:03 2009 From: jakubuv at gmail.com (Jan Jakubuv) Date: Sun Jan 25 07:35:40 2009 Subject: [Haskell-beginners] ($) operator In-Reply-To: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> References: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> Message-ID: 2009/1/24 John Hartnup : > > But is that it's only purpose? To placate the LISP haters by removing > parentheses? > Also one important difference is that the standard application operator (space) associates to the left while $ associates to the right. It says how missing parenthesis are filled in. For example (a b c d e) stands for ((((a b) c) d) e) while (a $ b $ c $ d $ e) stands for (a (b (c (d e)))) Sometimes you need the former behavior sometimes the later. The $ is useful for example when an argument to an unary function is itself a function application. For example you can write filter (<4) $ map (+1) $ [100,99,1,2,3,4] In this case you can think of $ to be like a "unix pipe". Sincerely, jan. From schwidom at gmx.net Sun Jan 25 09:25:03 2009 From: schwidom at gmx.net (Frank Schwidom) Date: Sun Jan 25 08:16:34 2009 Subject: [Haskell-beginners] ($) operator In-Reply-To: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> References: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> Message-ID: <20090125142503.GA4525@BigBox> On Sat, Jan 24, 2009 at 07:37:29PM +0000, John Hartnup wrote: > Hi. > > I'm working through Real World Haskell, and although it's going well > (I just finished the exercise to write a glob matcher without using a > regex library, and I'm pleased as punch), I keep seeing the ($) > operator, and I'm not sure I understand its use. If the book explains > it, I've been unable to find it. > > Empirically, it seems like: > a $ b c d e f > .. is equivalent to .. > a (b c d e f) > > But is that it's only purpose? To placate the LISP haters by removing > parentheses? > > (1 +) 2 does the same thing as (1 +) $ 2, and has the same type. > > Am I missing something? > > Thanks, > John I made some Examples for better understanding: -- creating an $ like function: f g x = (g x) -- some tests comparing $ with f: 5 == ($ 2) (+ 3) 5 == (`f` 2) (+ 3) 5 == (\x -> (($) x 2)) (+ 3) 5 == (\x -> (f x 2)) (+ 3) Regards From byorgey at seas.upenn.edu Sun Jan 25 09:12:06 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Jan 25 09:02:43 2009 Subject: [Haskell-beginners] ($) operator In-Reply-To: <6c1ba2fc0901242134i36e38fd6od9f5cf24fc6a075c@mail.gmail.com> References: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> <20090124225237.GA13950@seas.upenn.edu> <6c1ba2fc0901242134i36e38fd6od9f5cf24fc6a075c@mail.gmail.com> Message-ID: <20090125141206.GA18997@seas.upenn.edu> On Sun, Jan 25, 2009 at 05:34:35AM +0000, John Hartnup wrote: > 2009/1/24 Brent Yorgey : > > > > > map ($5) [(+1), (^2), abs] > > > > which evaluates to [6,25,5]. > > > > Just to check I understand correctly - you're using ($) to 'promote' > an expression into a function, in order that it may be used in higher > order functions? In this case, I'm using ($) to *make* a higher-order function---($5) is a function which takes its argument (which must be a function) and applies it to 5. (I'm assuming you're familiar with 'operator sections', if you aren't I can explain that too.) -Brent From bayer at cpw.math.columbia.edu Sun Jan 25 09:13:41 2009 From: bayer at cpw.math.columbia.edu (Dave Bayer) Date: Sun Jan 25 09:04:17 2009 Subject: [Haskell-beginners] ($) operator In-Reply-To: <11f192740901242125l22a7d8f1i9ccf0bd9dbcf33f2@mail.gmail.com> References: <6c1ba2fc0901241137x242cf4b4w2398896af45ae694@mail.gmail.com> <20090124225237.GA13950@seas.upenn.edu> <11f192740901242125l22a7d8f1i9ccf0bd9dbcf33f2@mail.gmail.com> Message-ID: 2009/1/24 John Hartnup : > But is that it's only purpose? To placate the LISP haters by removing > parentheses? On Jan 25, 2009, at 12:25 AM, David Morse wrote: > They definitely dropped the ball on introducing '$'. I think you just > hit the seam between two of the authors, and it fell through the > cracks. Haskell isn't Cobol, but in comparison with the lambda calculus, it flows a bit better like a natural language. '$' helps with this. For example, in the line > mempty = en $ en [] ...one clearly doesn't need to use $, parenthesizing (en []) has the same meaning. However, reading left-to-right, the $ coaxes one into dropping top-down into a new view of the line, partially abstracting out or forgetting what came before, without having to maintain a mental stack and brace oneself for the closing ). I've read books on numeracy and vision, that present the same conclusion: As our brain evolved new systems for seeing or counting, the old systems didn't get thrown out, they got buried by the new layers, but they're still wired in. Part of our reaction to a line of lisp that ends in seven )))))) is no different than a pigeon or a horse seeing the same number of objects; we're not sure. Then for us a new linguistic layer kicks in, "I can see two groups of three, that's even" and we rise above the animals, but our single conscious core got hijacked to sort this out. People take the ergonomics of cockpit design very seriously, to reduce the cognitive load on pilots in emergencies. On Apollo 13, they nearly blew it by flipping a switch the wrong way. I fly a lot, so I'm very grateful that the "purists" that gravitate to math and computer science aren't instead in ergonomic design. I actually love lisp, or more precisely Scheme. I came back to Haskell for strong typing and class abstractions; Haskell more directly supports making a theory about what one is coding. In order to use Scheme, I had to defang it of its parentheses. I didn't believe that any of the web proposals for this saw actual use, so I rolled my own preprocessor, using indentation to indicate outline structure, and using '|' roughly as Haskell uses '$'. There are other issues one inevitably faces, e.g. missing starts to outline levels, but I came to love '$' as Haskell uses it. Some people develop a point-free style in Haskell, e.g. > blah foo . blah . blah foo foo . blah and different people write code that piles up uses of '$' e.g. > blah foo $ blah $ blah foo foo $ blah With decent syntax coloring the second line can be given as light a touch as the first. Ultimately, '$' helps mitigate a left / right tension in Haskell that exists in all languages, and in algebra itself. In algebra, "f g" can mean either "f then g" or "g then f". It means "g then f" in any situation crippled by the ancestry of the function composition "f(g(x))", and it means "f then g" any time one has the free choice of easier ergonomics in a culture that reads left to right. Quick, ten times, work out out the permutation cycle product > (1 2 3) (2 3 4 5) (3 4 5 6) (4 5 6 2) (5 6 1 2) (1 2 3) (2 3 4 5) > (3 4 5 6) (4 5 6 2) (5 6 1 2) under each assumption for the order of operations. One wraps around through parentheses either way, but using the "f then g" convention, all other scanning is consistently left to right, not flitting back and forth like a deranged water bug. Now try composing a complex set of type signatures for Haskell functions. Do you feel like a deranged water bug? The arrows go the wrong way, don't they! You'd be playing a nice game of dominoes, canceling off neighbors and so forth, if the arrows went the other way. So Haskell doesn't have its left / right tension completely worked out, but I'd say '$' isn't part of the problem, it's part of the solution. From matthewjwilliams1 at googlemail.com Sun Jan 25 19:04:48 2009 From: matthewjwilliams1 at googlemail.com (Matthew J. Williams) Date: Sun Jan 25 18:55:07 2009 Subject: [Haskell-beginners] Calculating Time Complexity Message-ID: <497cfe10.0c53300a.065a.ffff8599@mx.google.com> Dear all, In general terms, how would one calculate the time complexity of a given algorithm? Feel free to make use of my pseudo code in your answer: /* input: 2-D array A of size n by n output: a number max */ Max := 0 For i := 1 to n sum := 0 For j := 1 to n sum := sum + A[i][j] End for If sum > max then max := sum End for Output max Sincerely Matthew J. Williams From gtener at gmail.com Sun Jan 25 19:51:51 2009 From: gtener at gmail.com (=?UTF-8?Q?Krzysztof_Skrz=C4=99tnicki?=) Date: Sun Jan 25 19:42:26 2009 Subject: [Haskell-beginners] Calculating Time Complexity In-Reply-To: <497cfe10.0c53300a.065a.ffff8599@mx.google.com> References: <497cfe10.0c53300a.065a.ffff8599@mx.google.com> Message-ID: <220e47b40901251651j1af2c6afteeb2e10b52f19f25@mail.gmail.com> On Mon, Jan 26, 2009 at 01:04, Matthew J. Williams < matthewjwilliams1@googlemail.com> wrote: > Dear all, > > In general terms, how would one calculate the time complexity of a given > algorithm? I would count most significant operations. The result is Theta(n^2) (see http://en.wikipedia.org/wiki/Big_O_notation for definition of Big Theta notation). Feel free to make use of my pseudo code in your answer: > > /* input: > 2-D array A of size n by n > output: a number max */ > Max := 0 > For i := 1 to n > sum := 0 > For j := 1 to n > sum := sum + A[i][j] > End for > If sum > max then max := sum > End for > Output max > > Christopher Skrz?tnicki -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090126/6e10550a/attachment-0001.htm From aneumann at inf.fu-berlin.de Mon Jan 26 02:31:48 2009 From: aneumann at inf.fu-berlin.de (Adrian Neumann) Date: Mon Jan 26 02:22:41 2009 Subject: [Haskell-beginners] Calculating Time Complexity In-Reply-To: <497cfe10.0c53300a.065a.ffff8599@mx.google.com> References: <497cfe10.0c53300a.065a.ffff8599@mx.google.com> Message-ID: <643BC7F7-E42E-492F-AB4D-FEC7FD35C540@inf.fu-berlin.de> With iterative algorithms like the one you posted it's usually reduced to "count the loops". Here we have two nested for-loops, each going from 1 to n. In each loop we do some constant amount of work, so we get (c1*n)*(c2*n) = (c1*c2)*n^2 -> Theta(n^2). With recursion it's usually a bit more complicated, as you have to find a closed form. There are however nice lemmata you can use, like the http://en.wikipedia.org/wiki/Master_theorem Regards, Adrian Am 26.01.2009 um 01:04 schrieb Matthew J. Williams: > Dear all, > > In general terms, how would one calculate the time complexity of a > given algorithm? Feel free to make use of my pseudo code in your > answer: > > /* input: > 2-D array A of size n by n > output: a number max */ > Max := 0 > For i := 1 to n > sum := 0 > For j := 1 to n > sum := sum + A[i][j] > End for > If sum > max then max := sum > End for > Output max > > Sincerely > Matthew J. Williams > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 194 bytes Desc: Signierter Teil der Nachricht Url : http://www.haskell.org/pipermail/beginners/attachments/20090126/c4a806e2/PGP.bin From martin.hofmann at uni-bamberg.de Mon Jan 26 04:33:36 2009 From: martin.hofmann at uni-bamberg.de (Martin Hofmann) Date: Mon Jan 26 04:20:32 2009 Subject: [Haskell-beginners] deleteM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a) Message-ID: <1232962416.6142.14.camel@ios.cogsys.wiai.uni-bamberg.de> I often come across the problem to insert into a collection which might not exist yet, or delete from it and want the collection to be deleted if it is empty afterwards. I always end up with these two functions: deleteM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a) deleteM e s = liftM (S.delete e) s >>= \s' -> if S.null s' then return s' else Nothing insertM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a) insertM e s = case s of (Just s') -> return $ S.insert e s' Nothing -> return $ S.insert S.empty Is there a way to express each in a (polymorphic) point-free one-liner? If not, why isn't there such a function for the standard collection, because IMHO this is what you need when using 'alter'. Thanks, Martin From apfelmus at quantentunnel.de Mon Jan 26 05:22:51 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Mon Jan 26 05:12:57 2009 Subject: [Haskell-beginners] Re: deleteM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a) In-Reply-To: <1232962416.6142.14.camel@ios.cogsys.wiai.uni-bamberg.de> References: <1232962416.6142.14.camel@ios.cogsys.wiai.uni-bamberg.de> Message-ID: Martin Hofmann wrote: > I often come across the problem to insert into a collection which might > not exist yet, or delete from it and want the collection to be deleted > if it is empty afterwards. > > I always end up with these two functions: > > > deleteM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a) > deleteM e s = > liftM (S.delete e) s >>= \s' -> > if S.null s' then return s' else Nothing > > insertM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a) > insertM e s = > case s of > (Just s') -> return $ S.insert e s' > Nothing -> return $ S.insert S.empty > > Is there a way to express each in a (polymorphic) point-free one-liner? > If not, why isn't there such a function for the standard collection, > because IMHO this is what you need when using 'alter'. Yes, there is a way. :) deleteM e = (\s -> if S.null s then Just s else Nothing) . S.delete e insertM e = Just . S.insert e . maybe S.empty id The maybe function is from Data.Maybe . I did wonder why you want to delete the empty set, but now I see that you need it for alter . Regards, apfelmus -- http://apfelmus.nfshost.com From byorgey at seas.upenn.edu Mon Jan 26 07:41:41 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Jan 26 07:32:14 2009 Subject: [Haskell-beginners] Calculating Time Complexity In-Reply-To: <497cfe10.0c53300a.065a.ffff8599@mx.google.com> References: <497cfe10.0c53300a.065a.ffff8599@mx.google.com> Message-ID: <20090126124141.GA11954@seas.upenn.edu> On Mon, Jan 26, 2009 at 12:04:48AM +0000, Matthew J. Williams wrote: > Dear all, > > In general terms, how would one calculate the time complexity of a given > algorithm? Feel free to make use of my pseudo code in your answer: > > /* input: > 2-D array A of size n by n > output: a number max */ > Max := 0 > For i := 1 to n > sum := 0 > For j := 1 to n > sum := sum + A[i][j] > End for > If sum > max then max := sum > End for > Output max This being a Haskell mailing list, I couldn't help also translating this code into simple Haskell: maxRowSum :: (Num a, Ord a) => [[a]] -> a maxRowSum = maximum . map sum In this form it's a little harder to see how many operations are being done (and hence the time complexity), however! -Brent From alan.cameron at iname.com Mon Jan 26 17:22:05 2009 From: alan.cameron at iname.com (Alan Cameron) Date: Mon Jan 26 17:12:27 2009 Subject: [Haskell-beginners] Follow up to reference request Message-ID: Hi, I am indebted to Andrew Wagner for pointing me in the direction of the book http://book.realworldhaskell.org/read/ Which I now have time to study. Everything was going fine until I got to the section in Getting Started where it gives A Simple Program. Now as someone who is used to the Windows environment CLI is not my forte. Following instructions which appear to be incomplete I created a file of the program WC.hs but where should it go? I tried various places until I reread the :? For the :cd command. Ah I said that's what I need to do put it in a folder and change the Dir. Now I can find the file with the :edit command. Did the same with the file quux.txt same place. Now run the command $ runghc WC < quux.txt :1:0: parse error on input '$' What have I done wrong or not done? It does say "at a shell or command prompt" what's that?? I reverted to the installation instructions provided by GHC for Windows. 2.2 Installing on Windows 2.2.1 Installing GHC on Windows Checked all that had been done correctly. Enter the program line 1> bash$ cat main.hs :1:0: parse error on input '$' Now bash looks like a modified prompt?? So what is happening? Regards to all and TIA for reply. Alan Cameron From wagner.andrew at gmail.com Mon Jan 26 17:44:58 2009 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Mon Jan 26 17:35:47 2009 Subject: [Haskell-beginners] Follow up to reference request In-Reply-To: References: Message-ID: <65C14BA6-C0AC-49C5-898B-D301F70CB0C5@gmail.com> Alan, I'd love to help you get started coding in haskell. It sounds like it might be easier to do interactively though. Can you get on the #haskell channel on IRC? I'm in and out of there as chessguy and will be on later tonight. On Jan 26, 2009, at 5:22 PM, "Alan Cameron" wrote: > Hi, > > I am indebted to Andrew Wagner for pointing me in the direction of > the book > http://book.realworldhaskell.org/read/ > Which I now have time to study. Everything was going fine until I > got to the > section in Getting Started where it gives A Simple Program. > > Now as someone who is used to the Windows environment CLI is not my > forte. > Following instructions which appear to be incomplete I created a > file of the > program WC.hs but where should it go? > > I tried various places until I reread the :? For the :cd command. > Ah I said that's what I need to do put it in a folder and change the > Dir. > > Now I can find the file with the :edit command. > Did the same with the file quux.txt same place. > > Now run the command $ runghc WC < quux.txt > > :1:0: parse error on input '$' > > What have I done wrong or not done? > > It does say "at a shell or command prompt" what's that?? > > I reverted to the installation instructions provided by GHC for > Windows. > 2.2 Installing on Windows > 2.2.1 Installing GHC on Windows > > Checked all that had been done correctly. > > Enter the program line 1> > > bash$ cat main.hs > :1:0: parse error on input '$' > > Now bash looks like a modified prompt?? > So what is happening? > > Regards to all and TIA for reply. > > Alan Cameron > > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From dpfrey at shaw.ca Mon Jan 26 17:59:19 2009 From: dpfrey at shaw.ca (David Frey) Date: Mon Jan 26 17:49:52 2009 Subject: [Haskell-beginners] Follow up to reference request In-Reply-To: Message-ID: On 1/26/2009, "Alan Cameron" wrote: >Hi, > >I am indebted to Andrew Wagner for pointing me in the direction of the book >http://book.realworldhaskell.org/read/ >Which I now have time to study. Everything was going fine until I got to the >section in Getting Started where it gives A Simple Program. > >Now as someone who is used to the Windows environment CLI is not my forte. >Following instructions which appear to be incomplete I created a file of the >program WC.hs but where should it go? Put it in any directory you want, but I would suggest putting it in a directory named "Chapter 1" inside another directory named "Real World Haskell". >I tried various places until I reread the :? For the :cd command. >Ah I said that's what I need to do put it in a folder and change the Dir. > >Now I can find the file with the :edit command. >Did the same with the file quux.txt same place. It's probably easier to just use the Windows GUI to browse to your Haskell sources and open them directly in the editor. > >Now run the command $ runghc WC < quux.txt > >:1:0: parse error on input '$' > >What have I done wrong or not done? The '$' character is not actually part of the command. It's just written in the book so that you know that what follows is a command that you should type into the command line. So: $ ghci File.hs means 1) Open a console, (terminal, command line prompt or whatever you want to call it) 2) Use the cd command to go into that directory containing File.hs 3) Type (without quotes) "ghci File.hs" and press enter. Similarly, ghci> 2 + 3 means type "2 + 3" followed by enter. I hope that clears things up a bit. From poliquin at softcomp.com Tue Jan 27 12:42:54 2009 From: poliquin at softcomp.com (Tom Poliquin) Date: Tue Jan 27 13:11:49 2009 Subject: [Haskell-beginners] Function Type Confusion .. Message-ID: <200901270942.54234.poliquin@softcomp.com> I was reading "Arrows and Computation" http://www.soi.city.ac.uk/~ross/papers/fop.ps.gz (trying to lose my 'beginner' status) when I saw (on page one) add :: (b -> Int) -> (b -> Int) -> (b -> Int) add f g b = f b + g b It seemed like the type definition was wrong (short at least). I tried it anyway .. module Main where add :: (b -> Int) -> (b -> Int) -> (b -> Int) add f g b = f b + g b main = do x <- return $ add (+2) (+3) 7 print x The program compiles and runs and produces '19' ! For fun I loaded into ghci and got what I believe is the proper type .. *Main> :t add add :: (b -> Int) -> (b -> Int) -> b -> Int When I try the same thing with something simpler (leaving a bit off the type definition) I get the expected error (by me) .. module Main where dog :: Int -> Int dog a b = a + b main = do x <- return $ dog 2 3 print x Main.hs:5:0: The equation(s) for `dog' have two arguments, but its type `Int -> Int' has only one What am I missing? .. Apparently something fundamental about type definitions .. Any help appreciated. Tom From gale at sefer.org Tue Jan 27 13:31:23 2009 From: gale at sefer.org (Yitzchak Gale) Date: Tue Jan 27 13:21:52 2009 Subject: [Haskell-beginners] Function Type Confusion .. In-Reply-To: <200901270942.54234.poliquin@softcomp.com> References: <200901270942.54234.poliquin@softcomp.com> Message-ID: <2608b8a80901271031l7d44ec42r7afbcc21d3401445@mail.gmail.com> Tom Poliquin wrote: > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > add f g b = f b + g b > > The program compiles and runs and produces '19' ! > > For fun I loaded into ghci and got what I believe is the proper > type .. > > *Main> :t add > add :: (b -> Int) -> (b -> Int) -> b -> Int > > When I try the same thing with something simpler > (leaving a bit off the type definition) > I get the expected error (by me) .. In type expressions, the symbol -> is right-associative. So ... -> (b -> Int) is exactly the same as ... -> b -> Int -Yitz From mail at paulvisschers.net Tue Jan 27 13:33:35 2009 From: mail at paulvisschers.net (Paul Visschers) Date: Tue Jan 27 13:24:07 2009 Subject: [Haskell-beginners] Function Type Confusion .. In-Reply-To: <200901270942.54234.poliquin@softcomp.com> References: <200901270942.54234.poliquin@softcomp.com> Message-ID: <497F537F.4020009@paulvisschers.net> The trick is this: add :: (b -> Int) -> (b -> Int) -> (b -> Int) is equal to add :: (b -> Int) -> (b -> Int) -> b -> Int This is because the function arrow is right-associative. Reading the function type in the latter way, you can then look at add f g b = f b + g b in a new way. f has type (b -> Int), g also has this type. The b has type b and the function result is an Int. Intuitively you can look at this function in two ways, as a function that takes two functions as arguments and then returns a function, or as a function that takes two functions and a value, and then returns a value. (You can take one more step and see it as a function that takes one argument (of type b -> Int) and then returns a function of type (b -> Int) -> b -> Int.) Similarly the function can be defined as: add f g = \b -> f b + g b which is a more direct implementation of the first type you gave. It's all equivalent though. It's actually pretty cool when you get used to it. Paul Tom Poliquin wrote: > I was reading "Arrows and Computation" > > http://www.soi.city.ac.uk/~ross/papers/fop.ps.gz > > (trying to lose my 'beginner' status) when I saw (on page > one) > > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > add f g b = f b + g b > > It seemed like the type definition was wrong (short at least). > > I tried it anyway .. > > module Main where > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > add f g b = f b + g b > main = do > x <- return $ add (+2) (+3) 7 > print x > > The program compiles and runs and produces '19' ! > > For fun I loaded into ghci and got what I believe is the proper > type .. > > *Main> :t add > add :: (b -> Int) -> (b -> Int) -> b -> Int > > > When I try the same thing with something simpler > (leaving a bit off the type definition) > I get the expected error (by me) .. > > module Main where > dog :: Int -> Int > dog a b = a + b > > main = do > x <- return $ dog 2 3 > print x > > Main.hs:5:0: > The equation(s) for `dog' have two arguments, > but its type `Int -> Int' has only one > > What am I missing? .. Apparently something fundamental > about type definitions .. > > Any help appreciated. > > Tom > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From tom.davie at gmail.com Tue Jan 27 13:32:04 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Tue Jan 27 13:25:43 2009 Subject: [Haskell-beginners] Function Type Confusion .. In-Reply-To: <200901270942.54234.poliquin@softcomp.com> References: <200901270942.54234.poliquin@softcomp.com> Message-ID: On 27 Jan 2009, at 18:42, Tom Poliquin wrote: > > I was reading "Arrows and Computation" > > http://www.soi.city.ac.uk/~ross/papers/fop.ps.gz > > (trying to lose my 'beginner' status) when I saw (on page > one) > > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > add f g b = f b + g b > > It seemed like the type definition was wrong (short at least). > > I tried it anyway .. > > module Main where > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > add f g b = f b + g b > main = do > x <- return $ add (+2) (+3) 7 > print x > > The program compiles and runs and produces '19' ! > > For fun I loaded into ghci and got what I believe is the proper > type .. > > *Main> :t add > add :: (b -> Int) -> (b -> Int) -> b -> Int > > > When I try the same thing with something simpler > (leaving a bit off the type definition) > I get the expected error (by me) .. > > module Main where > dog :: Int -> Int > dog a b = a + b > > main = do > x <- return $ dog 2 3 > print x > > Main.hs:5:0: > The equation(s) for `dog' have two arguments, > but its type `Int -> Int' has only one > > What am I missing? .. Apparently something fundamental > about type definitions .. What you're observing is "currying" at work When in Haskell we write the type a -> b, we mean "a function, which accepts items of type 'a', and returns items of type 'b'". Importantly, the -> type operator is right associative. Now, when we say a -> b -> c, right associativity of -> means that this *really* is a -> (b -> c), so, our function takes a single argument, of type a, and produces a new function, which accepts a single argument of type b, and produces something of type c. We can see this at work, lets define this function: f = (+ 1) plus gets applied to a single argument, and returns a new function. We can investigate the type of the new function 'f', and discover that it's a => a -> a ? it takes a single numeric argument, and returns something of the same type. Now lets go back and look at your examples: You expected the type of add to be (b -> Int) -> (b -> Int) -> b -> Int, but instead saw the type signature (b -> Int) -> (b -> Int) -> (b -> Int). *but*, thanks to right associativity, those two types are equal! The only reason it's written with parentheses is that the author is trying to draw your eye to the fact that it's a "function transformer" ? it takes two functions, and produces a new function based on them. Your dog function gives you an error, because indeed, it takes one argument (a), and returns a new function, which accepts another argument (b), and returns a + b. Thus, it's type signature is Int -> (Int -> Int), which can be written without parentheses as Int -> Int - > Int. Hope that helps Bob From byorgey at seas.upenn.edu Tue Jan 27 13:39:20 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Tue Jan 27 13:29:48 2009 Subject: [Haskell-beginners] Function Type Confusion .. In-Reply-To: <200901270942.54234.poliquin@softcomp.com> References: <200901270942.54234.poliquin@softcomp.com> Message-ID: <20090127183920.GA20307@seas.upenn.edu> On Tue, Jan 27, 2009 at 09:42:54AM -0800, Tom Poliquin wrote: > > I was reading "Arrows and Computation" > > http://www.soi.city.ac.uk/~ross/papers/fop.ps.gz > > (trying to lose my 'beginner' status) when I saw (on page > one) > > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > add f g b = f b + g b > > It seemed like the type definition was wrong (short at least). Hi Tom, that's a great paper to read! I think your confusion seems to stem from this simple fact: every function in Haskell only takes one argument. Functions that look like they take multiple arguments, for example add :: Int -> Int -> Int add x y = x + y are really one-argument functions which return functions. In the above example, 'add' is a function which takes a single Int, and returns a function as output. This output function also takes a single Int and finally returns an Int. Observe: Prelude> let add x y = (x + y :: Int) Prelude> :t add add :: Int -> Int -> Int Prelude> :t add 3 add 3 :: Int -> Int Prelude> :t (add 3) 5 (add 3) 5 :: Int Prelude> (add 3) 5 8 Prelude> add 3 5 8 So we could also write the type of 'add' like this: add :: Int -> (Int -> Int) and in fact, this add's real type. Int -> Int -> Int is just an abbreviation; -> associates to the right, so we can omit parentheses that occur at the rightmost end of a type. As you can see above, by the same token, function application associates to the left, so 'add 3 5' is really just an abbreviation for '(add 3) 5': ie., first apply 'add' to 3, obtaining another function as output, then apply that function to 5. By now I'm sure you can see that (b -> Int) -> (b -> Int) -> (b -> Int) is exactly the same type as (b -> Int) -> (b -> Int) -> b -> Int. You can think of something of this type *either* as something which takes two arguments of type (b -> Int) and returns a function of type (b -> Int); *or* as something which takes three arguments, two of type (b -> Int) and one of type b, and returns something of type Int; these are in fact just two different ways to think about the same thing. Hope that is helpful! -Brent From poliquin at softcomp.com Tue Jan 27 13:47:40 2009 From: poliquin at softcomp.com (Tom Poliquin) Date: Tue Jan 27 14:16:37 2009 Subject: [Haskell-beginners] Function Type Confusion .. In-Reply-To: <20090127183920.GA20307@seas.upenn.edu> References: <200901270942.54234.poliquin@softcomp.com> <20090127183920.GA20307@seas.upenn.edu> Message-ID: <200901271047.40920.poliquin@softcomp.com> On Tue, Jan 27, 2009 at 09:42:54AM -0800, Tom Poliquin wrote: > > I was reading "Arrows and Computation" > > http://www.soi.city.ac.uk/~ross/papers/fop.ps.gz > > (trying to lose my 'beginner' status) when I saw (on page > one) > > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > add f g b = f b + g b > > It seemed like the type definition was wrong (short at least). > ..... > The trick is this: > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > is equal to > add :: (b -> Int) -> (b -> Int) -> b -> Int Wow! .. Thanks everyone for the fast and informative responses. I get it now. I'm an old time imperative (C, Java, etc) programmer and I find Haskell incredibly powerful ... and fun! Now I can move on to page two in "Arrows and Computation" .. Thanks again .. Tom On Tuesday 27 January 2009 10:39, Brent Yorgey wrote: > On Tue, Jan 27, 2009 at 09:42:54AM -0800, Tom Poliquin wrote: > > I was reading "Arrows and Computation" > > > > http://www.soi.city.ac.uk/~ross/papers/fop.ps.gz > > > > (trying to lose my 'beginner' status) when I saw (on page > > one) > > > > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > > add f g b = f b + g b > > > > It seemed like the type definition was wrong (short at least). > > Hi Tom, that's a great paper to read! I think your confusion seems to > stem from this simple fact: every function in Haskell only takes one > argument. > > Functions that look like they take multiple arguments, for example > > add :: Int -> Int -> Int > add x y = x + y > > are really one-argument functions which return functions. In the > above example, 'add' is a function which takes a single Int, and > returns a function as output. This output function also takes a > single Int and finally returns an Int. Observe: > > Prelude> let add x y = (x + y :: Int) > Prelude> :t add > add :: Int -> Int -> Int > Prelude> :t add 3 > add 3 :: Int -> Int > Prelude> :t (add 3) 5 > (add 3) 5 :: Int > Prelude> (add 3) 5 > 8 > Prelude> add 3 5 > 8 > > So we could also write the type of 'add' like this: > > add :: Int -> (Int -> Int) > > and in fact, this add's real type. Int -> Int -> Int is just an > abbreviation; -> associates to the right, so we can omit parentheses > that occur at the rightmost end of a type. As you can see above, by > the same token, function application associates to the left, so 'add 3 > 5' is really just an abbreviation for '(add 3) 5': ie., first apply > 'add' to 3, obtaining another function as output, then apply that > function to 5. > > By now I'm sure you can see that > > (b -> Int) -> (b -> Int) -> (b -> Int) > > is exactly the same type as > > (b -> Int) -> (b -> Int) -> b -> Int. > > You can think of something of this type *either* as something which > takes two arguments of type (b -> Int) and returns a function of type > (b -> Int); *or* as something which takes three arguments, two of type > (b -> Int) and one of type b, and returns something of type Int; these > are in fact just two different ways to think about the same thing. > > Hope that is helpful! > -Brent > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From byorgey at seas.upenn.edu Tue Jan 27 14:29:22 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Tue Jan 27 14:19:51 2009 Subject: [Haskell-beginners] Function Type Confusion .. In-Reply-To: <200901271047.40920.poliquin@softcomp.com> References: <200901270942.54234.poliquin@softcomp.com> <20090127183920.GA20307@seas.upenn.edu> <200901271047.40920.poliquin@softcomp.com> Message-ID: <20090127192922.GA22185@seas.upenn.edu> On Tue, Jan 27, 2009 at 10:47:40AM -0800, Tom Poliquin wrote: > > On Tue, Jan 27, 2009 at 09:42:54AM -0800, Tom Poliquin wrote: > > > > I was reading "Arrows and Computation" > > > > http://www.soi.city.ac.uk/~ross/papers/fop.ps.gz > > > > (trying to lose my 'beginner' status) when I saw (on page > > one) > > > > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > > add f g b = f b + g b > > > > It seemed like the type definition was wrong (short at least). > > > ..... > > > The trick is this: > > add :: (b -> Int) -> (b -> Int) -> (b -> Int) > > is equal to > > add :: (b -> Int) -> (b -> Int) -> b -> Int > > Wow! .. Thanks everyone for the fast and informative responses. > > I get it now. > > I'm an old time imperative (C, Java, etc) programmer and > I find Haskell incredibly powerful ... and fun! > > Now I can move on to page two in "Arrows and Computation" .. > > Thanks again .. > > Tom Great! Have fun. I can guarantee you'll have more questions, so feel free to ask more on this list, or for quick questions there's also the #haskell IRC channel on freenode.net, which is another great place to learn and ask questions. -Brent From erickgc at instec.cu Tue Jan 27 22:33:45 2009 From: erickgc at instec.cu (=?iso-8859-1?Q?Erick_Gonz=E1lez?=) Date: Tue Jan 27 21:22:51 2009 Subject: [Haskell-beginners] To use random number monad inside function Message-ID: <002801c980f9$532426e0$0b08a8c0@usuario> Hi: Haskell' s way of random number generation is strange to me, but I know how to do that. I' d like to know how can I call random numbers generated on the screen inside a classic function. I mean, I need to know the way of calling random numbers (one different every time that I run) inside a function. Please, Could anybody help me? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090127/97ba2776/attachment.htm From dpfrey at shaw.ca Tue Jan 27 22:50:52 2009 From: dpfrey at shaw.ca (David Frey) Date: Tue Jan 27 22:41:20 2009 Subject: [Haskell-beginners] To use random number monad inside function In-Reply-To: <002801c980f9$532426e0$0b08a8c0@usuario> References: <002801c980f9$532426e0$0b08a8c0@usuario> Message-ID: <460fe639f54986d45be91eb9d016e626@localhost> On Tue, 27 Jan 2009 21:33:45 -0600, Erick Gonz?lez wrote: > Hi: > Haskell' s way of random number generation is strange to me, but I know > how to do that. I' d like to know how can I call random numbers generated > on the screen inside a classic function. I mean, I need to know the way of > calling random numbers (one different every time that I run) inside a > function. Please, Could anybody help me? > Thanks I'm not sure exactly what you're trying to get at, but if you were hoping to implement something like this: multiplyByRandom :: Int -> Int multiplyByRandom n = n * {- Get random number somehow -} That is not how things are done. Instead, you would do something like this: import System.Random (randomIO) multiplyByRandom :: Int -> IO Int multiplyByRandom n = do rand <- randomIO return (n * rand) When you said "classic function", did you mean pure function? http://en.wikipedia.org/wiki/Pure_function From gtener at gmail.com Tue Jan 27 22:57:41 2009 From: gtener at gmail.com (=?UTF-8?Q?Krzysztof_Skrz=C4=99tnicki?=) Date: Tue Jan 27 22:48:09 2009 Subject: [Haskell-beginners] To use random number monad inside function In-Reply-To: <002801c980f9$532426e0$0b08a8c0@usuario> References: <002801c980f9$532426e0$0b08a8c0@usuario> Message-ID: <220e47b40901271957w4ae70949uc6c43414966df9bc@mail.gmail.com> You need to store random generator seed somewhere and keep track of updated value after calling randomness-related functions.You can try doing it manually, but what really fits here is monad that keeps track of that seed value. Good news is: there is already package with such monad on Hackage. In particular, try package MonadRandom ( http://hackage.haskell.org/cgi-bin/hackage-scripts/package/MonadRandom-0.1.3 ). If you have cabal-install, you can simply get it with "cabal install monadrandom" (and if you don't have cabal-install, you should get this wonderful tool right now!). There are some examples within the documentation here: http://hackage.haskell.org/packages/archive/MonadRandom/0.1.3/doc/html/Control-Monad-Random.html#1 All best Christopher Skrz?tnicki On Wed, Jan 28, 2009 at 04:33, Erick Gonz?lez wrote: > Hi: > Haskell' s way of random number generation is strange to me, but I know how > to do that. I' d like to know how can I call random numbers generated on the > screen inside a classic function. I mean, I need to know the way of calling > random numbers (one different every time that I run) inside a function. > Please, Could anybody help me? > Thanks > > _______________________________________________ > 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/20090128/96e85197/attachment-0001.htm From mle+cl at mega-nerd.com Tue Jan 27 23:07:01 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Tue Jan 27 22:57:42 2009 Subject: [Haskell-beginners] Help! Trapped in the IO Monad! Message-ID: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> Hi all, I have a list of entries for a directory (FilePaths) and I'd like to partition them into files and directories using Data.List.partition: partition :: [a] -> ([a], [a]) Now, one solution is to use unsafePerformIO: splitDirFile :: [FilePath] -> ([FilePath], [FilePath]) splitDirFile paths = do partition (\p -> unsafePerformIO (doesDirectoryExist p)) paths Two questions: a) Is it possible to do this without invoking unsafePerformIO? Ie with a function signature of say: partition :: [FilePath] -> IO ([FilePath], [FilePath]) b) Exactly how unsafe is the unsafePerformIO version? Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- The main confusion about C++ is that its practitioners think it is simultaneously a high and low level language when in reality it is good at neither. From wagner.andrew at gmail.com Tue Jan 27 23:12:07 2009 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Tue Jan 27 23:02:35 2009 Subject: [Haskell-beginners] Help! Trapped in the IO Monad! In-Reply-To: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> References: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> Message-ID: Hi Erik,The short answer to your question is to not write splitDirFile to operate on FilePaths, but on some wrapper around FilePaths that also contain information about whether each path is to a directory or a file. Then you can call splitDirFile purely. For the long, but very good, answer, see RWH, where they discuss this very specifically: http://book.realworldhaskell.org/read/io-case-study-a-library-for-searching-the-filesystem.html On Tue, Jan 27, 2009 at 11:07 PM, Erik de Castro Lopo > wrote: > Hi all, > > I have a list of entries for a directory (FilePaths) and I'd like to > partition them into files and directories using Data.List.partition: > > partition :: [a] -> ([a], [a]) > > Now, one solution is to use unsafePerformIO: > > splitDirFile :: [FilePath] -> ([FilePath], [FilePath]) > splitDirFile paths = do > partition (\p -> unsafePerformIO (doesDirectoryExist p)) paths > > Two questions: > > a) Is it possible to do this without invoking unsafePerformIO? Ie with > a function signature of say: > > partition :: [FilePath] -> IO ([FilePath], [FilePath]) > > b) Exactly how unsafe is the unsafePerformIO version? > > Erik > -- > ----------------------------------------------------------------- > Erik de Castro Lopo > ----------------------------------------------------------------- > The main confusion about C++ is that its practitioners think > it is simultaneously a high and low level language when in > reality it is good at neither. > _______________________________________________ > 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/20090127/2d55812e/attachment.htm From alexander.dunlap at gmail.com Tue Jan 27 23:14:27 2009 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Tue Jan 27 23:04:54 2009 Subject: [Haskell-beginners] Help! Trapped in the IO Monad! In-Reply-To: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> References: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> Message-ID: <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> You can do (something like; this is untested) splitDirFile :: [FilePath] -> IO ([FilePath],[FilePath]) splitDirFile [] = return ([],[]) splitDirFile (f:fs) = do (yess,nos) <- splitDirFile fs exists <- doesDirectoryExist f return $ if exists then (f:yess,nos) else (yess,f:nos) You might also look at Control.Monad.filterM. I often define a function "partitionM" which is like partition except it uses a monadic test, just like you have. Alex On Tue, Jan 27, 2009 at 8:07 PM, Erik de Castro Lopo wrote: > Hi all, > > I have a list of entries for a directory (FilePaths) and I'd like to > partition them into files and directories using Data.List.partition: > > partition :: [a] -> ([a], [a]) > > Now, one solution is to use unsafePerformIO: > > splitDirFile :: [FilePath] -> ([FilePath], [FilePath]) > splitDirFile paths = do > partition (\p -> unsafePerformIO (doesDirectoryExist p)) paths > > Two questions: > > a) Is it possible to do this without invoking unsafePerformIO? Ie with > a function signature of say: > > partition :: [FilePath] -> IO ([FilePath], [FilePath]) > > b) Exactly how unsafe is the unsafePerformIO version? > > Erik > -- > ----------------------------------------------------------------- > Erik de Castro Lopo > ----------------------------------------------------------------- > The main confusion about C++ is that its practitioners think > it is simultaneously a high and low level language when in > reality it is good at neither. > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From tom.davie at gmail.com Wed Jan 28 02:23:07 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Wed Jan 28 02:13:37 2009 Subject: [Haskell-beginners] To use random number monad inside function In-Reply-To: <002801c980f9$532426e0$0b08a8c0@usuario> References: <002801c980f9$532426e0$0b08a8c0@usuario> Message-ID: On 28 Jan 2009, at 04:33, Erick Gonz?lez wrote: > Hi: > Haskell' s way of random number generation is strange to me, but I > know how to do that. I' d like to know how can I call random numbers > generated on the screen inside a classic function. I mean, I need to > know the way of calling random numbers (one different every time > that I run) inside a function. Please, Could anybody help me? There's a problem with doing this ? Haskell guarentees that no matter what (well, okay, not quite, but unsafePerformIO doesn't count), if you give the same arguments to a function, you'll get the same results. This is known as referential transparency. This is what gets us some of the biggest gains from the language (e.g. without it, we wouldn't be allowed to use our choice of non-strict evaluation order, we wouldn't be allowed to automatically parallelise, etc). So, how is this problem solved? In a couple of interesting ways. First is the way you've already seen, we can lock random number generation in a monad (usually the IO monad). What this does, is it guarentees that the same IO action will always be returned by the function, but when that IO action gets shoved into the runtime, it can do any non-referentially transparent thing it likes, but that's "okay", because we're out of haskell land. Understandably, this isn't the nicest way to do things, because it locks us in the IO monad, and in the evaluation of the action we lose all the advantages we had. Not only that, but the programming style is fairly imperative. So, we can think of a couple of ways round the restruction ? in order to give different outputs, we must have different inputs, so lets think about a couple of ways of doing that: Firstly, we can pass a 'seed' into our pure function with which to generate further random numbers. Secondly, we can use Haskell's ability to deal with infinitely large data structures, and pass in an infinitely long list of 'random' numbers. Here's the second one: main = do seed <- do something to generate a seed interact $ pureMain . randoms $ seed pureMain :: [Int] -> String -> String pureMain rs "jam" = show (take 20 rs) Hope that helps Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090128/96a913bb/attachment.htm From apfelmus at quantentunnel.de Wed Jan 28 05:37:31 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Wed Jan 28 05:27:24 2009 Subject: [Haskell-beginners] Re: To use random number monad inside function In-Reply-To: <002801c980f9$532426e0$0b08a8c0@usuario> References: <002801c980f9$532426e0$0b08a8c0@usuario> Message-ID: Erick Gonz?lez wrote: > Hi: > > Haskell' s way of random number generation is strange to me, but > I know how to do that. I' d like to know how can I call random > numbers generated on the screen inside a classic function. I mean, I > need to know the way of calling random numbers (one different every > time that I run) inside a function. Please, Could anybody help me? > Thanks Section 3.1 of http://en.wikibooks.org/wiki/Haskell/Understanding_monads explains how to work with random numbers in Haskell. Regards, apfelmus -- http://apfelmus.nfshost.com From mle+cl at mega-nerd.com Wed Jan 28 20:18:23 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Wed Jan 28 20:09:03 2009 Subject: [Haskell-beginners] Help! Trapped in the IO Monad! In-Reply-To: <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> References: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> Message-ID: <20090129121823.c342b052.mle+cl@mega-nerd.com> Alexander Dunlap wrote: > You can do (something like; this is untested) > > splitDirFile :: [FilePath] -> IO ([FilePath],[FilePath]) > splitDirFile [] = return ([],[]) > splitDirFile (f:fs) = do > (yess,nos) <- splitDirFile fs > exists <- doesDirectoryExist f > return $ if exists > then (f:yess,nos) > else (yess,f:nos) Untested, but seems to work perfectly :-). Thanks. However, that brings me to the next stage where again I'm trapped. I would like to do a foldl' on a function that returns IO [FilePath]. I tried using Control.Monad.foldM, but then I end up with a function taht return : IO (IO ([FilePath])) which doesn't work :-). It seems pretty obvious that I could implement a recursion like Alexander did above for splitDirFile but I was wondering if there was a more general solution. Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- Heisenbugs - The bugs that go away when you turn on debugging. From alexander.dunlap at gmail.com Wed Jan 28 20:30:00 2009 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Wed Jan 28 20:20:25 2009 Subject: [Haskell-beginners] Help! Trapped in the IO Monad! In-Reply-To: <20090129121823.c342b052.mle+cl@mega-nerd.com> References: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> <20090129121823.c342b052.mle+cl@mega-nerd.com> Message-ID: <57526e770901281730j3e5e12fcs67ed6db576ec39c2@mail.gmail.com> On Wed, Jan 28, 2009 at 5:18 PM, Erik de Castro Lopo wrote: > Alexander Dunlap wrote: > >> You can do (something like; this is untested) >> >> splitDirFile :: [FilePath] -> IO ([FilePath],[FilePath]) >> splitDirFile [] = return ([],[]) >> splitDirFile (f:fs) = do >> (yess,nos) <- splitDirFile fs >> exists <- doesDirectoryExist f >> return $ if exists >> then (f:yess,nos) >> else (yess,f:nos) > > Untested, but seems to work perfectly :-). Thanks. > > However, that brings me to the next stage where again I'm trapped. > I would like to do a foldl' on a function that returns IO [FilePath]. > > I tried using Control.Monad.foldM, but then I end up with a function > taht return : > > IO (IO ([FilePath])) > > which doesn't work :-). > > It seems pretty obvious that I could implement a recursion like > Alexander did above for splitDirFile but I was wondering if there > was a more general solution. > > Cheers, > Erik It seems like foldM ought to do what you want. Could you post some more details please? Alex From mle+cl at mega-nerd.com Wed Jan 28 21:14:55 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Wed Jan 28 21:05:23 2009 Subject: [Haskell-beginners] Help! Trapped in the IO Monad! In-Reply-To: <57526e770901281730j3e5e12fcs67ed6db576ec39c2@mail.gmail.com> References: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> <20090129121823.c342b052.mle+cl@mega-nerd.com> <57526e770901281730j3e5e12fcs67ed6db576ec39c2@mail.gmail.com> Message-ID: <20090129131455.d80035df.mle+cl@mega-nerd.com> Alexander Dunlap wrote: > It seems like foldM ought to do what you want. Could you post some > more details please? This is a function that I have working in Ocaml which is a little more lenient about IO :-). This is what I have but won't compile: fileNames :: ([FilePath] -> FilePath -> FilePath -> [FilePath]) -> [FilePath] -> FilePath -> IO [FilePath] fileNames builder builder_accum topdir = do names <- getDirectoryContents topdir let properNames = filter (`notElem` [".", ".."]) names (dirs, files) <- splitDirFile properNames let accum <- foldl' (\ acc f -> builder acc topdir f) builder_accum files return $ foldM (\ acc d -> fileNames builder accum (topdir d)) accum dirs I get following error on the foldM: Couldn't match expected type `[FilePath]' against inferred type `IO [FilePath]' Expected type: IO [FilePath] Inferred type: IO (IO [FilePath]) Thinking about it some more, I can see the problem; accum is an "IO [FilePath]" and my builder function requires a "[FilePath]". Once I get the function working I would like to generalize it to: fileNames :: (a -> FilePath -> FilePath -> a) -> a -> FilePath -> IO a Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "Re graphics: A picture is worth 10K words - but only those to describe the picture. Hardly any sets of 10K words can be adequately described with pictures." -- Alan Perlis From thestonetable at gmail.com Wed Jan 28 21:44:30 2009 From: thestonetable at gmail.com (Cory Knapp) Date: Wed Jan 28 21:35:04 2009 Subject: [Haskell-beginners] Monads... Message-ID: <4981180E.5010204@gmail.com> Hello, so, I'm having a simple problem with monads: I have no idea how to actually use them. I understand the category theory (or, at least well enough to be able to explain "what is a monad"); I understand the way to declare something as a monad instance, but I just don't get how to program with them. Can anyone provide me with, or direct me towards, some simple monads and some ways of using (for example) the monadic properties of lists? Thanks, Cory From alexander.dunlap at gmail.com Wed Jan 28 21:55:09 2009 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Wed Jan 28 21:45:34 2009 Subject: [Haskell-beginners] Help! Trapped in the IO Monad! In-Reply-To: <20090129131455.d80035df.mle+cl@mega-nerd.com> References: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> <20090129121823.c342b052.mle+cl@mega-nerd.com> <57526e770901281730j3e5e12fcs67ed6db576ec39c2@mail.gmail.com> <20090129131455.d80035df.mle+cl@mega-nerd.com> Message-ID: <57526e770901281855yb4e1540qcf1d69f162aed0f3@mail.gmail.com> On Wed, Jan 28, 2009 at 6:14 PM, Erik de Castro Lopo wrote: > Alexander Dunlap wrote: > >> It seems like foldM ought to do what you want. Could you post some >> more details please? > > This is a function that I have working in Ocaml which is a little > more lenient about IO :-). > > This is what I have but won't compile: > > fileNames :: ([FilePath] -> FilePath -> FilePath -> [FilePath]) > -> [FilePath] -> FilePath -> IO [FilePath] > fileNames builder builder_accum topdir = do > names <- getDirectoryContents topdir > let properNames = filter (`notElem` [".", ".."]) names > (dirs, files) <- splitDirFile properNames > let accum <- foldl' (\ acc f -> builder acc topdir f) builder_accum files > return $ foldM (\ acc d -> fileNames builder accum (topdir d)) accum dirs > > I get following error on the foldM: > > Couldn't match expected type `[FilePath]' > against inferred type `IO [FilePath]' > Expected type: IO [FilePath] > Inferred type: IO (IO [FilePath]) > > Thinking about it some more, I can see the problem; accum is an > "IO [FilePath]" and my builder function requires a "[FilePath]". > > Once I get the function working I would like to generalize it to: > > fileNames :: (a -> FilePath -> FilePath -> a) -> a -> FilePath -> IO a > > Cheers, > Erik > -- > ----------------------------------------------------------------- > Erik de Castro Lopo Try removing the "return $" on the last line. foldM ... will already be in the IO monad; return will lift the IO a into the IO monad again, so you'll have IO (IO a), which you don't want. Alex From mle+cl at mega-nerd.com Wed Jan 28 21:57:02 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Wed Jan 28 21:47:34 2009 Subject: [Haskell-beginners] Monads... In-Reply-To: <4981180E.5010204@gmail.com> References: <4981180E.5010204@gmail.com> Message-ID: <20090129135702.18d43d0a.mle+cl@mega-nerd.com> Cory Knapp wrote: > Hello, so, I'm having a simple problem with monads: I have no idea how > to actually use them. I understand the category theory (or, at least > well enough to be able to explain "what is a monad"); I come from the complete other end of the spectrum, someone who does not know category theory, but know many programming languages, including Ocaml function language much like Haskell, but less pure. It is possible to use monads in Ocaml, but most code doesn't. > I understand the > way to declare something as a monad instance, but I just don't get how > to program with them. When it comes to coding with Haskell, you can basically ignore monads and just follow the type signatures. > Can anyone provide me with, or direct me towards, > some simple monads and some ways of using (for example) the monadic > properties of lists? Writing my own monad is something I will tackle when I know I need to. Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "C++ is like jamming a helicopter inside a Miata and expecting some sort of improvement." -- Drew Olbrich From mle+cl at mega-nerd.com Wed Jan 28 22:00:07 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Wed Jan 28 21:50:55 2009 Subject: [Haskell-beginners] Help! Trapped in the IO Monad! In-Reply-To: <57526e770901281855yb4e1540qcf1d69f162aed0f3@mail.gmail.com> References: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> <20090129121823.c342b052.mle+cl@mega-nerd.com> <57526e770901281730j3e5e12fcs67ed6db576ec39c2@mail.gmail.com> <20090129131455.d80035df.mle+cl@mega-nerd.com> <57526e770901281855yb4e1540qcf1d69f162aed0f3@mail.gmail.com> Message-ID: <20090129140007.e43e7326.mle+cl@mega-nerd.com> Alexander Dunlap wrote: > Try removing the "return $" on the last line. foldM ... will already > be in the IO monad; return will lift the IO a into the IO monad again, > so you'll have IO (IO a), which you don't want. Fantastic! Worked a treat. Thanks, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "C++ has its place in the history of programming languages. Just as Caligula has his place in the history of the Roman Empire." -- Robert Firth From nanothief at gmail.com Wed Jan 28 22:38:38 2009 From: nanothief at gmail.com (nanothief) Date: Wed Jan 28 22:29:59 2009 Subject: [Haskell-beginners] Monads... In-Reply-To: <4981180E.5010204@gmail.com> References: <4981180E.5010204@gmail.com> Message-ID: <498124BE.60506@gmail.com> Cory Knapp wrote: > Hello, so, I'm having a simple problem with monads: I have no idea how > to actually use them. I understand the category theory (or, at least > well enough to be able to explain "what is a monad"); I understand the > way to declare something as a monad instance, but I just don't get how > to program with them. Can anyone provide me with, or direct me > towards, some simple monads and some ways of using (for example) the > monadic properties of lists? > > Thanks, > Cory > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners I found that http://www.haskell.org/all_about_monads/html/index.html gave a lot of nice examples of using list and maybe monads. The list monad is particularly useful for finding possible solutions given available input values. For example, with the problem x + 8y = 114 3x - 8y + 4z = 182 x < y < z < 100 Find solutions for x,y,z The program: res :: [(Int,Int,Int)] res = do x <- [1..100] y <- [1..100] z <- [1..100] guard $ x + 8 * y == 114 guard $ 3*x - 8*y + 4*z == 182 guard $ x < y guard $ y < z return (x,y,z) will output all the possible solutions. Note how close the program is to the actual problem. The values of x,y, and z are chosen from the value [1..100], but if a guard statement fails, the (x,y,z) choice is abandoned. Another example (taken from http://www.mathsisfun.com/puzzles/sum-of-digits-is-43-solution.html ) *The Puzzle:* I am thinking of a 6-digit number. The sum of the digits is 43. And only two of the following three statements about the number are true: (1) it's a square number, (2) it's a cube number, and (3) the number is under 500000. the program answer = do d1 <- [0..9] d2 <- [0..9] d3 <- [0..9] d4 <- [0..9] d5 <- [0..9] d6 <- [0..9] let digitSum = d1 + d2 + d3 + d4 + d5 + d6 let value = d1 + d2*10 + d3*100 + d4*1000 + d5*10000 + d6*100000 guard $ digitSum == 43 let lessThan500000 = digitSum < 500000 let isSquare = (round $ sqrt (fromIntegral value)) ^ 2 == value let isCube = (round $ (fromIntegral value) ** (1/3)) ^ 3 == value guard $ length (filter id [lessThan500000,isSquare,isCube]) == 2 return value will output the three answers (not that the author only found one solution!). From mle+cl at mega-nerd.com Wed Jan 28 22:46:50 2009 From: mle+cl at mega-nerd.com (Erik de Castro Lopo) Date: Wed Jan 28 22:37:25 2009 Subject: [Haskell-beginners] Help! Trapped in the IO Monad! In-Reply-To: <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> References: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> Message-ID: <20090129144650.00747e41.mle+cl@mega-nerd.com> Alexander Dunlap wrote: > You might also look at Control.Monad.filterM. I often define a > function "partitionM" which is like partition except it uses a monadic > test, just like you have. Just for completeness, my partitionM: partitionM :: (Monad m) => (a -> m Bool) -> [a] -> m ([a], [a]) partitionM _ [] = return ([], []) partitionM p (x:xs) = do flg <- p x (ys, ns) <- partitionM p xs return (if flg then (x:ys, ns) else (ys, x:ns)) Cheers, Erik -- ----------------------------------------------------------------- Erik de Castro Lopo ----------------------------------------------------------------- "Indeed, I am impressed that Google runs an 8,000 node Linux cluster, 5 data centers, an extensive network, and a rapidly evolving application all with a staff of 12." -- http://research.microsoft.com/~gray/papers/FAAMs_HPTS.doc From RafaelGCPP.Linux at gmail.com Thu Jan 29 04:56:55 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Thu Jan 29 04:47:20 2009 Subject: [Haskell-beginners] Monads... In-Reply-To: <498124BE.60506@gmail.com> References: <4981180E.5010204@gmail.com> <498124BE.60506@gmail.com> Message-ID: <351ff25e0901290156m50e74ebft20c085cc1486e55b@mail.gmail.com> Cory, The big hit for me was Phillip Wadler's paper "Monads for functional programming" I made me start thinking "well, this looks like a monad..." homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf Cheers On Thu, Jan 29, 2009 at 01:38, nanothief wrote: > Cory Knapp wrote: > >> Hello, so, I'm having a simple problem with monads: I have no idea how to >> actually use them. I understand the category theory (or, at least well >> enough to be able to explain "what is a monad"); I understand the way to >> declare something as a monad instance, but I just don't get how to program >> with them. Can anyone provide me with, or direct me towards, some simple >> monads and some ways of using (for example) the monadic properties of lists? >> >> Thanks, >> Cory >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > I found that http://www.haskell.org/all_about_monads/html/index.html gave > a lot of nice examples of using list and maybe monads. The list monad is > particularly useful for finding possible solutions given available input > values. > For example, with the problem > x + 8y = 114 > 3x - 8y + 4z = 182 > x < y < z < 100 > Find solutions for x,y,z > > The program: > res :: [(Int,Int,Int)] > res = do > x <- [1..100] > y <- [1..100] > z <- [1..100] > guard $ x + 8 * y == 114 > guard $ 3*x - 8*y + 4*z == 182 > guard $ x < y > guard $ y < z > return (x,y,z) > > will output all the possible solutions. Note how close the program is to > the actual problem. The values of x,y, and z are chosen from the value > [1..100], but if a guard statement fails, the (x,y,z) choice is abandoned. > > Another example (taken from > http://www.mathsisfun.com/puzzles/sum-of-digits-is-43-solution.html ) > *The Puzzle:* I am thinking of a 6-digit number. The sum of the digits is > 43. > > And only two of the following three statements about the number are true: > > (1) it's a square number, > (2) it's a cube number, and > (3) the number is under 500000. > > the program > answer = do > d1 <- [0..9] > d2 <- [0..9] > d3 <- [0..9] > d4 <- [0..9] > d5 <- [0..9] > d6 <- [0..9] > let digitSum = d1 + d2 + d3 + d4 + d5 + d6 > let value = d1 + d2*10 + d3*100 + d4*1000 + d5*10000 + d6*100000 > guard $ digitSum == 43 > let lessThan500000 = digitSum < 500000 > let isSquare = (round $ sqrt (fromIntegral value)) ^ 2 == value > let isCube = (round $ (fromIntegral value) ** (1/3)) ^ 3 == value > guard $ length (filter id [lessThan500000,isSquare,isCube]) == 2 > return value > > will output the three answers (not that the author only found one > solution!). > > > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090129/5f9caad5/attachment-0001.htm From benedikt.ahrens at gmx.net Thu Jan 29 05:50:47 2009 From: benedikt.ahrens at gmx.net (Benedikt Ahrens) Date: Thu Jan 29 05:41:11 2009 Subject: [Haskell-beginners] Re: Beginners Digest, Vol 7, Issue 24 In-Reply-To: <20090129094722.2001A324490@www.haskell.org> References: <20090129094722.2001A324490@www.haskell.org> Message-ID: <432babfe0901290250y1846ade7u2f3e95772b94dd83@mail.gmail.com> hello cory, you might want to read this article: http://stefan-klinger.de/files/monadGuide.pdf it helped me find and understand the monads in haskell. ben > Message: 2 > Date: Wed, 28 Jan 2009 20:44:30 -0600 > From: Cory Knapp > Subject: [Haskell-beginners] Monads... > To: Beginners@haskell.org > Message-ID: <4981180E.5010204@gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Hello, so, I'm having a simple problem with monads: I have no idea how > to actually use them. I understand the category theory (or, at least > well enough to be able to explain "what is a monad"); I understand the > way to declare something as a monad instance, but I just don't get how > to program with them. Can anyone provide me with, or direct me towards, > some simple monads and some ways of using (for example) the monadic > properties of lists? > > Thanks, > Cory > From apfelmus at quantentunnel.de Thu Jan 29 05:58:51 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Thu Jan 29 05:48:45 2009 Subject: [Haskell-beginners] Re: Help! Trapped in the IO Monad! In-Reply-To: <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> References: <20090128150701.183f5c9f.mle+cl@mega-nerd.com> <57526e770901272014t5f396cfby25bf855d2b79a58f@mail.gmail.com> Message-ID: Alexander Dunlap wrote: > You can do (something like; this is untested) > > splitDirFile :: [FilePath] -> IO ([FilePath],[FilePath]) > splitDirFile [] = return ([],[]) > splitDirFile (f:fs) = do > (yess,nos) <- splitDirFile fs > exists <- doesDirectoryExist f > return $ if exists > then (f:yess,nos) > else (yess,f:nos) > > You might also look at Control.Monad.filterM. I often define a > function "partitionM" which is like partition except it uses a monadic > test, just like you have. How about splitDirFile ps = ((map fst *** map fst) . partition snd . zip ps) `liftM` mapM doesDirectoryExist ps There is no need to rewrite partition , you can reuse it. Hm, the plumbing seems slightly cumbersome to me, maybe Conal's editor combinators http://conal.net/blog/posts/semantic-editor-combinators/ can help. Regards, apfelmus -- http://apfelmus.nfshost.com From thestonetable at gmail.com Thu Jan 29 09:48:42 2009 From: thestonetable at gmail.com (Cory Knapp) Date: Thu Jan 29 09:39:10 2009 Subject: [Haskell-beginners] Monads... In-Reply-To: <351ff25e0901290156m50e74ebft20c085cc1486e55b@mail.gmail.com> References: <4981180E.5010204@gmail.com> <498124BE.60506@gmail.com> <351ff25e0901290156m50e74ebft20c085cc1486e55b@mail.gmail.com> Message-ID: <4981C1CA.9050304@gmail.com> Thanks to both of you, I'll look into those. Cory Rafael Gustavo da Cunha Pereira Pinto wrote: > Cory, > > The big hit for me was Phillip Wadler's paper "Monads for functional > programming" I made me start thinking "well, this looks like a monad..." > > homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf > > > Cheers > > On Thu, Jan 29, 2009 at 01:38, nanothief > wrote: > > Cory Knapp wrote: > > Hello, so, I'm having a simple problem with monads: I have no > idea how to actually use them. I understand the category > theory (or, at least well enough to be able to explain "what > is a monad"); I understand the way to declare something as a > monad instance, but I just don't get how to program with them. > Can anyone provide me with, or direct me towards, some simple > monads and some ways of using (for example) the monadic > properties of lists? > > Thanks, > Cory > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > I found that > http://www.haskell.org/all_about_monads/html/index.html gave a lot > of nice examples of using list and maybe monads. The list monad is > particularly useful for finding possible solutions given available > input values. > For example, with the problem > x + 8y = 114 > 3x - 8y + 4z = 182 > x < y < z < 100 > Find solutions for x,y,z > > The program: > res :: [(Int,Int,Int)] > res = do > x <- [1..100] > y <- [1..100] > z <- [1..100] > guard $ x + 8 * y == 114 > guard $ 3*x - 8*y + 4*z == 182 > guard $ x < y > guard $ y < z > return (x,y,z) > > will output all the possible solutions. Note how close the program > is to the actual problem. The values of x,y, and z are chosen from > the value [1..100], but if a guard statement fails, the (x,y,z) > choice is abandoned. > > Another example (taken from > http://www.mathsisfun.com/puzzles/sum-of-digits-is-43-solution.html ) > *The Puzzle:* I am thinking of a 6-digit number. The sum of the > digits is 43. > > And only two of the following three statements about the number > are true: > > (1) it's a square number, > (2) it's a cube number, and > (3) the number is under 500000. > > the program > answer = do > d1 <- [0..9] > d2 <- [0..9] > d3 <- [0..9] > d4 <- [0..9] > d5 <- [0..9] > d6 <- [0..9] > let digitSum = d1 + d2 + d3 + d4 + d5 + d6 > let value = d1 + d2*10 + d3*100 + d4*1000 + d5*10000 + d6*100000 > guard $ digitSum == 43 > let lessThan500000 = digitSum < 500000 > let isSquare = (round $ sqrt (fromIntegral value)) ^ 2 == value > let isCube = (round $ (fromIntegral value) ** (1/3)) ^ 3 == value > guard $ length (filter id [lessThan500000,isSquare,isCube]) == 2 > return value > > will output the three answers (not that the author only found one > solution!). > > > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > > > > -- > Rafael Gustavo da Cunha Pereira Pinto > Electronic Engineer, MSc. From hjgtuyl at chello.nl Thu Jan 29 10:06:07 2009 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Thu Jan 29 09:56:33 2009 Subject: [Haskell-beginners] Monads... In-Reply-To: <4981180E.5010204@gmail.com> References: <4981180E.5010204@gmail.com> Message-ID: I have written a reference manual for the basic Haskell monad functions, "A Tour of the Haskell Monad functions". It contains a lot of examples. You can find it at: http://members.chello.nl/hjgtuyl/tourdemonad.html Regards, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- On Thu, 29 Jan 2009 03:44:30 +0100, Cory Knapp wrote: > Hello, so, I'm having a simple problem with monads: I have no idea how > to actually use them. I understand the category theory (or, at least > well enough to be able to explain "what is a monad"); I understand the > way to declare something as a monad instance, but I just don't get how > to program with them. Can anyone provide me with, or direct me towards, > some simple monads and some ways of using (for example) the monadic > properties of lists? > > Thanks, > Cory > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- From alan.cameron at iname.com Thu Jan 29 10:21:24 2009 From: alan.cameron at iname.com (Alan Cameron) Date: Thu Jan 29 10:11:53 2009 Subject: [Haskell-beginners] Question about Real World Haskell Message-ID: In Chapter 3 of Real World Haskell it is not clear to me how to get the myInfo into the ghci system there appears to be two definitions for ch03/BookStore.hs can anyone help? Alan Cameron From emmanuel.delaborde at cimex.com Thu Jan 29 10:25:59 2009 From: emmanuel.delaborde at cimex.com (emmanuel.delaborde) Date: Thu Jan 29 10:16:27 2009 Subject: [Haskell-beginners] Compile type Error Message-ID: Hello I have the following snippet : ---------------------------------------------------------- module Main where import System.Environment (getArgs) import Data.Digest.OpenSSL.MD5 (md5sum) import Data.Digest.Pure.SHA (sha1, showDigest) import qualified Data.ByteString as BS (readFile) -- sha1 :: ByteString -> Digest -- readFile :: FilePath -> IO ByteString -- md5sum :: ByteString -> String -- showDigest :: Digest -> String checkHash :: String -> String -> String -> IO () checkHash codec hash file = let f = case codec of --"md5" -> md5sum "sha1" -> showDigest . sha1 _ -> error "Codec must be md5 or sha1 !" in BS.readFile file >>= \fileBS -> let fileHash = f fileBS in print (hash == fileHash) main = getArgs >>= \as -> case as of (codec:hash:file:_) -> checkHash codec hash file _ -> usage usage = print "checksum codec hash file" ---------------------------------------------------------- which fails to compile, this is the error I get : checksum.hs:20:19: Couldn't match expected type `Data.ByteString.Lazy.Internal.ByteString' against inferred type `Data.ByteString.Internal.ByteString' In the first argument of `f', namely `fileBS' In the expression: f fileBS In the definition of `fileHash': fileHash = f fileBS it looks like (showDigest . sha1) expects Data.ByteString.Lazy.Internal.ByteString but gets Data.ByteString.Internal.ByteString What can I do ? Thanks E. ----------------------------------------------------------------------------------------------- This e-mail (and any attachments) is confidential and may contain personal views which are not the views of Cimex Media Ltd and any affiliated companies, unless specifically stated. It is intended for the use of the individual or group to whom it is addressed. If you have received it in error, please delete it from your system, do not use, copy or disclose the information in any way nor act in reliance on it and please notify postmaster@cimex.com A company registered in England Wales. Company Number 03765711 Registered Office : The Olde Bakehouse, 156 Watling Street East, Towcester, Northants NN12 6DB This email was scanned by Postini, the leading provider in Managed Email Security. From alan.cameron at iname.com Thu Jan 29 10:54:20 2009 From: alan.cameron at iname.com (Alan Cameron) Date: Thu Jan 29 10:44:44 2009 Subject: [Haskell-beginners] Real World Haskell book authors accepting comments? Message-ID: The online version of the book seems to have stopped accepting comments - at least from me. Alan Cameron From RafaelGCPP.Linux at gmail.com Thu Jan 29 11:19:38 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Thu Jan 29 11:10:01 2009 Subject: [Haskell-beginners] Compile type Error In-Reply-To: References: Message-ID: <351ff25e0901290819l40427aaas918e70f6a9dbde78@mail.gmail.com> I didn't compile, but, by the looks of it, I would change import qualified Data.ByteString as BS (readFile) for import qualified Data.ByteString.Lazy as BS (readFile) as it seems sha1 needs a lazy bytestring On Thu, Jan 29, 2009 at 13:25, emmanuel.delaborde < emmanuel.delaborde@cimex.com> wrote: > Hello > > I have the following snippet : > > ---------------------------------------------------------- > > module Main where > > import System.Environment (getArgs) > import Data.Digest.OpenSSL.MD5 (md5sum) > import Data.Digest.Pure.SHA (sha1, showDigest) > import qualified Data.ByteString as BS (readFile) > > -- sha1 :: ByteString -> Digest > -- readFile :: FilePath -> IO ByteString > -- md5sum :: ByteString -> String > -- showDigest :: Digest -> String > > checkHash :: String -> String -> String -> IO () > checkHash codec hash file = > let f = case codec of > --"md5" -> md5sum > "sha1" -> showDigest . sha1 > _ -> error "Codec must be md5 or sha1 !" in > BS.readFile file >>= \fileBS -> > let fileHash = f fileBS in > print (hash == fileHash) > > main = > getArgs >>= \as -> > case as of > (codec:hash:file:_) -> checkHash codec hash file > _ -> usage > > usage = print "checksum codec hash file" > > ---------------------------------------------------------- > > which fails to compile, this is the error I get : > > > checksum.hs:20:19: > Couldn't match expected type `Data.ByteString.Lazy.Internal.ByteString' > against inferred type `Data.ByteString.Internal.ByteString' > In the first argument of `f', namely `fileBS' > In the expression: f fileBS > In the definition of `fileHash': fileHash = f fileBS > > > > > it looks like (showDigest . sha1) expects > Data.ByteString.Lazy.Internal.ByteString but gets > Data.ByteString.Internal.ByteString > > What can I do ? > > Thanks > > E. > > > > > > > > > ----------------------------------------------------------------------------------------------- > > This e-mail (and any attachments) is confidential and may containpersonal > views which are not the views of Cimex Media Ltd andany affiliated > companies, unless specifically stated. It is intendedfor the use of the > individual or group to whom it is addressed. Ifyou have received it in > error, please delete it from your system,do not use, copy or disclose the > information in any way nor act inreliance on it and please notify > postmaster@cimex.com > > A company registered in England Wales. Company Number 03765711 > Registered Office : The Olde Bakehouse, 156 Watling Street East, Towcester, > Northants NN12 6DB > > This email was scanned by Postini, the leading provider in Managed Email > Security. > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090129/2bcbe134/attachment-0001.htm From emmanuel.delaborde at cimex.com Thu Jan 29 11:28:10 2009 From: emmanuel.delaborde at cimex.com (emmanuel.delaborde) Date: Thu Jan 29 11:18:41 2009 Subject: [Haskell-beginners] Compile type Error In-Reply-To: <20090129161005.4EDCE3247B1@www.haskell.org> References: <20090129161005.4EDCE3247B1@www.haskell.org> Message-ID: <30BF5C42-A6DF-4352-BF1C-9ABC0BFE5434@cimex.com> On 29 Jan 2009, at 16:10, beginners-request@haskell.org wrote: > Content-Type: text/plain; charset="iso-8859-1" > > I didn't compile, but, by the looks of it, I would change > > import qualified Data.ByteString as BS (readFile) > > for > > import qualified Data.ByteString.Lazy as BS (readFile) > > > as it seems sha1 needs a lazy bytestring Thanks ! It compiles now but brings me to my real problem :) If I uncomment this line "md5" -> md5sum I get the following : ------ module Main where import System.Environment (getArgs) import Data.Digest.OpenSSL.MD5 (md5sum) import Data.Digest.Pure.SHA (sha1, showDigest) import qualified Data.ByteString.Lazy as BS (readFile) -- sha1 :: ByteString -> Digest -- readFile :: FilePath -> IO ByteString -- md5sum :: ByteString -> String -- showDigest :: Digest -> String checkHash :: String -> String -> String -> IO () checkHash codec hash file = let f = case codec of "md5" -> md5sum "sha1" -> showDigest . sha1 _ -> error "Codec must be md5 or sha1 !" in BS.readFile file >>= \fileBS -> let fileHash = f fileBS in print (hash == fileHash) main = getArgs >>= \as -> case as of (codec:hash:file:_) -> checkHash codec hash file _ -> usage usage = print "checksum codec hash file" ------ which now fails to compile with this error : checksum.hs:17:22: Couldn't match expected type `Data.ByteString.Internal.ByteString' against inferred type `Data.ByteString.Lazy.Internal.ByteString' In the expression: showDigest . sha1 In a case alternative: "sha1" -> showDigest . sha1 In the expression: case codec of { "md5" -> md5sum "sha1" -> showDigest . sha1 _ -> error "Codec must be md5 or sha1 !" } How can I both use md5sum and sha1 when one use a lazy ByteString end the other one does not ? Thanks E -- Emmanuel Delaborde Web Technologist Cimex 53-55 Scrutton Street, London UK, EC2A 4PJ T: +44 (0)20 7324 7780 F: +44 (0)20 7324 7781 http://www.cimex.com ----------------------------------------------------------------------------------------------- This e-mail (and any attachments) is confidential and may contain personal views which are not the views of Cimex Media Ltd and any affiliated companies, unless specifically stated. It is intended for the use of the individual or group to whom it is addressed. If you have received it in error, please delete it from your system, do not use, copy or disclose the information in any way nor act in reliance on it and please notify postmaster@cimex.com A company registered in England Wales. Company Number 03765711 Registered Office : The Olde Bakehouse, 156 Watling Street East, Towcester, Northants NN12 6DB This email was scanned by Postini, the leading provider in Managed Email Security. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090129/e7355d2e/attachment.htm From daniel.is.fischer at web.de Thu Jan 29 11:41:06 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Jan 29 11:28:54 2009 Subject: [Haskell-beginners] Compile type Error In-Reply-To: References: Message-ID: <200901291741.07042.daniel.is.fischer@web.de> Am Donnerstag, 29. Januar 2009 16:25 schrieb emmanuel.delaborde: > Hello > > I have the following snippet : > > ---------------------------------------------------------- > > module Main where > > import System.Environment (getArgs) > import Data.Digest.OpenSSL.MD5 (md5sum) > import Data.Digest.Pure.SHA (sha1, showDigest) > import qualified Data.ByteString as BS (readFile) > > -- sha1 :: ByteString -> Digest > -- readFile :: FilePath -> IO ByteString > -- md5sum :: ByteString -> String > -- showDigest :: Digest -> String > > checkHash :: String -> String -> String -> IO () > checkHash codec hash file = > let f = case codec of > --"md5" -> md5sum > "sha1" -> showDigest . sha1 > _ -> error "Codec must be md5 or sha1 !" in > BS.readFile file >>= \fileBS -> > let fileHash = f fileBS in > print (hash == fileHash) > > main = > getArgs >>= \as -> > case as of > (codec:hash:file:_) -> checkHash codec hash file > _ -> usage > > usage = print "checksum codec hash file" > > ---------------------------------------------------------- > > which fails to compile, this is the error I get : > > > checksum.hs:20:19: > Couldn't match expected type > `Data.ByteString.Lazy.Internal.ByteString' > against inferred type `Data.ByteString.Internal.ByteString' > In the first argument of `f', namely `fileBS' > In the expression: f fileBS > In the definition of `fileHash': fileHash = f fileBS > > > > > it looks like (showDigest . sha1) expects > Data.ByteString.Lazy.Internal.ByteString but gets > Data.ByteString.Internal.ByteString > > What can I do ? import qualified Data.ByteString.Lazy as BS (readFile) should do it. > > Thanks > > E. Cheers, Daniel From daniel.is.fischer at web.de Thu Jan 29 13:33:21 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Jan 29 13:21:10 2009 Subject: [Haskell-beginners] Compile type Error In-Reply-To: <30BF5C42-A6DF-4352-BF1C-9ABC0BFE5434@cimex.com> References: <20090129161005.4EDCE3247B1@www.haskell.org> <30BF5C42-A6DF-4352-BF1C-9ABC0BFE5434@cimex.com> Message-ID: <200901291933.21694.daniel.is.fischer@web.de> Am Donnerstag, 29. Januar 2009 17:28 schrieb emmanuel.delaborde: > On 29 Jan 2009, at 16:10, beginners-request@haskell.org wrote: > > Content-Type: text/plain; charset="iso-8859-1" > > > > I didn't compile, but, by the looks of it, I would change > > > > import qualified Data.ByteString as BS (readFile) > > > > for > > > > import qualified Data.ByteString.Lazy as BS (readFile) > > > > > > as it seems sha1 needs a lazy bytestring > > Thanks ! > It compiles now but brings me to my real problem :) > If I uncomment this line > > "md5" -> md5sum > > I get the following : > > ------ > > module Main where > > import System.Environment (getArgs) > import Data.Digest.OpenSSL.MD5 (md5sum) > import Data.Digest.Pure.SHA (sha1, showDigest) > import qualified Data.ByteString.Lazy as BS (readFile) > > -- sha1 :: ByteString -> Digest > -- readFile :: FilePath -> IO ByteString > -- md5sum :: ByteString -> String > -- showDigest :: Digest -> String > > checkHash :: String -> String -> String -> IO () > checkHash codec hash file = > let f = case codec of > "md5" -> md5sum > "sha1" -> showDigest . sha1 > _ -> error "Codec must be md5 or sha1 !" in > BS.readFile file >>= \fileBS -> > let fileHash = f fileBS in > print (hash == fileHash) > > main = > getArgs >>= \as -> > case as of > (codec:hash:file:_) -> checkHash codec hash file > _ -> usage > > usage = print "checksum codec hash file" > > ------ > > which now fails to compile with this error : > > checksum.hs:17:22: > Couldn't match expected type `Data.ByteString.Internal.ByteString' > against inferred type > `Data.ByteString.Lazy.Internal.ByteString' > In the expression: showDigest . sha1 > In a case alternative: "sha1" -> showDigest . sha1 > In the expression: > case codec of { > "md5" -> md5sum > "sha1" -> showDigest . sha1 > _ -> error "Codec must be md5 or sha1 !" } > > > How can I both use md5sum and sha1 when one use a lazy ByteString end > the other one does not ? Convert lazy to strict ByteStrings before using md5sum import qualified Data.ByteString as S -- strict ByteStrings import qualified Data.ByteString.Lazy as L checkHash :: String -> String -> String -> IO () checkHash codec hash file = let f = case codec of "md5" -> md5sum . S.concat . L.toChunks "sha1" -> showDigest . sha1 _ -> error "Codec must be md5 or sha1 !" in L.readFile file >>= \fileBS -> let fileHash = f fileBS in print (hash == fileHash) or the other way round: checkHash :: String -> String -> String -> IO () checkHash codec hash file = let f = case codec of "md5" -> md5sum "sha1" -> showDigest . sha1 . L.fromChunks . (:[]) _ -> error "Codec must be md5 or sha1 !" in S.readFile file >>= \fileBS -> let fileHash = f fileBS in print (hash == fileHash) > > Thanks > > E Cheers, Daniel From patl at cpan.org Thu Jan 29 13:46:18 2009 From: patl at cpan.org (Patrick LeBoutillier) Date: Thu Jan 29 13:40:06 2009 Subject: [Haskell-beginners] Understanding cached fibonnacci function Message-ID: Hi all, I recently stumbled on this example in some wiki: mfib :: Int -> Integer mfib = (map fib [0 ..] !!) where fib 0 = 0 fib 1 = 1 fib n = mfib (n-2) + mfib (n-1) I don't understand how the results get cached. When mfib is recursively called, doesn't a new (map fib [0 ..] !!) start over again? Or perhaps I'm thinking too imperatively here... Also, if I change the definition to this (adding "a" on both sides): mfib :: Int -> Integer mfib a = (map fib [0 ..] !!) a where fib 0 = 0 fib 1 = 1 fib n = mfib (n-2) + mfib (n-1) the funtion becomes slow again. Why is that? Thanks a lot, Patrick LeBoutillier -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From tom.davie at gmail.com Thu Jan 29 14:29:35 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Thu Jan 29 14:24:04 2009 Subject: [Haskell-beginners] Understanding cached fibonnacci function In-Reply-To: References: Message-ID: <1217EC28-CB6A-43CC-9414-627A6BB97796@gmail.com> On 29 Jan 2009, at 19:46, Patrick LeBoutillier wrote: > Hi all, > > I recently stumbled on this example in some wiki: > > mfib :: Int -> Integer > mfib = (map fib [0 ..] !!) > where fib 0 = 0 > fib 1 = 1 > fib n = mfib (n-2) + mfib (n-1) > > I don't understand how the results get cached. When mfib is > recursively called, doesn't a new (map fib [0 ..] !!) start over > again? Or perhaps I'm thinking too imperatively here... > > Also, if I change the definition to this (adding "a" on both sides): > > mfib :: Int -> Integer > mfib a = (map fib [0 ..] !!) a > where fib 0 = 0 > fib 1 = 1 > fib n = mfib (n-2) + mfib (n-1) > > the funtion becomes slow again. Why is that? The reason that the second one is slower is that ghc makes a distinction that so called CAFs (constant applicative forms) are likely to be constants, and evaluates them once. Thus, your list (map fib [0..]) gets kept between runs. In the second form though, ghc sees a function, and evaluates it every time it gets called, which makes it into an exponential time algorithm. An aside: fibs !! 0 is usually defined to be 1. Here's another couple of definitions of fib for you to play with, and try and figure out the properties of: mfib :: Int -> Integer mfib = ((fibs 1 1) !!) fibs :: Integer -> Integer -> [Integer] fibs n m = n : fibs m (n+m) -- and fibs :: [Integer] fibs = 1 : 1 : zipWith (+) fibs (tail fibs) Have fun Bob From daniel.is.fischer at web.de Thu Jan 29 15:22:44 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Jan 29 15:10:42 2009 Subject: [Haskell-beginners] Understanding cached fibonnacci function In-Reply-To: <1217EC28-CB6A-43CC-9414-627A6BB97796@gmail.com> References: <1217EC28-CB6A-43CC-9414-627A6BB97796@gmail.com> Message-ID: <200901292122.44610.daniel.is.fischer@web.de> Am Donnerstag, 29. Januar 2009 20:29 schrieb Thomas Davie: > > The reason that the second one is slower is that ghc makes a > distinction that so called CAFs (constant applicative forms) are > likely to be constants, and evaluates them once. Thus, your list (map > fib [0..]) gets kept between runs. In the second form though, ghc > sees a function, and evaluates it every time it gets called, which > makes it into an exponential time algorithm. However, if you compile it with -O2, the optimiser sees it's better to keep the list and it's again a linear time algorithm. > > An aside: fibs !! 0 is usually defined to be 1. I meet fibs !! 0 == 0 more often. > > Here's another couple of definitions of fib for you to play with, and > try and figure out the properties of: > mfib :: Int -> Integer > mfib = ((fibs 1 1) !!) > > fibs :: Integer -> Integer -> [Integer] > fibs n m = n : fibs m (n+m) > > -- and > fibs :: [Integer] > fibs = 1 : 1 : zipWith (+) fibs (tail fibs) > > Have fun Not to forget the marvellous import Control.Monad.Fix fibs :: [Integer] fibs = fix ((0:) . scanl (+) 1) > > Bob From dpfrey at shaw.ca Thu Jan 29 18:27:37 2009 From: dpfrey at shaw.ca (David Frey) Date: Thu Jan 29 18:17:58 2009 Subject: [Haskell-beginners] Question about Real World Haskell In-Reply-To: References: Message-ID: On Thu, 29 Jan 2009 15:21:24 +0000, Alan Cameron wrote: > In Chapter 3 of Real World Haskell it is not clear to me how to get the > myInfo into the ghci system there appears to be two definitions for > ch03/BookStore.hs can anyone help? > > Alan Cameron > I assume you are referring to this: -- file: ch03/BookStore.hs data BookInfo = Book Int String [String] deriving show ... Book text here ... -- file: ch03/BookStore.hs data MagazineInfo = Magazine Int String [String] deriving show ... More book text here ... -- file: ch03/BookStore.hs myInfo = Book 9870135072455 "Algebra of Programming" ["Richard Bird", "Oege de Moor"] When the book mentions a filename, that means that what follows is from that file, but may only be a piece of that file. Save all of these pieces into a file named BookStore.hs and then run "ghci BookStore.hs" in the same directory as the file. From patl at cpan.org Thu Jan 29 20:05:51 2009 From: patl at cpan.org (Patrick LeBoutillier) Date: Thu Jan 29 19:56:13 2009 Subject: [Haskell-beginners] Question about Real World Haskell In-Reply-To: References: Message-ID: > When the book mentions a filename, that means that what follows is from > that file, but may only be a piece of that file. Save all of these pieces > into a file named BookStore.hs and then run "ghci BookStore.hs" in the > same directory as the file. You can find the entire source code from the book here: http://examples.oreilly.com/9780596514983/rwh-examples2.zip Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From chaddai.fouche at gmail.com Fri Jan 30 00:14:45 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Fri Jan 30 00:05:08 2009 Subject: [Haskell-beginners] Compile type Error In-Reply-To: <200901291933.21694.daniel.is.fischer@web.de> References: <20090129161005.4EDCE3247B1@www.haskell.org> <30BF5C42-A6DF-4352-BF1C-9ABC0BFE5434@cimex.com> <200901291933.21694.daniel.is.fischer@web.de> Message-ID: On Thu, Jan 29, 2009 at 7:33 PM, Daniel Fischer wrote: > > Convert lazy to strict ByteStrings before using md5sum > Or you could use Data.Digest.Pure.MD5 instead of Data.Digest.OpenSSL.MD5, it takes lazy bytestring too. -- Jeda? From patrick.leboutillier at gmail.com Thu Jan 29 13:18:32 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Fri Jan 30 01:58:06 2009 Subject: [Haskell-beginners] Understanding cached fibonnacci function Message-ID: Hi all, I recently stumbled on this example in some wiki: mfib :: Int -> Integer mfib = (map fib [0 ..] !!) where fib 0 = 0 fib 1 = 1 fib n = mfib (n-2) + mfib (n-1) I don't understand how the results get cached. When mfib is recursively called, doesn't a new (map fib [0 ..] !!) start over again? Or perhaps I'm thinking too imperatively here... Also, if I change the definition to this (adding "a" on both sides): mfib :: Int -> Integer mfib a = (map fib [0 ..] !!) a where fib 0 = 0 fib 1 = 1 fib n = mfib (n-2) + mfib (n-1) the funtion becomes slow again. Why is that? Thanks a lot, Patrick LeBoutillier -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From RafaelGCPP.Linux at gmail.com Fri Jan 30 04:39:08 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Fri Jan 30 04:29:30 2009 Subject: [Haskell-beginners] Understanding cached fibonnacci function In-Reply-To: References: Message-ID: <351ff25e0901300139y1c621f50qc93ee6b2144a08a5@mail.gmail.com> I don't know exactly how to explain it, but it has to do with memoization The first version generates a fully memoized function, while the second creates a memoized version for each call, since the thunk and memoization for fib is destroyed after each computation. This is not a precise explanation, but I can't think of a better way to put it... On Thu, Jan 29, 2009 at 16:18, Patrick LeBoutillier < patrick.leboutillier@gmail.com> wrote: > Hi all, > > I recently stumbled on this example in some wiki: > > mfib :: Int -> Integer > mfib = (map fib [0 ..] !!) > where fib 0 = 0 > fib 1 = 1 > fib n = mfib (n-2) + mfib (n-1) > > I don't understand how the results get cached. When mfib is > recursively called, doesn't a new (map fib [0 ..] !!) start over > again? Or perhaps I'm thinking too imperatively here... > > Also, if I change the definition to this (adding "a" on both sides): > > mfib :: Int -> Integer > mfib a = (map fib [0 ..] !!) a > where fib 0 = 0 > fib 1 = 1 > fib n = mfib (n-2) + mfib (n-1) > > the funtion becomes slow again. Why is that? > > > Thanks a lot, > > Patrick LeBoutillier > > -- > ===================== > Patrick LeBoutillier > Rosem?re, Qu?bec, Canada > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Rafael Gustavo da Cunha Pereira Pinto Electronic Engineer, MSc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090130/548aedb7/attachment.htm From es at ertes.de Fri Jan 30 09:59:02 2009 From: es at ertes.de (Ertugrul Soeylemez) Date: Fri Jan 30 09:49:33 2009 Subject: [Haskell-beginners] Re: Understanding cached fibonnacci function References: <1217EC28-CB6A-43CC-9414-627A6BB97796@gmail.com> <200901292122.44610.daniel.is.fischer@web.de> Message-ID: <20090130155902.44ab2b34@tritium.xx> Daniel Fischer wrote: > Not to forget the marvellous > > import Control.Monad.Fix > > fibs :: [Integer] > fibs = fix ((0:) . scanl (+) 1) I don't like that one. My favorite is the following, because it's short, concise and still very comprehensible: import Data.Function fibs :: Num i => [i] fibs = fix (\r x y -> x : r y (x+y)) 0 1 Replace 0 by 1, if you want to exclude it from the sequence. I prefer to include it. Greets, Ertugrul. -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From daniel.is.fischer at web.de Fri Jan 30 10:24:07 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Jan 30 10:11:51 2009 Subject: [Haskell-beginners] Re: Understanding cached fibonnacci function In-Reply-To: <20090130155902.44ab2b34@tritium.xx> References: <200901292122.44610.daniel.is.fischer@web.de> <20090130155902.44ab2b34@tritium.xx> Message-ID: <200901301624.07296.daniel.is.fischer@web.de> Am Freitag, 30. Januar 2009 15:59 schrieb Ertugrul Soeylemez: > Daniel Fischer wrote: > > Not to forget the marvellous > > > > import Control.Monad.Fix > > > > fibs :: [Integer] > > fibs = fix ((0:) . scanl (+) 1) > > I don't like that one. My favorite is the following, because it's > short, concise and still very comprehensible: > > import Data.Function > > fibs :: Num i => [i] > fibs = fix (\r x y -> x : r y (x+y)) 0 1 But that's too easy to understand! What a waste of fix, sheesh ;-) My favourite is fibs = 0:1:zipWith (+) fibs (tail fibs) clear, elegant, accessible. But I also like the other one, precisely because, unless one is very experienced, one has to do a few rounds of "Wait, how on earth does this work?" before it clicks. > > Replace 0 by 1, if you want to exclude it from the sequence. I prefer > to include it. Yep. Much more natural if the powers match the index. > > > Greets, > Ertugrul. Cheers, Daniel From patl at cpan.org Fri Jan 30 11:41:29 2009 From: patl at cpan.org (Patrick LeBoutillier) Date: Fri Jan 30 11:31:49 2009 Subject: [Haskell-beginners] Re: Understanding cached fibonnacci function In-Reply-To: <20090130155902.44ab2b34@tritium.xx> References: <1217EC28-CB6A-43CC-9414-627A6BB97796@gmail.com> <200901292122.44610.daniel.is.fischer@web.de> <20090130155902.44ab2b34@tritium.xx> Message-ID: >> fibs = fix ((0:) . scanl (+) 1) > > I don't like that one. My favorite is the following, because it's > short, concise and still very comprehensible: > > import Data.Function > > fibs :: Num i => [i] > fibs = fix (\r x y -> x : r y (x+y)) 0 1 Can someone please explain this one? I can't seem to figure out what 'fix' does (the definition in the documentation is a bit to mathematically inclined for me...). Thanks, Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From tom.davie at gmail.com Fri Jan 30 11:55:25 2009 From: tom.davie at gmail.com (Thomas Davie) Date: Fri Jan 30 11:45:52 2009 Subject: [Haskell-beginners] Re: Understanding cached fibonnacci function In-Reply-To: References: <1217EC28-CB6A-43CC-9414-627A6BB97796@gmail.com> <200901292122.44610.daniel.is.fischer@web.de> <20090130155902.44ab2b34@tritium.xx> Message-ID: <28FBF03F-F64E-4658-B442-A9D6BEFE9C4C@gmail.com> On 30 Jan 2009, at 17:41, Patrick LeBoutillier wrote: >>> fibs = fix ((0:) . scanl (+) 1) >> >> I don't like that one. My favorite is the following, because it's >> short, concise and still very comprehensible: >> >> import Data.Function >> >> fibs :: Num i => [i] >> fibs = fix (\r x y -> x : r y (x+y)) 0 1 > > Can someone please explain this one? I can't seem to figure out what > 'fix' does (the definition in the documentation is a bit to > mathematically inclined for me...). It computes a fixed point for a function ? that is a value which when passed to the function gives back the same answer. Some examples: fix id ? any value is a fixed point for id, no matter what you give it, it always comes back the same! fix (+ 1) ? no values, no matter what you give it, it'll always come out one bigger, so there's no fixed point here fix (1:) ? the infinite list of 1s, if you put a 1 on the front of it, you get back the inifinite list of ones again. fix (\r x y -> x : r y (x+y)) ? Lets try giving this function to itself: (\r x y -> x : (y : r (x+y) (y+(x+y)))), and again... (\r x y - > x : (y : ((x+y) : r (y+(x+y)) ((x+y)+y+(x+y))))... you can see where this is going, if we apply this to 0 and 1, we get 0 : 1 : (0+1) : (1 + (0 + 1)) : ... fibonacci numbers. In general, we can write *any* recursive function using the fix function, we transform the function to accept another argument first, we replace all recursive calls with calls to this argument, and we wrap it in the fix function. Hope that helps. Bob From apfelmus at quantentunnel.de Sat Jan 31 05:23:29 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Sat Jan 31 05:13:15 2009 Subject: [Haskell-beginners] Re: Understanding cached fibonnacci function In-Reply-To: References: <1217EC28-CB6A-43CC-9414-627A6BB97796@gmail.com> <200901292122.44610.daniel.is.fischer@web.de> <20090130155902.44ab2b34@tritium.xx> Message-ID: Patrick LeBoutillier wrote: >> >> import Data.Function >> >> fibs :: Num i => [i] >> fibs = fix (\r x y -> x : r y (x+y)) 0 1 > > Can someone please explain this one? I can't seem to figure out what > 'fix' does (the definition in the documentation is a bit to > mathematically inclined for me...). Well, you can just try to replace fix by its definition and see what happens: fix (\r x y -> x : r y (x+y)) 0 1 = (let go = (\r x y -> x : r y (x+y)) go in go) 0 1 = let go = \x y -> x : go y (x+y) in go 0 1 = let go x y = x : go y (x+y) in go 0 1 In other words, fix can define a recursive function. -- http://apfelmus.nfshost.com From es at ertes.de Sat Jan 31 10:43:37 2009 From: es at ertes.de (Ertugrul Soeylemez) Date: Sat Jan 31 10:34:10 2009 Subject: [Haskell-beginners] Re: Understanding cached fibonnacci function References: <1217EC28-CB6A-43CC-9414-627A6BB97796@gmail.com> <200901292122.44610.daniel.is.fischer@web.de> <20090130155902.44ab2b34@tritium.xx> <28FBF03F-F64E-4658-B442-A9D6BEFE9C4C@gmail.com> Message-ID: <20090131164337.401c18c8@tritium.xx> Thomas Davie wrote: > >> fibs :: Num i => [i] > >> fibs = fix (\r x y -> x : r y (x+y)) 0 1 > > > > Can someone please explain this one? I can't seem to figure out what > > 'fix' does (the definition in the documentation is a bit to > > mathematically inclined for me...). > > It computes a fixed point for a function ? that is a value which when > passed to the function gives back the same answer. Some examples: > > fix id ? any value is a fixed point for id, no matter what you give > it, it always comes back the same! Beware that 'fix' doesn't simply return an arbitrary fixed point. It gives you _the_ least-defined fixed point, which is bottom for 'fix id'. By the way, it's a very aggressive implementation of bottom. Trying to evaluate 'fix id' may crash your system, unless you set proper memory limits. > fix (+ 1) ? no values, no matter what you give it, it'll always come > out one bigger, so there's no fixed point here It does have a fixed point. Every function has a fixed point. Its fixed point is 1+1+1+1+... It's easy to verify: (+1) (1+1+1+1+...) = 1+1+1+1+... However, the fixed point has the least possible definedness, which means it's bottom. > fix (1:) ? the infinite list of 1s, if you put a 1 on the front of it, > you get back the inifinite list of ones again. Same story here, but (1:) is not strict in its argument, so you get higher definedness than bottom. > fix (\r x y -> x : r y (x+y)) ? Lets try giving this function to > itself: (\r x y -> x : (y : r (x+y) (y+(x+y)))), and again... (\r x y > -> x : (y : ((x+y) : r (y+(x+y)) ((x+y)+y+(x+y))))... you can see > where this is going, if we apply this to 0 and 1, we get 0 : 1 : > (0+1) : (1 + (0 + 1)) : ... fibonacci numbers. I find it easier to explain in terms of typed lambda calculus. The problem with it is that you can't express recursion directly in raw lambda notation. The fixed point operator 'fix' gives you the power to do this: fix f = f (fix f) If you pass a lambda to 'fix', then it results in a function, which gets itself as its first argument, so you can express recursion. Say, you would like to write the greatest common divisor algorithm, which is: gcd x 0 = x gcd x y = gcd y (x `mod` y) Now in raw lambda calculus, you can't write equations like above. You can only express functions in terms of their lambdas: (\x y -> if y == 0 then x else ...) The problem should be clear: There is no way for the function to call itself. Now the fixed point operator comes into play. It turns the first argument of the function into a recursive reference to itself: fix (\recurse x y -> if y == 0 then x else recurse y (x `mod` y)) Of course, with all the expressive power you've got in Haskell, it's never necessary and seldomly useful to use the fixed point operator. You would write the GCD function just in the usual style. But sometimes, particularly for infinite unfolds, it's more convenient than 'unfoldr' or 'iterate', without making code incomprehensible. Greets, Ertugrul. -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/