From alex at alexjacobson.com Wed Aug 1 00:34:23 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Wed Aug 1 00:27:05 2007 Subject: [Haskell-cafe] Re: HDBC or HSQL In-Reply-To: <470880360707300831s44170261lb5d2002d1f56e70b@mail.gmail.com> References: <470880360707300831s44170261lb5d2002d1f56e70b@mail.gmail.com> Message-ID: <46B00D4F.6090206@alexjacobson.com> Out of curiosity, can I ask what you are actually trying to do? I am asking because I am trying to make HAppS a reasonable replacement for all contexts in which you would otherwise use an external relational database except those in which an external SQL database is a specific requirement. -Alex- Isto Aho wrote: > Hi, > > I was also wandering between these different db-libs and thanks for your > information. > > I tried several (HDBC, HSQL, HaskellDB) and made only small trials. > HaskellDB has quite many examples on wiki that gave a quick start to > further trials. > But, I wasn't able to tell that some of the fields have default values > and then it > was already time to move on to the HSQL and HDBC trials. > > Is it possible to use sql-array-types with HDBC with postgresql? I don't > remember was this the > reason why I eventually tried HSQL - anyhow, it was rather difficult to > get started with HDBC > but the src test cases helped here. One example in a wiki would do > miracles :) > > HSQL didn't have the array-types but it took only couple of hours to add > "a sort of" support > for those. There are some problems though... (indexed table queries > returning some nulls > is not yet working and ghci seems to be allergic to this) I was even > wondering, should I propose > a patch in some near future for this. > > But if HDBC can handle those sql-arrays or if you can give a couple of > hints, how to proceed > in order to add them there, given your view below, I'd be willing to try > to help / to try to use HDBC. > > br, > Isto > > 2007/7/30, John Goerzen >: > > On 2007-07-25, George Moschovitis > wrote: > > I am a Haskell newbie and I would like to hear your suggestions > regarding a > > Database conectivity library: > > > > HSQL or HDBC ? > > > > which one is better / more actively supported? > > I am the author of HDBC, so take this for what you will. > > There were several things that bugged me about HSQL, if memory serves: > > 1) It segfaulted periodically, at least with PostgreSQL > > 2) It had memory leaks > > 3) It couldn't read the result set incrementally. That means that if > you have a 2GB result set, you better have 8GB of RAM to hold it. > > 4) It couldn't reference colums in the result set by position, only by > name > > 5) It didn't support pre-compiled queries (replacable parameters) > > 6) Its transaction handling didn't permit enough flexibility > > I initially looked at fixing HSQL, but decided it would be easier to > actually write my own interface from scratch. > > HDBC is patterned loosely after Perl's DBI, with a few thoughts from > Java's JDBC, Python's DB-API, and HSQL mixed in. > > I believe it has fixed all of the above issues. The HDBC backends that > I've written (Sqlite3, PostgreSQL, and ODBC) all use Haskell's C memory > management tools, which *should* ensure that there is no memory > leakage. > > I use it for production purposes in various applications at work, > connecting to both Free and proprietary databases. I also use it in my > personal projects. hpodder, for instance, stores podcast > information in > a Sqlite3 database accessed via HDBC. I have found HDBC+Sqlite3 to be a > particularly potent combination for a number of smaller projects. > > http://software.complete.org/hdbc/wiki/HdbcUsers > has a list of some > programs that are known to use HDBC. Feel free to add yours to it. > > -- John > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > > > -- > br, > Isto > > > ------------------------------------------------------------------------ > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From drtomc at gmail.com Wed Aug 1 01:44:32 2007 From: drtomc at gmail.com (Thomas Conway) Date: Wed Aug 1 01:36:54 2007 Subject: [Haskell-cafe] Backpatching Message-ID: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> Hi All, One of the things I've been working on lately is some ASN.1 stuff.One of the first things I wrote in Haskell was an ASN.1 parser. It only worked for a subset, and I'm revisiting it to make it handle a larger subset. One of the things that gets messy is that in lots of places you can put either a thing or a reference to a thing (i.e. the name of a thing defined elsewhere). For example, consider the production: NamedNumber ::= identifier "(" SignedNumber ")" | identifier "(" DefinedValue ")" If we ignore the second alternative, the natural translation into a Parsec parser would look like: namedNumber = do name <- identifier val <- parens signedNumber return (name, val) Now to handle the second alternative is easy enough: namedNumber = do name <- identifier val <- parens (fmap Left signedNumber <|> fmap Right definedValue) return (name, val) however because names can be used before they are defined the result typegoes from being type NamedNumber = (Name,Integer) to type NamedNumber = (Name,Either Integer Name) Nothing too terrible so far. The messiness comes in when you considerthe number of places that you have to replace a type 't' with (Either t Name). I'd really like to avoid having to do this. If I were using Prolog, I could finesse the problem by introducing afree variable and filling it in when I come across the definition[*]. Logic variable backpatching. :-) So one possibility would be to return a closure: ... return $ \bindings -> (name,resolve val bindings) resolve :: (Either t Name) -> Map Name t -> t or something like that. Then when you get to the end, you apply the bindings and voila, out pops the simple type. I'm not sure this will work quite as well as it sounds. This sounds like a common problem type. Is there a well known solution to this sort of problem? cheers, Tom [*] And then at the end use var/1 to look for undefined names. Urk. Actually, if I were using Prolog in the way most Prolog programmers use it, I wouldn't be thinking about the types. -- Dr Thomas Conway drtomc@gmail.com Silence is the perfectest herald of joy: I were but little happy, if I could say how much. From alex at alexjacobson.com Wed Aug 1 01:45:56 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Wed Aug 1 01:38:34 2007 Subject: [Haskell-cafe] OS swapping and haskell data structures Message-ID: <46B01E14.2020109@alexjacobson.com> If you create a Data.Map or Data.Set larger than fits in physical memory, will OS level swapping enable your app to behave reasonably or will things just die catastrophically as you hit a memory limit? -Alex- From bulat.ziganshin at gmail.com Wed Aug 1 01:45:01 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Wed Aug 1 01:39:47 2007 Subject: [Haskell-cafe] i need wxHaskell compiled for ghc 6.6.1 on Windows In-Reply-To: References: <20070720120236.CC2543244FF@www.haskell.org> <20070721052930.GA5934@dewdrop.local> <943563891.20070722180350@gmail.com> <4a0b969d0707220720v644de98es2122a0455ffa1e20@mail.gmail.com> <1806526956.20070725171858@gmail.com> Message-ID: <1234735448.20070801094501@gmail.com> Hello shelarcy, Wednesday, August 1, 2007, 4:03:52 AM, you wrote: >> problems. the only question that remains - does this version supports >> unicode? > Yes. Current darcs repository version support only unicode > enabled version. great, it's all what i need. but i'm still curious about other features enabled when building this package. can i see config.gcc or build.cfg or setup.h or any other file that shows feature list? also it will be useful to include such file with the next builds of wxHaskell -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From stefanor at cox.net Wed Aug 1 01:59:01 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 1 01:51:27 2007 Subject: [Haskell-cafe] OS swapping and haskell data structures In-Reply-To: <46B01E14.2020109@alexjacobson.com> References: <46B01E14.2020109@alexjacobson.com> Message-ID: <20070801055901.GA6033@localhost.localdomain> On Tue, Jul 31, 2007 at 10:45:56PM -0700, Alex Jacobson wrote: > If you create a Data.Map or Data.Set larger than fits in physical memory, > will OS level swapping enable your app to behave reasonably or will things > just die catastrophically as you hit a memory limit? Data.{Set,Map} uses balanced binary trees. So if you have a 1 billion element data set which is so large that no significant fraction of it fits into cache, you can expect to access a random element in ~9 seeks, which is less than a second... good enough? This is a lot worse than it could be because memory access is too transparent. When GHC triggers a page fault, the Right Thing to do is for Linux to somehow put *that haskell thread* to sleep; but instead it will put the entire capability (or your whole program on the non-threading rts) to sleep. Linux's filesystems (which use various kinds of trees internally) avoid this issue by using asynchronous IO requests, but that's not an option for VM since there's only so much room for callbacks in a MOV instruction! There is much fertile territory for OS design space exploration here! Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070731/7ad34934/attachment.bin From stefanor at cox.net Wed Aug 1 02:04:18 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 1 01:56:43 2007 Subject: [Haskell-cafe] Backpatching In-Reply-To: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> References: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> Message-ID: <20070801060418.GB6033@localhost.localdomain> On Wed, Aug 01, 2007 at 03:44:32PM +1000, Thomas Conway wrote: > This sounds like a common problem type. Is there a well known solution > to this sort of problem? Mmm... logic programming? http://citeseer.ist.psu.edu/claessen00typed.html You'll only need the code for logic-variables, and even that can be simplified because your "terms" are non-recursive. (Even in the recursive case, a logic program like a HM typechecker usually only needs ~50 lines of prelude). (If you want an less enlightening answer, Map String (STRef s (Maybe Integer))).. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070731/4548103b/attachment-0001.bin From derek.a.elkins at gmail.com Wed Aug 1 02:40:51 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Wed Aug 1 02:33:19 2007 Subject: [Haskell-cafe] Backpatching In-Reply-To: <20070801060418.GB6033@localhost.localdomain> References: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> <20070801060418.GB6033@localhost.localdomain> Message-ID: <1185950451.6796.1.camel@derek-laptop> On Tue, 2007-07-31 at 23:04 -0700, Stefan O'Rear wrote: > On Wed, Aug 01, 2007 at 03:44:32PM +1000, Thomas Conway wrote: > > This sounds like a common problem type. Is there a well known solution > > to this sort of problem? > > Mmm... logic programming? > > http://citeseer.ist.psu.edu/claessen00typed.html > > You'll only need the code for logic-variables, and even that can be > simplified because your "terms" are non-recursive. (Even in the > recursive case, a logic program like a HM typechecker usually only needs > ~50 lines of prelude). If someone is interested, I did transcribe and mildly generalize the code from that paper. From kaveh.shahbazian at gmail.com Wed Aug 1 03:02:11 2007 From: kaveh.shahbazian at gmail.com (Kaveh Shahbazian) Date: Wed Aug 1 02:54:33 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer Message-ID: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> This is about to put a definition/description to test. So please cooperate! ;) Is this a useful ? sufficient, not complete ? definition/description for a monad; for an imperative mind: (?) "A monad is like a loop that can run a new function against it's variable in each iteration." (I insist on the simplicity! And I will resist any expansion of this sentence (except for an exceptional note that I think of it hardly). I think there is not any complete definitions in computer world. At least there are many things to know when you want to use them in practice. So please have this in mind and review me!) Cheers :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/1bb8bff3/attachment.htm From bulat.ziganshin at gmail.com Wed Aug 1 03:59:57 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Wed Aug 1 03:54:37 2007 Subject: [Haskell-cafe] Re: HDBC or HSQL In-Reply-To: <46B00D4F.6090206@alexjacobson.com> References: <470880360707300831s44170261lb5d2002d1f56e70b@mail.gmail.com> <46B00D4F.6090206@alexjacobson.com> Message-ID: <1449382301.20070801115957@gmail.com> Hello Alex, Wednesday, August 1, 2007, 8:34:23 AM, you wrote: > I am asking because I am trying to make HAppS a reasonable replacement > for all contexts in which you would otherwise use an external relational > database except those in which an external SQL database is a specific > requirement. where i can read about such usage? -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From dry.green.tea at gmail.com Wed Aug 1 04:16:50 2007 From: dry.green.tea at gmail.com (Alexis Hazell) Date: Wed Aug 1 04:09:17 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> Message-ID: <200708011816.51278.dry.green.tea@gmail.com> On Wednesday 01 August 2007 17:02, Kaveh Shahbazian wrote: > This is about to put a definition/description to test. So please cooperate! > ;) > Is this a useful ? sufficient, not complete ? definition/description for a > monad; for an imperative mind: (?) > > "A monad is like a loop that can run a new function against it's variable > in each iteration." At least in the context of Haskell, that's not correct. For a recent discussion about a simple definition of Haskell monads, see the thread beginning at: http://permalink.gmane.org/gmane.comp.lang.haskell.cafe/25882 Alexis. From haskell at list.mightyreason.com Wed Aug 1 04:44:08 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Wed Aug 1 04:36:41 2007 Subject: [Haskell-cafe] Re: [Haskell] View patterns in GHC: Request?for?feedback In-Reply-To: <20070731230417.GA4866@localhost.localdomain> References: <20070723090900.GA25820@cs.cmu.edu> <46A87C01.5020808@list.mightyreason.com> <200707270902.50113.jcast@ou.edu> <20070727175124.GB12477@darcs.net> <20070731223153.GD12386@darcs.net> <20070731230417.GA4866@localhost.localdomain> Message-ID: Discussion continues below quoted text... Stefan O'Rear wrote: > On Tue, Jul 31, 2007 at 03:31:54PM -0700, David Roundy wrote: >> On Mon, Jul 30, 2007 at 11:47:46AM +0100, Jon Fairbairn wrote: >>> ChrisK writes: >>> >>>> And the readability is destroyed because you cannot do any type inference in >>>> your head. >>>> >>>> If you see >>>> >>>> { >>>> Matrix m = ....; >>>> Matrix x = m * y; >>>> ...; >>>> } >>>> >>>> Then you know very little about the possible types of y >>>> since can only conclude that: >>> [snippage] This is all very horrid, but as far as I can tell >>> what I was proposing wouldn't lead to such a mess, except >>> possibly via defaulting, which, as the least important >>> aspect of the idea could easily be abandoned. >> What your suggestion would do would be to make the type inferred for every >> pattern-matched function polymorphic, which means that in order to >> determine the correctness of a function you'd need to examine all other >> modules. Similarly, if you fail to include a type signature in some simple >> pattern-matched function in a where clause, adding an import of another >> module could make that function fail to compile (with an undeterminable >> type error). > > Excuse me? One of the most critical properties of type classes is that > adding new instances can never make old code that uses old instances > stop compiling; the worst you could get is a definition conflict. > > Stefan That is true, and it is one of of the perfect things about type classes. But that is not the problem with some of the proposals to make normal syntax patterns always look for a View inference. The problem is that to read any pattern match I have to know which View instance was chosen. So each and every pattern match requires me to run a type checker in my head which draws on all the View instances which were implicitly imported into the current module. That adding another invisible instance does not break the code is irrelevant, the problem is that huge amount of effort it takes the human reader to prove to herself or himself that any particular pattern match has been correctly understood. It should require a new syntax to invoke this complexity. -- Chris From haskell at list.mightyreason.com Wed Aug 1 05:32:01 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Wed Aug 1 05:25:06 2007 Subject: [Haskell-cafe] Re: Backpatching In-Reply-To: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> References: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> Message-ID: Thomas Conway wrote: > One of the things that gets messy is that in lots of places you can > put either a thing or a reference to a thing (i.e. the name of a thing > defined elsewhere). For example, consider the production: > > NamedNumber ::= identifier "(" SignedNumber ")" > | identifier "(" DefinedValue ")" > I like solving this with either a (WriterT Parser) or using the Parsec state to lazily access the final mapping. Here is a working Toy example where 'finalMap' is used during the parsing. Parsec was a bit too strict with the return of 'parseVal' so I had to use a (data Box) to make it lazy: > import Text.ParserCombinators.Parsec > > import Data.Maybe > import qualified Data.Map as M > > data Box a = Box {unBox :: a} > > input = unlines $ > [ "name(ref)" > , "ref=7" > ] > > data Toy = Toy String Int deriving (Show) > > myParse s = toys where > result = runParser parser M.empty "Title" s > toys = either Left (Right . fst) result > > lookupRef r = Box (finalMap M.! r) > where finalMap = either undefined snd result > > parser = do > maybeToyList <- many parseLine > defMap <- getState > return (catMaybes maybeToyList,defMap) > > parseLine = try parseToy <|> parseDef <|> (char '\n' >> return Nothing) > > parseToy = do > name <- many1 letter > val <- between (char '(') (char ')') (try parseVal <|> parseRef) > return (Just (Toy name (unBox val))) > > parseVal = do > s <- many1 digit > return (Box (read s)) > > parseRef = do > s <- many1 letter > return (lookupRef s) > > parseDef = do > s <- many1 letter > char '=' > v <- parseVal > defMap <- getState > let defMap' = M.insert s (unBox v) defMap > setState $! defMap' > return Nothing When I run it in ghci I get: > *Main> myParse input > Right [Toy "name" 7] Cheers, Chris From jon.fairbairn at cl.cam.ac.uk Wed Aug 1 06:06:09 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Wed Aug 1 05:59:40 2007 Subject: [Haskell-cafe] Re: [Haskell] View patterns in GHC: Request?for?feedback References: <20070723090900.GA25820@cs.cmu.edu> <46A87C01.5020808@list.mightyreason.com> <200707270902.50113.jcast@ou.edu> <20070727175124.GB12477@darcs.net> <20070731223153.GD12386@darcs.net> Message-ID: David Roundy writes: > On Mon, Jul 30, 2007 at 11:47:46AM +0100, Jon Fairbairn wrote: > > [snippage] This is all very horrid, but as far as I can tell > > what I was proposing wouldn't lead to such a mess, except > > possibly via defaulting, which, as the least important > > aspect of the idea could easily be abandoned. > > What your suggestion would do would be to make the type inferred for every > pattern-matched function polymorphic, No it wouldn't. I reiterate: constructors would either belong to a class or to a datatype, so for constructors that belong to a datatype the situation would be exactly as before. It's unfortunate that when I wrote my example I assumed that everyone would understand that for some classes we would have defaults (because we already have this: the constructors for Integer effectively belong to a class and are defaulted to Integer). I'm now quite convinced that using defaults together with more general overloaded constructors would be a mistake, but that's all you've managed to convince me of! Yes, there is a problem that importing a class with a constructor into a scope that declares the same constructor as a data constructor would cause difficulties (namely the module would nolonger compile), but aren't they exactly the same difficulties as when the name in question is just a function name? -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From wagner.andrew at gmail.com Wed Aug 1 08:43:28 2007 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Wed Aug 1 08:35:48 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> Message-ID: This seems wrong to me. A monad is, first and foremost, a type constructor class. I'm not sure how you can really compare that to a loop. But perhaps the easiest way to test your definition would be to ask this: How is, for example, the Maybe monad like a loop, in your definition? On 8/1/07, Kaveh Shahbazian wrote: > This is about to put a definition/description to test. So please cooperate! > ;) > Is this a useful ? sufficient, not complete ? definition/description for a > monad; for an imperative mind: (?) > > "A monad is like a loop that can run a new function against it's variable in > each iteration." > > (I insist on the simplicity! And I will resist any expansion of this > sentence (except for an exceptional note that I think of it hardly). > I think there is not any complete definitions in computer world. At least > there are many things to know when you want to use them in practice. So > please have this in mind and review me!) > > Cheers :) > > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From ithika at gmail.com Wed Aug 1 08:54:24 2007 From: ithika at gmail.com (Dougal Stanton) Date: Wed Aug 1 08:46:45 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> Message-ID: <2d3641330708010554g303cc804v71a458605f1c240b@mail.gmail.com> On 01/08/07, Andrew Wagner wrote: > This seems wrong to me. A monad is, first and foremost, a type > constructor class. I'm not sure how you can really compare that to a > loop. But perhaps the easiest way to test your definition would be to > ask this: How is, for example, the Maybe monad like a loop, in your > definition? I am baffled by this discussion. I thought monads were something to do with boxes of toxic apples in space? Obviously we can relate monadic apples to arrows through the William Tell analogy. And erm... yeah. Still needs a little polishing. I just hope the whole metaphor isn't rotten to the core. I will be here all week. Please, try the spice cake. Cheers, D. From dav.vire+haskell at gmail.com Wed Aug 1 09:15:47 2007 From: dav.vire+haskell at gmail.com (david48) Date: Wed Aug 1 09:08:08 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> Message-ID: <4c88418c0708010615y2e688376x3842746028c67183@mail.gmail.com> On 8/1/07, Andrew Wagner wrote: > This seems wrong to me. A monad is, first and foremost, a type > constructor class. I'm not sure how you can really compare that to a > loop. But perhaps the easiest way to test your definition would be to > ask this: How is, for example, the Maybe monad like a loop, in your > definition? As a beginner haskeller coming from an imperative experience, I think I understood what he meant. say you have this code : putStrLn "1" >> putStrLn "2" >> putStrLn "3" you can imagine each of the calls to putStrLn gets implicitly passed a variable (here, the world ) and they happen in succession so it's "like a loop". Except that a loop... loops so the comparison is far fetched. From jim at sdf-eu.org Wed Aug 1 09:21:21 2007 From: jim at sdf-eu.org (Jim Burton) Date: Wed Aug 1 09:13:41 2007 Subject: [Haskell-cafe] Backpatching In-Reply-To: <1185950451.6796.1.camel@derek-laptop> References: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> <20070801060418.GB6033@localhost.localdomain> <1185950451.6796.1.camel@derek-laptop> Message-ID: <11945491.post@talk.nabble.com> Derek Elkins wrote: > > On Tue, 2007-07-31 at 23:04 -0700, Stefan O'Rear wrote: >> On Wed, Aug 01, 2007 at 03:44:32PM +1000, Thomas Conway wrote: >> > This sounds like a common problem type. Is there a well known solution >> > to this sort of problem? >> >> Mmm... logic programming? >> >> http://citeseer.ist.psu.edu/claessen00typed.html >> >> You'll only need the code for logic-variables, and even that can be >> simplified because your "terms" are non-recursive. (Even in the >> recursive case, a logic program like a HM typechecker usually only needs >> ~50 lines of prelude). > > If someone is interested, I did transcribe and mildly generalize the > code from that paper. > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > Hi Derek, I'd be interested in looking at that -- have you put it online? -- View this message in context: http://www.nabble.com/Backpatching-tf4198168.html#a11945491 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From cconway at cs.nyu.edu Wed Aug 1 09:27:26 2007 From: cconway at cs.nyu.edu (Christopher L Conway) Date: Wed Aug 1 09:19:48 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <4c88418c0708010615y2e688376x3842746028c67183@mail.gmail.com> References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> <4c88418c0708010615y2e688376x3842746028c67183@mail.gmail.com> Message-ID: <4a051d930708010627t2d95ac9fg75537da8ac20f3ea@mail.gmail.com> On 8/1/07, david48 wrote: > As a beginner haskeller coming from an imperative experience, I think > I understood what he meant. > > say you have this code : > > putStrLn "1" >> putStrLn "2" >> putStrLn "3" > > you can imagine each of the calls to putStrLn gets implicitly passed a > variable (here, the world ) and they happen in succession so it's > "like a loop". Why isn't this "like a semicolon"? Chris From wagner.andrew at gmail.com Wed Aug 1 09:27:43 2007 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Wed Aug 1 09:20:04 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <4c88418c0708010615y2e688376x3842746028c67183@mail.gmail.com> References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> <4c88418c0708010615y2e688376x3842746028c67183@mail.gmail.com> Message-ID: > say you have this code : > > putStrLn "1" >> putStrLn "2" >> putStrLn "3" > > you can imagine each of the calls to putStrLn gets implicitly passed a > variable (here, the world ) and they happen in succession so it's > "like a loop". It breaks down further as soon as you add any amount of complexity to the code as well. E.g.: putStrLn "1" >> getLine >>= \line -> putStrLn line >> putStrLn "end" This prints something, gets something from the user and prints it, and then prints something else. The equivalent imperative pseudo-code is something like: print "foo"; line = inputLine(); print line; print "end"; Not loop-ish at all! From dav.vire+haskell at gmail.com Wed Aug 1 09:59:35 2007 From: dav.vire+haskell at gmail.com (david48) Date: Wed Aug 1 09:51:55 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> <4c88418c0708010615y2e688376x3842746028c67183@mail.gmail.com> Message-ID: <4c88418c0708010659w4a4d15aekaefa34b6f2a9977b@mail.gmail.com> On 8/1/07, Andrew Wagner wrote: > > you can imagine each of the calls to putStrLn gets implicitly passed a > > variable (here, the world ) and they happen in succession so it's > > "like a loop". > It breaks down further as soon as you add any amount of complexity to > the code as well. E.g.: [....] > Not loop-ish at all! I totally agree I was just stating how I understood the original poster's statement :) Personally I showed haskell to a Friend last week end. To explain some monadic code I explained it somewhat this way ( please keep in mind that I'm a beginner so the explanation I gave him is probably not accurate ) I told him that in a lazy functional programming language you can't decide when a function gets evaluated or not. I then told him that it gets problematic if you want evaluate some functions in sequence. I also told him that haskell is a pure language, that is there is no side effects in the functions. I then told him that it's a problem if you want to interact with the outside world (IO) I explained that a monad is a way to get functions evaluated in a specific order, with a type such that you can't mix actions with pure functions. I told him that monads are just a special datatype and implementation of 2 functions : - a function that lets you evaluate a function before evaluating the next one, taking the output of the first function to feed the input of the second. - a function that takes a pure value and "promotes" to the monad's type. I told him that in the case of IO the datatype in question is IO and it contains data about the outside world, but there are many other monads, but I didn't go there too much because it's not totally clear for me. He seemed to be not too much confused by the concept, so I hope that I didn't told him too much inaccuracies... From dav.vire+haskell at gmail.com Wed Aug 1 10:05:43 2007 From: dav.vire+haskell at gmail.com (david48) Date: Wed Aug 1 09:58:03 2007 Subject: [Haskell-cafe] Indentation woes In-Reply-To: <7CEC32B7-F9B7-4312-9F63-A479DE0B2DBD@cs.otago.ac.nz> References: <20070726192337.GA4598@localhost.localdomain> <20070726220052.GA5028@localhost.localdomain> <7CEC32B7-F9B7-4312-9F63-A479DE0B2DBD@cs.otago.ac.nz> Message-ID: <4c88418c0708010705r67df16cawcc4db8caf25a2d24@mail.gmail.com> On the topic of indenting, it would be nice if there was a way to tell the compiler the size of the tab characters. The way it is now, I have to use space characters to indent. It's not really a problem though. From duncan.coutts at worc.ox.ac.uk Wed Aug 1 10:12:31 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 1 10:03:44 2007 Subject: [Haskell-cafe] Indentation woes In-Reply-To: <4c88418c0708010705r67df16cawcc4db8caf25a2d24@mail.gmail.com> References: <20070726192337.GA4598@localhost.localdomain> <20070726220052.GA5028@localhost.localdomain> <7CEC32B7-F9B7-4312-9F63-A479DE0B2DBD@cs.otago.ac.nz> <4c88418c0708010705r67df16cawcc4db8caf25a2d24@mail.gmail.com> Message-ID: <1185977551.5989.67.camel@localhost> On Wed, 2007-08-01 at 16:05 +0200, david48 wrote: > On the topic of indenting, it would be nice if there was a way to tell > the compiler the size of the tab characters. > > The way it is now, I have to use space characters to indent. Good! You're doing exactly the right thing according to the Haskell style guide: http://urchin.earth.li/~ian/style/haskell.html :-) Duncan From bf3 at telenet.be Wed Aug 1 10:26:47 2007 From: bf3 at telenet.be (peterv) Date: Wed Aug 1 10:19:21 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer Message-ID: <00d401c7d447$fe1c1bd0$fa545370$@be> Kaveh> "A monad is like a loop that can run a new function against its variable in each iteration." I?m an imperative programmer learning Haskell, so I?m a newbie, but I?ll give it a try ? Making mistakes is the best way to learn it ;) There are lots of different kinds of monads, but let?s stick to the IO monad first, which you seem to refer to. No *an IO monad is not a loop at all*. Instead, from an imperative programmer?s point of view, the following might be better: ?an IO monad is a delayed action that will be executed as soon as that action is needed for further evaluation of the program.? The simple program main = getLine >>= putStrLn can be visually represented as (see attachment) The ?world? (=a representation of your computer?s hardware) is passed to the main function, which passes it to all actions that it encounters during its lazy evaluation, causing the executing of the actions as an effect. The red wire through which the ?world flows? is a ?single thread?, it cannot be split (because the physical world cannot be copied!!!), so no unwanted side effects can ever occur, making IO safe in Haskell. When you write your IO program, this world object is never available (the IO type is a special internal type), so the red wire is erased from the diagram, and the getLine and putStrLn boxes become ?delayed actions?. Imperative programmers like myself might initially be confused when they see Haskell?s do notation, because it looks like the actions are strict statements as in C/C++/Pascal/Java/C#/etc, but they are not. For example, try the following program: main = do last [ putStrLn "NOT executed although it is first in the list, as it is not used by the main function!", putStrLn "This action IS executed because it is evaluated by the main function." ] This is of course all due to Haskell?s laziness which only evaluates just those expressions that it needs to evaluate the main function. One thing to note in the diagram above is that the getLine box has TWO outputs, the String and the World. But functions can only have a single output, but this can be tuple. Hence the passing of the world from one box to the other is a bit more complicated. It is this pattern of extracting both values from the output and passing them to the next function and other related combinations that form the generic monad class, which can be used for many more things than IO. See http://haskell.org/haskellwiki/IO_inside for a much deeper and more correct explanation ? And for the pros here, did this newbie make any sense? Probably not ;-) Oh no, yet another monad explanation!!! Now the universe will most certainly collapse? No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.476 / Virus Database: 269.11.0/929 - Release Date: 31/07/2007 17:26 -------------- next part -------------- A non-text attachment was scrubbed... Name: IO monad.GIF Type: image/gif Size: 7808 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/32e3b083/IOmonad-0001.gif From A.M.Gimblett at swansea.ac.uk Wed Aug 1 10:28:01 2007 From: A.M.Gimblett at swansea.ac.uk (Andy Gimblett) Date: Wed Aug 1 10:20:27 2007 Subject: [Haskell-cafe] Cartesian product of a Set Message-ID: <20070801142801.GA7647@cspcag2.swan.ac.uk> Hi all, Is this a reasonable way to compute the cartesian product of a Set? > cartesian :: Ord a => S.Set a -> S.Set (a,a) > cartesian x = S.fromList [(i,j) | i <- xs, j <- xs] > where xs = S.toList x It's a fairly "obvious" way to do it, but I wondered if there were any hidden gotchas. I'm particularly concerned by toList (O(n)) fromList (O(n log n)) - but for other reasons I'd really like to be using Set rather than List for this (I think). Many thanks for any thoughts, -Andy -- Andy Gimblett Computer Science Department University of Wales Swansea http://www.cs.swan.ac.uk/~csandy/ From lgreg.meredith at biosimilarity.com Wed Aug 1 10:48:41 2007 From: lgreg.meredith at biosimilarity.com (Greg Meredith) Date: Wed Aug 1 10:41:02 2007 Subject: [Haskell-cafe] monads and groups -- instead of loops Message-ID: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> Haskellians, Though the actual metaphor in the monads-via-loops doesn't seem to fly with this audience, i like the spirit of the communication and the implicit challenge: find a pithy slogan that -- for a particular audience, like imperative programmers -- serves to uncover the essence of the notion. i can't really address that audience as my first real exposure to programming was scheme and i moved into concurrency and reflection after that and only ever used imperative languages as means to an end. That said, i think i found another metaphor that summarizes the notion for me. In the same way that the group axioms organize notions of symmetry, including addition, multiplication, reflections, translations, rotations, ... the monad(ic axioms) organize(s) notions of snapshot (return) and update (bind), including state, i/o, control, .... In short group : symmetry :: monad : update Best wishes, --greg -- L.G. Meredith Managing Partner Biosimilarity LLC 505 N 72nd St Seattle, WA 98103 +1 206.650.3740 http://biosimilarity.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/2c03d3f5/attachment.htm From allbery at ece.cmu.edu Wed Aug 1 10:58:19 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Wed Aug 1 10:50:42 2007 Subject: [Haskell-cafe] Indentation woes In-Reply-To: <4c88418c0708010705r67df16cawcc4db8caf25a2d24@mail.gmail.com> References: <20070726192337.GA4598@localhost.localdomain> <20070726220052.GA5028@localhost.localdomain> <7CEC32B7-F9B7-4312-9F63-A479DE0B2DBD@cs.otago.ac.nz> <4c88418c0708010705r67df16cawcc4db8caf25a2d24@mail.gmail.com> Message-ID: <61D2DF2B-56E8-4291-B350-5383FE9E1FCA@ece.cmu.edu> On Aug 1, 2007, at 10:05 , david48 wrote: > On the topic of indenting, it would be nice if there was a way to tell > the compiler the size of the tab characters. > > The way it is now, I have to use space characters to indent. The problem with that is, while there's a standard for the width of a tab on Unix, there isn't on Windows. It's really only safe to use spaces for indentation. Thus, it's better to use an editor which converts tabs to spaces in a specified manner, so you can use whatever tabs you're comfortable with (or none; Emacs generally uses tab to mean "indent appropriately") but the resulting file uses spaces and will behave reliably anywhere. -- 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 dav.vire+haskell at gmail.com Wed Aug 1 11:04:02 2007 From: dav.vire+haskell at gmail.com (david48) Date: Wed Aug 1 10:56:23 2007 Subject: [Haskell-cafe] Indentation woes In-Reply-To: <61D2DF2B-56E8-4291-B350-5383FE9E1FCA@ece.cmu.edu> References: <20070726192337.GA4598@localhost.localdomain> <20070726220052.GA5028@localhost.localdomain> <7CEC32B7-F9B7-4312-9F63-A479DE0B2DBD@cs.otago.ac.nz> <4c88418c0708010705r67df16cawcc4db8caf25a2d24@mail.gmail.com> <61D2DF2B-56E8-4291-B350-5383FE9E1FCA@ece.cmu.edu> Message-ID: <4c88418c0708010804y4b663ce0u1f082ab9098ae526@mail.gmail.com> On 8/1/07, Brandon S. Allbery KF8NH wrote: > > On Aug 1, 2007, at 10:05 , david48 wrote: > > > On the topic of indenting, it would be nice if there was a way to tell > > the compiler the size of the tab characters. > > > > The way it is now, I have to use space characters to indent. > > The problem with that is, while there's a standard for the width of a > tab on Unix, there isn't on Windows. It's really only safe to use > spaces for indentation. On second thought, I don't even know why I posted this. There's so many things far more important that tabs, and using spaces is truly the only safe way. Sorry for the noise. From wagner.andrew at gmail.com Wed Aug 1 11:14:36 2007 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Wed Aug 1 11:06:57 2007 Subject: [Haskell-cafe] monads and groups -- instead of loops In-Reply-To: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> References: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> Message-ID: That's great, unless the imperative programmer happens to be one of the 90% of programmers that isn't particularly familiar with group theory... On 8/1/07, Greg Meredith wrote: > Haskellians, > > Though the actual metaphor in the monads-via-loops doesn't seem to fly with > this audience, i like the spirit of the communication and the implicit > challenge: find a pithy slogan that -- for a particular audience, like > imperative programmers -- serves to uncover the essence of the notion. i > can't really address that audience as my first real exposure to programming > was scheme and i moved into concurrency and reflection after that and only > ever used imperative languages as means to an end. That said, i think i > found another metaphor that summarizes the notion for me. In the same way > that the group axioms organize notions of symmetry, including addition, > multiplication, reflections, translations, rotations, ... the monad(ic > axioms) organize(s) notions of snapshot (return) and update (bind), > including state, i/o, control, .... In short > > group : symmetry :: monad : update > > Best wishes, > > --greg > > -- > L.G. Meredith > Managing Partner > Biosimilarity LLC > 505 N 72nd St > Seattle, WA 98103 > > +1 206.650.3740 > > http://biosimilarity.blogspot.com > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From wagner.andrew at gmail.com Wed Aug 1 11:31:45 2007 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Wed Aug 1 11:24:04 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <00d401c7d447$fe1c1bd0$fa545370$@be> References: <00d401c7d447$fe1c1bd0$fa545370$@be> Message-ID: > > "an IO monad is a delayed action that will be executed as soon as that action is needed for further evaluation of the program." > I'm not sure I like this, as it seems to confuse the issue. An expert should correct me if I'm wrong, but monads in and of themselves don't depend on laziness. Rather, *everything* in haskell is lazy, unless explicitly strict-ified. As for the rest of your email, I don't necessarily disagree, but don't find it particularly helpful either. Which may, of course, be a personal thing. For me, I think the key to monads is to really understand 2 things about them: 1.) They are simply type constructor classes 2.) Monads are about sequencing For point 2, think about the two main things you have to define to create an instance of a monad: (>>=) :: m a -> (a -> m b) -> m b That is, you have two monadic actions, m a and m b, and bind says how to take the result of the first and fit it into the second -- in sequence! (>>) :: m a -> m b -> m b Again, we have 2 monadic actions that we're composing, in sequence. This time, we're just discarding the result of the first. From jgbailey at gmail.com Wed Aug 1 11:36:00 2007 From: jgbailey at gmail.com (Justin Bailey) Date: Wed Aug 1 11:28:20 2007 Subject: [Haskell-cafe] Knuth Morris Pratt for Lazy Bytestrings implementation In-Reply-To: <20070801020709.GF21697@cse.unsw.EDU.AU> References: <20070801020709.GF21697@cse.unsw.EDU.AU> Message-ID: On 7/31/07, Donald Bruce Stewart wrote: > jgbailey: > Also, be sure to compare against a naive search, optimised for > strict and lazy bytestrings, > > http://hpaste.org/1803 > > If its not faster than those 2, then you're doing something wrong :) > > -- Don Yes, I was really hoping someone (dons :)) would look at my code and give any suggestions. Did the attachment come through? Justin From jgbailey at gmail.com Wed Aug 1 11:39:29 2007 From: jgbailey at gmail.com (Justin Bailey) Date: Wed Aug 1 11:31:50 2007 Subject: [Haskell-cafe] Knuth Morris Pratt for Lazy Bytestrings implementation In-Reply-To: <59534.203.185.215.144.1185929486.squirrel@dockerz.net> References: <59534.203.185.215.144.1185929486.squirrel@dockerz.net> Message-ID: On 7/31/07, Tim Docker wrote: > Now I wonder what that 7MB file might be? :-) > > We (team TNT) implemented KMP over lazy bytestrings as part of our icfp > 2007 contest entry. As I remember, for the DNA evaluator it gave modest > speed improvements over more na?ve searching. Our implementation was based > upon this blog post: > > http://twan.home.fmf.nl/blog/ > > Tim What prompted this was we adapted Oleg's KMP module for PackedStrings to lazy bytestrings, and it was too slow. I am actually interested in implementing KMP for Data.Sequence, but wanted to get bytestrings out of the way first. Justin From mail at joachim-breitner.de Wed Aug 1 11:52:10 2007 From: mail at joachim-breitner.de (Joachim Breitner) Date: Wed Aug 1 11:44:32 2007 Subject: [Haskell-cafe] Cartesian product of a Set In-Reply-To: <20070801142801.GA7647@cspcag2.swan.ac.uk> References: <20070801142801.GA7647@cspcag2.swan.ac.uk> Message-ID: <1185983530.4312.36.camel@otto.ehbuehl.net> Hi, Am Mittwoch, den 01.08.2007, 15:28 +0100 schrieb Andy Gimblett: > Hi all, > > Is this a reasonable way to compute the cartesian product of a Set? > > > cartesian :: Ord a => S.Set a -> S.Set (a,a) > > cartesian x = S.fromList [(i,j) | i <- xs, j <- xs] > > where xs = S.toList x > > It's a fairly "obvious" way to do it, but I wondered if there were any > hidden gotchas. I'm particularly concerned by toList (O(n)) fromList > (O(n log n)) - but for other reasons I'd really like to be using Set > rather than List for this (I think). Using only functions from the Set module, you could write: > catesian s = fold (\v prod -> prod `union` map ((,)v) s ) empty s But this won?t be faster, I guess, as map is O(n?log n) and fold is O(n) OTOH, ((,)v) should be monotonic, so it might be faster (and hopefully still correct) to write: > catesian s = fold (\v prod -> prod `union` mapMonotonic ((,)v) s ) empty s Greetings, Joachim -- Joachim Breitner e-Mail: mail@joachim-breitner.de Homepage: http://www.joachim-breitner.de ICQ#: 74513189 From dpiponi at gmail.com Wed Aug 1 12:01:58 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Wed Aug 1 11:54:18 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: References: <00d401c7d447$fe1c1bd0$fa545370$@be> Message-ID: <625b74080708010901m65a14b98j1d17188bcc606c6@mail.gmail.com> On 8/1/07, Andrew Wagner wrote: > For me, I think the key to monads is to really > understand 2 things about them: > ... > 2.) Monads are about sequencing Now I disagree on 2. Monads are no more about sequencing than binary operators are about sequencing. Sure, if you want to, you can define an operator like (*) to be non-commutative, so that a*b is different to b*a, but that doesn't really get to the essence of what a binary operator is. And in everyday usage we use (*) to mean ordinary commutative multiplication where there is no sense of sequencing. The same holds for monads. If you want to use them for sequencing the option is there, but there are plenty of commutative monads out there, for which the order of operations doesn't matter, and the fact that they are commutative doesn't make them any less monads. So while you can use monads to sequence, I don't think sequencing gets to the essence of what monads are. I suspect I hold a minority view here... :-) -- Dan From dukedave at gmail.com Wed Aug 1 12:08:22 2007 From: dukedave at gmail.com (Dave Tapley) Date: Wed Aug 1 12:00:42 2007 Subject: [Haskell-cafe] Exiting GLUT application In-Reply-To: References: <200707312316.09949.coeus@gmx.de> Message-ID: Unfortunately whilst the new code is returning me to a 'Main >' prompt as required another problem has come up. The issue here is found when the code is executed in both GHCi (6.6) and hugs (20050308). Once the code below is loaded evaluating main opens an unfilled window as required. However if this window is closed and main is evaluated again both GHCi and hugs die thus: GHCi: Illegal instruction (core dumped) hugs: Unexpected signal Any thoughts? On 31/07/07, Dave Tapley wrote: > Excellent, thank you Marc your advice worked perfectly. > > For reference the corrected code reads: > > > import Graphics.UI.GLUT > > main = do > > getArgsAndInitialize > > createWindow "" > > actionOnWindowClose $= ContinueExectuion > > mainLoop > > Dave, > > > On 31/07/07, Marc A. Ziegert wrote: > > in old glut, the main loop was the core of the single threaded program. exiting it did mean to exit the program completely. > > in freeglut, you have alternatives. but for compatibility, it defaults to the old behaviour. > > > > > > > > - marc > > > > > > Am Dienstag, 31. Juli 2007 19:16 schrieb Dave Tapley: > > > Hi everyone, I have the following skeleton GLUT code: > > > > > > > import Graphics.UI.GLUT > > > > main = do > > > > getArgsAndInitialize > > > > createWindow "" > > > > mainLoop > > > > > > It loads into both hugs and ghci fine and when 'main' is evaluated an > > > empty window opens as expected. > > > However when closing the window (clicking the window manager's x > > > button) both hugs and ghci exit with the window, as opposed to > > > returning to the the 'Main>' prompt. > > > > > > I suspect I need some callback to exit the GUI cleanly? > > > > > > Cheers, > > > Dave > > > _______________________________________________ > > > Haskell-Cafe mailing list > > > Haskell-Cafe@haskell.org > > > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > > > > > > From jeff.polakow at db.com Wed Aug 1 12:11:51 2007 From: jeff.polakow at db.com (Jeff Polakow) Date: Wed Aug 1 12:04:15 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <625b74080708010901m65a14b98j1d17188bcc606c6@mail.gmail.com> Message-ID: Hello, > On 8/1/07, Andrew Wagner wrote: > > For me, I think the key to monads is to really > > understand 2 things about them: > > ... > > 2.) Monads are about sequencing > > Now I disagree on 2. > > Monads are no more about sequencing than binary operators are about > sequencing. Sure, if you want to, you can define an operator like (*) > to be non-commutative, so that a*b is different to b*a, but that > doesn't really get to the essence of what a binary operator is. And in > everyday usage we use (*) to mean ordinary commutative multiplication > where there is no sense of sequencing. > > The same holds for monads. If you want to use them for sequencing the > option is there, but there are plenty of commutative monads out there, > for which the order of operations doesn't matter, and the fact that > they are commutative doesn't make them any less monads. So while you > can use monads to sequence, I don't think sequencing gets to the > essence of what monads are. > > I suspect I hold a minority view here... :-) > You are entirely correct. Data dependencies enforce/specify sequencing. -Jeff --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/33b88c2c/attachment.htm From dukedave at gmail.com Wed Aug 1 12:30:53 2007 From: dukedave at gmail.com (Dave Tapley) Date: Wed Aug 1 12:23:12 2007 Subject: [Haskell-cafe] renderString problems Message-ID: Hi all, I'm having a lot of trouble using renderString from Graphics.UI.GLUT.Fonts. All my attempts to render a StrokeFont have so far failed. Using a BitmapFont I can get strings to appear but they demonstrate the odd behaviour of translating themselves a distance equal to their length every time my displayCallback function is evaluated. My requests are: * Does anyone know how to keep the position fixed? * Are there any good examples of (working) GLUT code available on the web, I'm finding it very hard to make any progress at the moment. Certainly not at Haskell speed :( I am using the following code: > import Graphics.UI.GLUT > main = do > getArgsAndInitialize > createWindow "" > displayCallback $= update > actionOnWindowClose $= ContinueExectuion > mainLoop > > update = do > clear [ColorBuffer] > renderString Fixed8By13 $ "Test string" > flush Cheers, Dave From sethg at ropine.com Wed Aug 1 12:39:14 2007 From: sethg at ropine.com (Seth Gordon) Date: Wed Aug 1 12:31:37 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> Message-ID: <46B0B732.1010905@ropine.com> My own perspective on monads is this: In procedural and OO languages, when dealing with compound data structures, we think in terms of getters (*taking data out* of the structure) and setters (*putting data in* to the structure). Languages with some impure functional features (Lisp, Scheme, Perl, Python) let you operate on lists with a "map" function ("mapcar" in Common Lisp), where instead of *taking data out* of a list, you *put a function in*, and the function manipulates each element without being aware of the context. You *turn the data structure inside-out*, as it were, so you don't have to think about how the elements are accessed. Functors are a generalization from lists to "things that can be mapped over" in general, and then monads are a generalization of functors. Haskell solves the "how can I do I/O in a pure functional language" problem by *turning the world inside-out*. Instead of taking data from the mutable outside world, using functions to manipulate it, and depositing results back into that world, you put your functions into the IO monad. It's like the joke about how a theoretical mathematician catches an elephant: build a cage, go inside, close the door, and redefine outside as inside. From misc at alpheccar.org Wed Aug 1 13:13:15 2007 From: misc at alpheccar.org (alpheccar) Date: Wed Aug 1 13:03:46 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <00d401c7d447$fe1c1bd0$fa545370$@be> References: <00d401c7d447$fe1c1bd0$fa545370$@be> Message-ID: > Kaveh> "A monad is like a loop that can run a new function against > its variable in each iteration." > > I?m an imperative programmer learning Haskell, so I?m a newbie, > but I?ll give it a try ? Making mistakes is the best way to > learn it ;) > I was a newbie not so long ago so I can understand the trouble of imperative programmers when they meet monads for the first time. I think the problem is due to a few bad tutorial still available on the web and which are making two mistakes: 1 - Focusing on the IO monad which is very special ; 2 - Detailing the implementation. As a newie we don't care and we would prefer to see how to use monads rather than how to develop monads. When you look at monads you see they can be used for controlling the evaluation order (list monad, error monad, IO monad). They can be used for side effects (IO, state monad). They can be seen as containers (list, Maybe). They can be used to provide a protected environment (tainting). So, it is difficult to see what they have in common. Of course, what they have in common is a set of algebraic laws : the monadic laws but it does not help to know it. I think that a way to see monads (and a consequence of the monadic laws) is that monads are interpreters for domain specific languages. Each monad will generally come with a runMonad function (runReader, runWriter etc...) to execute the monadic program. IO is different because runIO is controlled by the runtime and cannot be manipulated by the user. The monadic combinators >>= are used to build programs. It is a way to concatenate two small programs to create a bigger one. In fact a combinator like >>= is doing two things : building new sentences of your domain specific language and evaluating them. if you take the list monad as example : [1,2,3] >>= \x -> [x*2,x*3]. First a new sentence will be created : [[2,3],[4,6],[6,9]]. Then, it is evaluated to give [2,3,4,6,6,9]. Here the interesting part is the sentence construction one. In other monads it may be the evaluation one. So, instead of building a big sentence and then evaluating it, a monad is a dynamical interpreter. The sentences are built and evaluated progressively. But of course, as I said, I was a newbie not long ago so the experts will correct me if needed. Now, a bit of self promotion but just because it may help. I have summarized the problems I faced when I was a newbie learning Haskell : http://www.alpheccar.org/en/posts/show/67 Some people told me it was useful. It is a summary of how imperative programmers should change their state of mind to understand the Haskell way. alpheccar. > There are lots of different kinds of monads, but let?s stick to > the IO monad first, which you seem to refer to. > > No *an IO monad is not a loop at all*. Instead, from an imperative > programmer?s point of view, the following might be better: > > ?an IO monad is a delayed action that will be executed as soon as > that action is needed for further evaluation of the program.? > > The simple program > > main = getLine >>= putStrLn > > can be visually represented as (see attachment) > > The ?world? (=a representation of your computer?s hardware) is > passed to the main function, which passes it to all actions that it > encounters during its lazy evaluation, causing the executing of the > actions as an effect. > > The red wire through which the ?world flows? is a ?single > thread?, it cannot be split (because the physical world cannot be > copied!!!), so no unwanted side effects can ever occur, making IO > safe in Haskell. > > When you write your IO program, this world object is never > available (the IO type is a special internal type), so the red wire > is erased from the diagram, and the getLine and putStrLn boxes > become ?delayed actions?. > > Imperative programmers like myself might initially be confused when > they see Haskell?s do notation, because it looks like the actions > are strict statements as in C/C++/Pascal/Java/C#/etc, but they are > not. > > For example, try the following program: > > main = do last [ > putStrLn "NOT executed although it is first in the list, > as it is not used by the main function!", > putStrLn "This action IS executed because it is > evaluated by the main function." ] > > This is of course all due to Haskell?s laziness which only > evaluates just those expressions that it needs to evaluate the main > function. > > One thing to note in the diagram above is that the getLine box has > TWO outputs, the String and the World. But functions can only have > a single output, but this can be tuple. Hence the passing of the > world from one box to the other is a bit more complicated. It is > this pattern of extracting both values from the output and passing > them to the next function and other related combinations that form > the generic monad class, which can be used for many more things > than IO. > > See http://haskell.org/haskellwiki/IO_inside for a much deeper and > more correct explanation ? > > And for the pros here, did this newbie make any sense? Probably > not ;-) > > Oh no, yet another monad explanation!!! Now the universe will most > certainly collapse? > > > No virus found in this outgoing message. > Checked by AVG Free Edition. > Version: 7.5.476 / Virus Database: 269.11.0/929 - Release Date: > 31/07/2007 17:26 > > > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From lgreg.meredith at biosimilarity.com Wed Aug 1 13:12:32 2007 From: lgreg.meredith at biosimilarity.com (Greg Meredith) Date: Wed Aug 1 13:04:56 2007 Subject: [Haskell-cafe] monads and groups -- instead of loops In-Reply-To: References: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> Message-ID: <5de3f5ca0708011012v805034egaef852ece0b13bd3@mail.gmail.com> Andrew, ;-) Agreed! As i said in my previous post, i can't address the imperative programmer. i really don't think that way and have a hard time understanding people who do! (-; Best wishes, --greg On 8/1/07, Andrew Wagner wrote: > > That's great, unless the imperative programmer happens to be one of > the 90% of programmers that isn't particularly familiar with group > theory... > > On 8/1/07, Greg Meredith wrote: > > Haskellians, > > > > Though the actual metaphor in the monads-via-loops doesn't seem to fly > with > > this audience, i like the spirit of the communication and the implicit > > challenge: find a pithy slogan that -- for a particular audience, like > > imperative programmers -- serves to uncover the essence of the notion. i > > can't really address that audience as my first real exposure to > programming > > was scheme and i moved into concurrency and reflection after that and > only > > ever used imperative languages as means to an end. That said, i think i > > found another metaphor that summarizes the notion for me. In the same > way > > that the group axioms organize notions of symmetry, including addition, > > multiplication, reflections, translations, rotations, ... the monad(ic > > axioms) organize(s) notions of snapshot (return) and update (bind), > > including state, i/o, control, .... In short > > > > group : symmetry :: monad : update > > > > Best wishes, > > > > --greg > > > > -- > > L.G. Meredith > > Managing Partner > > Biosimilarity LLC > > 505 N 72nd St > > Seattle, WA 98103 > > > > +1 206.650.3740 > > > > http://biosimilarity.blogspot.com > > _______________________________________________ > > Haskell-Cafe mailing list > > Haskell-Cafe@haskell.org > > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > > > -- L.G. Meredith Managing Partner Biosimilarity LLC 505 N 72nd St Seattle, WA 98103 +1 206.650.3740 http://biosimilarity.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/0c4f17e5/attachment-0001.htm From haskell at list.mightyreason.com Wed Aug 1 14:04:25 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Wed Aug 1 13:56:54 2007 Subject: [Haskell-cafe] Re: Knuth Morris Pratt for Lazy Bytestrings implementation In-Reply-To: References: <20070801020709.GF21697@cse.unsw.EDU.AU> Message-ID: <46B0CB29.5080101@list.mightyreason.com> Justin Bailey wrote: > On 7/31/07, Donald Bruce Stewart wrote: >> jgbailey: >> Also, be sure to compare against a naive search, optimised for >> strict and lazy bytestrings, >> >> http://hpaste.org/1803 >> >> If its not faster than those 2, then you're doing something wrong :) >> >> -- Don > > Yes, I was really hoping someone (dons :)) would look at my code and > give any suggestions. Did the attachment come through? > > Justin I will make measurements. I already see that > {-# OPTIONS_GHC -fbang-patterns #-} > module KMPSeq (kmpMatch) > kmpMatch' :: B.ByteString -> Int64 -> Int -> Int64 > kmpMatch' !str !currIdx !patShift > let matchLength' !pat !str !cnt | B.null pat = {-# SCC "kmpMatch_nullPatStr" #-} cnt > matchLength' !pat !str !cnt | B.null str = {-# SCC "kmpMatch_nullStr" #-} 0 > matchLength' !pat !str !cnt | (B.head pat == B.head str) = {-# SCC "kmpMatch_eqHead" #-} Is a huge win. It now uses 3 MB instead of 243 MB and runs faster. -- Chris From iahogsp at gmail.com Wed Aug 1 14:06:55 2007 From: iahogsp at gmail.com (Isto Aho) Date: Wed Aug 1 13:59:14 2007 Subject: [Haskell-cafe] Re: HDBC or HSQL In-Reply-To: <46B00D4F.6090206@alexjacobson.com> References: <470880360707300831s44170261lb5d2002d1f56e70b@mail.gmail.com> <46B00D4F.6090206@alexjacobson.com> Message-ID: <470880360708011106h30e646dai3b79ce8f673f5ac1@mail.gmail.com> Hi, I'd like to store small matrices into a db. Number of rows and columns may vary in a way not known in advance. One might use a relation (matrixId, col, row, value) or something like that but if it is possible to put a matrix in one command into db, some queries will be easier. E.g., one relation can store several matrices and it would be easy to query, how many matrices are stored currently. With that above four tuple you can find out the number of unique matrixId's, too, but it is not as easy as with matrices. Anyhow, now I'm not sure if I should stick with HSQL any more... Earlier comments on this thread made me think that maybe it would be a better idea to try to learn enough HDBC. This would be used in a server application. Is HAppS applicable here? e.g. after some tweaking the following works with HSQL: addRows = do dbh <- connect server database user_id passwd intoDB dbh ([555,111, 50, 1000]::[Int]) ([21.0,22.0,23.0,24.0 ]::[Double]) intoDB dbh ([556,111, 50, 1000]::[Int]) ([21.0,22.0,23.0,24.0 ]::[Double]) intoDB dbh ([]::[Int]) ([]::[Double]) where intoDB dbh i_lst d_lst = catchSql (do let cmd = "INSERT INTO trial (intList, dList) VALUES (" ++ toSqlValue i_lst ++ "," ++ toSqlValue d_lst ++ ")" execute dbh cmd ) (\e -> putStrLn $ "Problem: " ++ show e) Similarly, queries can handle matrices and I like that it is now possible to select those columns or rows from the stored matrix that are needed. E.g. retrieveRecords2 :: Connection -> IO [[Double]] retrieveRecords2 c = do -- query c "select dList[1:2] from trial" >>= collectRows getRow query c "select dList from trial" >>= collectRows getRow where getRow :: Statement -> IO [Double] getRow stmt = do lst <- getFieldValue stmt "dList" return lst readTable2 = do dbh <- connect server database user_id passwd values <- retrieveRecords2 dbh putStrLn $ "dLists are : " ++ (show values) br, Isto 2007/8/1, Alex Jacobson : > > Out of curiosity, can I ask what you are actually trying to do? > > I am asking because I am trying to make HAppS a reasonable replacement > for all contexts in which you would otherwise use an external relational > database except those in which an external SQL database is a specific > requirement. > > -Alex- > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/2e41235c/attachment.htm From bos at serpentine.com Wed Aug 1 14:31:52 2007 From: bos at serpentine.com (Bryan O'Sullivan) Date: Wed Aug 1 14:24:57 2007 Subject: [Haskell-cafe] OS swapping and haskell data structures In-Reply-To: <46B01E14.2020109@alexjacobson.com> References: <46B01E14.2020109@alexjacobson.com> Message-ID: <46B0D198.2040506@serpentine.com> Alex Jacobson wrote: > If you create a Data.Map or Data.Set larger than fits in physical > memory, will OS level swapping enable your app to behave reasonably or > will things just die catastrophically as you hit a memory limit? Relying on the OS to page portions of your app in and out should always be the fallback of last resort. You are fairly guaranteed to get terrible performance because the VM subsystem can't anticipate your app's memory access patterns, and catastrophic death of either your app or other system processes is a strong possibility (Google for "OOM killer" if you want some horror stories). In many cases, you can't even rely on paging being possible. References: <46B01E14.2020109@alexjacobson.com> <46B0D198.2040506@serpentine.com> Message-ID: <1185993632.5989.79.camel@localhost> On Wed, 2007-08-01 at 11:31 -0700, Bryan O'Sullivan wrote: > Alex Jacobson wrote: > > If you create a Data.Map or Data.Set larger than fits in physical > > memory, will OS level swapping enable your app to behave reasonably or > > will things just die catastrophically as you hit a memory limit? > > Relying on the OS to page portions of your app in and out should always > be the fallback of last resort. You are fairly guaranteed to get > terrible performance because the VM subsystem can't anticipate your > app's memory access patterns, and catastrophic death of either your app > or other system processes is a strong possibility (Google for "OOM > killer" if you want some horror stories). In many cases, you can't even > rely on paging being possible. Furthermore, as I understand it, GC does not interact well with paging since the GC has to traverse the data structures on major GCs it'll force it all to be kept in memory. Duncan From apfelmus at quantentunnel.de Wed Aug 1 14:42:22 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Wed Aug 1 14:34:42 2007 Subject: [Haskell-cafe] Re: Zippers, Random Numbers & Terrain In-Reply-To: <784a62100707292326u2b8fb37bl5fccb9b0c86ecf4c@mail.gmail.com> References: <784a62100707292326u2b8fb37bl5fccb9b0c86ecf4c@mail.gmail.com> Message-ID: Thomas Conway wrote: > This got me thinking that it would be cool to make an infinite terrain > generator using a zipper, so you can zoom in/out infinitely, and by > implication, infinitely in any direction. After some pondering, I think it's indeed possible and the zipper is the right tool for the job. I'll present the idea for constructing a one-dimensional "fractal terrain" but it generalizes to higher dimensions. First, consider the task to construct a 1D fractal height function defined on a bounded interval like [0,1]. type Pos = Double type Height = Double terrain :: Interval -> Pos -> Height We construct the terrain by dividing the interval in half and adjust the height of the midpoint randomly relative to the mean of the other heights. data Interval = I (Pos,Pos) (Height,Height) StdGen terrain :: Interval -> Pos -> Height terrain i x | x `in` left = terrain left x | x `in` right = terrain right x where (left, right) = bisect i in :: Pos -> Interval -> Bool in x (I (a,b) _ _) = a <= x && x <= b bisect :: Interval -> (Interval, Interval) bisect (I (a,b) (ha,hb) g) = (I (a,m) (ha,h) ga, I (m,b) (h,hb) gb) where m = (a+b)/2 h = (ha+hb)/2 + d * (a-b) * scale (d,g') = randomR (0,1) g (ga,gb) = split g' The factor scale controls the roughness of the terrain. True enough, the function terrain never returns but that shouldn't be an issue to the mathematician ;) Of course, we have to stop as soon as the interval length is smaller than some given resolution epsilon (i.e. the width of a pixel). Splitting the random number generator is not necessarily a good idea, but I don't care right now. For zoom-in, we want to specify different epsilons and get the same random values each time. So, we memoize the steps to produce the height function in an infinite tree data Terrain = Branch Terrain (Height,Height) Terrain terrain :: Interval -> Terrain terrain i = Branch (terrain left) h (terrain right) where (left, right) = bisect i I _ h _ = i The actual rendering can be obtained from the infinite Terrain, I'll omit it for simplicity. For finite zoom-out, we use a zipper type Zipper = (Context, Terrain) type Context = [Either Terrain Terrain] zoomInLeft, zoomInRight :: Zipper -> Zipper zoomInLeft (xs, Branch l h r) = (Left r:xs, l) zoomInRight (xs, Branch l h r) = (Right l:xs, r) zoomOut :: Zipper -> Zipper zoomOut (x:xs, t) = case x of Left r -> (xs, Branch t (t `joinHeights` r) r) Right l -> (xs, Branch l (l `joinHeights` t) t) where joinHeights (Branch _ (ha,_) _) (Branch _ (_,hb) _) = (ha,hb) zoomOut ([], _) = error "You fell out of the picture!" Mnemonics: Left means that we descended into the left half, Right that we descended into the right half of the interval. The final step is to allow infinite zoom-out. How to do that? Well, assume that we generate the landscape on the interval [0,1] and zoom out. The reverse of this would be to create the landscape on the interval [-1,1] and then zoom into the right half [0,1]. In other words, we view [0,1] as the right half of the bigger interval [-1,1]. This in turn can be viewed as the left half of the even bigger interval [-1,3]. In order to grow both interval bounds to infinity, we alternate between viewing it as left half and as right half. In other words, the insight is that *we're inside an infinite context*! Thus, generating an infinite terrain is like generating a finite one except that we need to generate the infinite context as well: terrainInfinite :: Interval -> Zipper terrainInfinite i = (right i, terrain i) where right (I (m,b) (h,hb) g) = Right (terrain l) : left i where l = fst $ bisect i i = I (a,b) (ha,hb) g' a = m - (b -m) ha = hb - (hb-h) + d * (a-b) * scale (d,g') = randomR (0,1) g left (I (a,m) (ha,h) g) = Left (terrain r) : right i where r = snd $ bisect i i = I (a,b) (ha,hb) g' b = m + (m-a ) hb = h + (h-ha) + d * (a-b) * scale (d,g') = randomR (0,1) g Here, left starts by extending a given interval to the right and right starts by extending it to the left. It would be nice to run the random generator backwards, the generator transitions in terrainInfinite are surely wrong, i.e. too deterministic. Also, the scale of the random height adjustment d is probably wrong. But those things are exercises for the attentive reader ;) That concludes the infinite terrain generation for one dimension. For higher dimension, one just needs to use 2D objects instead of intervals to split into two or more pieces. For instance, one can divide equilateral triangles into 4 smaller ones. In fact, it doesn't matter whether the starting triangle is equilateral or not when using the midpoints of the three sides to split it into four smaller triangles. Regards, apfelmus From lgreg.meredith at biosimilarity.com Wed Aug 1 15:23:26 2007 From: lgreg.meredith at biosimilarity.com (Greg Meredith) Date: Wed Aug 1 15:15:48 2007 Subject: [Haskell-cafe] Re: monads and groups -- instead of loops In-Reply-To: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> References: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> Message-ID: <5de3f5ca0708011223y322ec175p8b30422d5de76b3d@mail.gmail.com> Haskellians, But, along these lines i have been wondering for a while... the monad laws present an alternative categorification of monoid. At least it's alternative to monoidoid. In the spirit of this thought, does anyone know of an expansion of the monad axioms to include an inverse action? Here, i am following an analogy monoidoid : monad :: groupoid : ??? i did a search of the literature, but was probably using the wrong terminology to try to find references. i would be very grateful for anyone who might point me in the right direction. My intuition tells me this could be quite generally useful to computing in situation where boxing and updating have natural (or yet to be discovered) candidates for undo operations. i'm given to understand reversible computing might be a good thing to be thinking about if QC ever gets real... ;-) Best wishes, --greg On 8/1/07, Greg Meredith wrote: > > Haskellians, > > Though the actual metaphor in the monads-via-loops doesn't seem to fly > with this audience, i like the spirit of the communication and the implicit > challenge: find a pithy slogan that -- for a particular audience, like > imperative programmers -- serves to uncover the essence of the notion. i > can't really address that audience as my first real exposure to programming > was scheme and i moved into concurrency and reflection after that and only > ever used imperative languages as means to an end. That said, i think i > found another metaphor that summarizes the notion for me. In the same way > that the group axioms organize notions of symmetry, including addition, > multiplication, reflections, translations, rotations, ... the monad(ic > axioms) organize(s) notions of snapshot (return) and update (bind), > including state, i/o, control, .... In short > > group : symmetry :: monad : update > > Best wishes, > > --greg > > -- > L.G. Meredith > Managing Partner > Biosimilarity LLC > 505 N 72nd St > Seattle, WA 98103 > > +1 206.650.3740 > > http://biosimilarity.blogspot.com -- L.G. Meredith Managing Partner Biosimilarity LLC 505 N 72nd St Seattle, WA 98103 +1 206.650.3740 http://biosimilarity.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/412c87a9/attachment-0001.htm From haskell at list.mightyreason.com Wed Aug 1 15:23:58 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Wed Aug 1 15:16:38 2007 Subject: [Haskell-cafe] Re: Knuth Morris Pratt for Lazy Bytestrings implementation In-Reply-To: References: <20070801020709.GF21697@cse.unsw.EDU.AU> Message-ID: <46B0DDCE.4040704@list.mightyreason.com> I am still working on improving your code. And I have a "Is this a bug?" question: The "lookup = computeLookup pat" defines lookup to take an Int which represents the index into pat, where this index is 0 based and the 0th item is the head of pat. Now look at "matchLength :: Int; matchLength = let ... in matchLength' (B.drop (fromIntegral patShift) pat) str 0" That starts the "pat" from a shorter version that starts at 'patShift' and sets the last argument to matchLength' to 0. matchLength' is in the ... as: let matchLength' pat str cnt | B.null pat = cnt matchLength' pat str cnt | B.null str = 0 matchLength' pat str cnt | (B.head pat == B.head str) = matchLength' (B.drop 1 pat) (B.drop 1 str) (cnt + 1) | otherwise = cnt I see that cnt is incremented until * all of pat is matched, return cnt * all of str is used, return 0 * a mismatch is found, return cnt So a mismatch means that the character at index (patShift+cnt) in the original 'pat' had the mismatch. Now I see this that uses the 'cnt' returned from matchLength: shiftAmt = {-# SCC "kmpMatch_shiftAmt" #-} lookup matchLength And this is the bug. lookup should be given (shiftAmt + matchLength). This was not clear or obvious since * Nearly everything is Int or Int64 * The name "pat" in matchLength' shadows "pat" in kmpMatch This was not caught by quickcheck since it is an internal value and only rarely will trigger an error where a legitimate match is missed. If there is no match then this bug does not cause an incorrect answer (I think). I will fix this and continue hacking on it. -- Chris From ryani.spam at gmail.com Wed Aug 1 15:31:43 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Wed Aug 1 15:24:02 2007 Subject: [Haskell-cafe] How can I optimize pattern matching on views? Message-ID: <2f9b2d30708011231m5d45e854s77b1de2fe18ac3ba@mail.gmail.com> Background: I participated in this year's ICFP programming contestand our team did quite well, coming in 37th. Our simulator (in somewhat naive C++ with a good algorithm) took about 45 seconds to run the original problem, and afterwards one of my coworkers took the same algorithm and optimized it to run in about 6-10 seconds. The rest of the email will have minor spoilers, so skip it if you want to work on the problem yourself. I'm using that problem as a good testcase for learning to write high-performance Haskell. I'm using the same data structure and basic algorithm as the C++ version, but I'm having problems getting the performance where I think it should be. The relevant parts of the code: > import qualified Data.ByteString.Base as B > import qualified Data.ByteString.Char8 as BC > > type DNABlock = B.ByteString > type DNA = [DNABlock] I represent the DNA string as a simplified ropethat supports fast reading from the front & prepending. To access this in a reasonable fashion, I used a view to let me treat the data as a string. Here's a sample bit of code using that view: > matchConsts :: Int -> DNA -> (Int, DNA) > matchConsts len dna | len `seq` dna `seq` False = undefined -- force strictness > matchConsts len dna = case dnaView dna of > ('F':_) -> matchConsts (len+1) (dropDna 1 dna) > ('C':_) -> matchConsts (len+1) (dropDna 1 dna) > ('P':_) -> matchConsts (len+1) (dropDna 1 dna) > ('I':'C':_) -> matchConsts (len+2) (dropDna 2 dna) > _ -> (len, dna) > dropDna :: Int -> DNA -> DNA > dropDna n dna | n `seq` dna `seq` False = undefined -- force strictness > dropDna _ [] = [] > dropDna 0 dna = d > dropDna n (d:ds) > | n >= BC.length d = dropDna (n - BC.length d) ds > | otherwise = B.unsafeDrop n d : ds > {-# INLINE dropDna #-} Profiling showed that almost all of my time & allocations were spent in my view function: > dnaView :: DNA -> String > -- dnaView d = foldr (++) [] (map BC.unpack d) > -- This was ridiculously slow for some reason that I don't entirely understand > dnaView [] = [] > dnaView (d:ds) > | BC.null d = dnaView ds > | otherwise = (w2c $ B.unsafeHead d) : dnaView (B.unsafeTail d : ds) > {-# INLINE dnaView #-} The question I have for you, the haskell-cafe-reading-audience, is how can I get GHC to do smart code-gen for this? I want "case dnaView dna of ..." to not allocate and instead fuse the list generation with the pattern-match. -- ryan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/67753f53/attachment.htm From alex at alexjacobson.com Wed Aug 1 15:32:54 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Wed Aug 1 15:25:39 2007 Subject: [Haskell-cafe] OS swapping and haskell data structures In-Reply-To: <1185993632.5989.79.camel@localhost> References: <46B01E14.2020109@alexjacobson.com> <46B0D198.2040506@serpentine.com> <1185993632.5989.79.camel@localhost> Message-ID: <46B0DFE6.5080008@alexjacobson.com> Ok, so for low throughput applications, you actually need a disk strategy. Got it. Ok, is there a standard interface to BerkleyDB or some other disk based store? -Alex- Duncan Coutts wrote: > On Wed, 2007-08-01 at 11:31 -0700, Bryan O'Sullivan wrote: >> Alex Jacobson wrote: >>> If you create a Data.Map or Data.Set larger than fits in physical >>> memory, will OS level swapping enable your app to behave reasonably or >>> will things just die catastrophically as you hit a memory limit? >> Relying on the OS to page portions of your app in and out should always >> be the fallback of last resort. You are fairly guaranteed to get >> terrible performance because the VM subsystem can't anticipate your >> app's memory access patterns, and catastrophic death of either your app >> or other system processes is a strong possibility (Google for "OOM >> killer" if you want some horror stories). In many cases, you can't even >> rely on paging being possible. > > Furthermore, as I understand it, GC does not interact well with paging > since the GC has to traverse the data structures on major GCs it'll > force it all to be kept in memory. > > Duncan From sethg at ropine.com Wed Aug 1 15:37:37 2007 From: sethg at ropine.com (Seth Gordon) Date: Wed Aug 1 15:30:09 2007 Subject: [Haskell-cafe] OS swapping and haskell data structures In-Reply-To: <46B0DFE6.5080008@alexjacobson.com> References: <46B01E14.2020109@alexjacobson.com> <46B0D198.2040506@serpentine.com> <1185993632.5989.79.camel@localhost> <46B0DFE6.5080008@alexjacobson.com> Message-ID: <46B0E101.4010008@ropine.com> Alex Jacobson wrote: > Ok, so for low throughput applications, you actually need a disk > strategy. Got it. > > Ok, is there a standard interface to BerkleyDB or some other disk based > store? I would absolutely kvell if there were some way to use a disk-based store to back Haskell objects without going through the IO monad. From westondan at imageworks.com Wed Aug 1 16:01:36 2007 From: westondan at imageworks.com (Dan Weston) Date: Wed Aug 1 15:53:58 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <00d401c7d447$fe1c1bd0$fa545370$@be> References: <00d401c7d447$fe1c1bd0$fa545370$@be> Message-ID: <46B0E6A0.3010707@imageworks.com> Here's my rant about the way monads are explained in Haskell tutorials (which are much too polluted with nuclear waste to be safely approached): It is a big mistake to start with the IO monad. It pollutes and misdirects the understanding of what a monad is. The dreaded "nuclear waste" metaphor is actually a red herring, having nothing do do with a monad at all, merely the artifact of the absence of an exit function in the IO monad (which actually does exist and is called unsafePerformIO, but that is a secret. Shhh...), combined with Haskell's refusal to work for free. Monads are required to have an extrance (reification/constructor function) called return. They are *not* required to have an exit (reflection/deconstructor function). They *do* combine (bind) together like links in a chain, which is not a list but an equivalence class of trees, where the only thing that matters is the order of the leaves, so unlike a list you don't have to start at the tail and assemble one-by-one. [Actually, the compiler picks just one of these trees (the singly-linked list) but expects that all trees would evaluate the same.] They *do* bind only with flavors of themselves (State a cannot bind to IO b, though a monad transformer can merge the two). The output type of one monad instance must match the input type of another monad reification function (e.g. return) that it wants to bind to. In compensation for this tribalism, those snobby monads that want to clique off are out of luck: a monad cannot restrict what possible types can be used to construct a monad instance. That would be discrimination, and you must agree to accept all comers. Simple, no? Apparently not... Other things have nothing to do with monads per se gunk up the descriptions about monads: One red herring (the nuclear waste metaphor) refers to the fact since monads may or may not have an escape-clause (called variously runXXX, evalXXX, unsafePerformXXX), and IO in particular does not. The presence or absence of this has *nothing* to do with monads (only with IO), participates in no monadic laws, and shouldn't even be in the chapter on Monads. Whether nuclear waste seeps in (as in a State monad) or stays out (IO monad) has nothing to do with their monadic property and is a special property of those particular classes. Another even redder herring is the dreaded sequencing aspect. Monads do sequence *denotationally*, the way any nested closures sequence, which is exactly *backwards* from the naive understanding of sequencing: symbols defined to the left are in the *inner* scope, those to the right are in the *outer* scope. Perversely, when the symbols are evaluated, the rightmost monad is evaluated first. The leftmost monad in the program, the IO () passed in by main, is the *last* thing to be evaluated, not the first. The outermost monad (rightmost bound function) is in the driver seat, and is absolutely free to ignore the monad to its left (which in turn encloses monads to its left)! This includes of course the main input IO () monad. Don't believe me? Prelude> const 3 (return "Nuclear waste leaking..." >>= print) + 5 8 Phew, no nuclear waste leaked after all. What a relief! This sequencing then has nothing to do with *operational* sequencing. When the symbols are evaluated is the basic call-by-need data-dependent stuff of most Haskell symbols and again, has nothing to do with monads. I learned about the IO monad first and I regret it bitterly. It cost me a years' worth of misunderstanding. I misapprehended that a monad had something to do with nuclear waste and never escaping the single-threadedness. I hope the new O'Reilly book doesn't make that mistake. Teach IO right away, but just don't call it a monad. IO is the exception, not the rule, in the menagerie of Haskell monads. How does all this map to C++? A monad is a a class, with no useful interface for the end user, that looks roughly (i.e. I haven't tested it) like: template class Monad { public: virtual ~Monad() {} // return Monad(T t) : t_(t) {} // bind operator (>>=), where // F :: Monad -> (T -> Monad) -> Monad virtual template Monad operator>>(typename U::F f) = 0; private: T t_; }; C++ programmers will immediately see past the syntactic kruft to notice that 1) the constructor arg is not a value but an unevaluated function object, that starts out unevaluated. 2) The result of m >> f is a monad object, totally unevaluated. 3) There is no member function to do anything with the monad at all! As is, it is useless. Derivers of this class will naturally want to add such functionality: template class MyMonad : public Monad { // The parent class needs to know what type of monad // this can bind to typedef someUnaryFunctionObjectTypeReturningB F; // There is no input, just an output! // The input is via the constructor arg of the innermost monad B operator()() { ... start the ball rolling ... } }; Non-C++ programmers will be stunned that the above garbage can be understood by anyone, compared to the simplicity of type classes in Haskell. When all you have is a hammer... The moral of the story is that monads are less than meets the eye. You can create them and concatenate them, but may not be able to do anything with them (some monads do let you, some don't), though the runtime system agrees to evaluate one special monad exactly once. What the rightmost monad does with its internals (including all inner/left monads bound to it) has nothing to do with monads whatever, except for the minimal requirement that they agree to be bound only to other monads like themselves, and that as a group they all agree to not form a clique (i.e. they are associative). What could be simpler that that? No please, no more nuclear waste! :) Dan peterv wrote: > Kaveh> "A monad is like a loop that can run a new function against its variable in each iteration." > > I?m an imperative programmer learning Haskell, so I?m a newbie, but I?ll give it a try ? Making mistakes is the best way to learn it ;) > > There are lots of different kinds of monads, but let?s stick to the IO monad first, which you seem to refer to. > > No *an IO monad is not a loop at all*. Instead, from an imperative programmer?s point of view, the following might be better: > > ?an IO monad is a delayed action that will be executed as soon as that action is needed for further evaluation of the program.? > > The simple program > > main = getLine >>= putStrLn > > can be visually represented as (see attachment) > > The ?world? (=a representation of your computer?s hardware) is passed to the main function, which passes it to all actions that it encounters during its lazy evaluation, causing the executing of the actions as an effect. > > The red wire through which the ?world flows? is a ?single thread?, it cannot be split (because the physical world cannot be copied!!!), so no unwanted side effects can ever occur, making IO safe in Haskell. > > When you write your IO program, this world object is never available (the IO type is a special internal type), so the red wire is erased from the diagram, and the getLine and putStrLn boxes become ?delayed actions?. > > Imperative programmers like myself might initially be confused when they see Haskell?s do notation, because it looks like the actions are strict statements as in C/C++/Pascal/Java/C#/etc, but they are not. > > For example, try the following program: > > main = do last [ > putStrLn "NOT executed although it is first in the list, as it is not used by the main function!", > putStrLn "This action IS executed because it is evaluated by the main function." ] > > This is of course all due to Haskell?s laziness which only evaluates just those expressions that it needs to evaluate the main function. > > One thing to note in the diagram above is that the getLine box has TWO outputs, the String and the World. But functions can only have a single output, but this can be tuple. Hence the passing of the world from one box to the other is a bit more complicated. It is this pattern of extracting both values from the output and passing them to the next function and other related combinations that form the generic monad class, which can be used for many more things than IO. > > See http://haskell.org/haskellwiki/IO_inside for a much deeper and more correct explanation ? > > And for the pros here, did this newbie make any sense? Probably not ;-) > > Oh no, yet another monad explanation!!! Now the universe will most certainly collapse? > > > No virus found in this outgoing message. > Checked by AVG Free Edition. > Version: 7.5.476 / Virus Database: 269.11.0/929 - Release Date: 31/07/2007 17:26 > > > > > ------------------------------------------------------------------------ > > > ------------------------------------------------------------------------ > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From duncan.coutts at worc.ox.ac.uk Wed Aug 1 16:09:13 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 1 16:00:29 2007 Subject: [Haskell-cafe] OS swapping and haskell data structures In-Reply-To: <46B0DFE6.5080008@alexjacobson.com> References: <46B01E14.2020109@alexjacobson.com> <46B0D198.2040506@serpentine.com> <1185993632.5989.79.camel@localhost> <46B0DFE6.5080008@alexjacobson.com> Message-ID: <1185998953.5989.83.camel@localhost> On Wed, 2007-08-01 at 12:32 -0700, Alex Jacobson wrote: > Ok, so for low throughput applications, you actually need a disk > strategy. Got it. > > Ok, is there a standard interface to BerkleyDB or some other disk based > store? Well on hackage there's anydbm and BerkeleyDB. The former is probably the older and more mature of the two. Duncan From fb at frank-buss.de Wed Aug 1 16:27:31 2007 From: fb at frank-buss.de (Frank Buss) Date: Wed Aug 1 16:19:54 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <46B0E6A0.3010707@imageworks.com> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> Message-ID: <063901c7d47a$633f2610$64c5a8c0@galilei> > How does all this map to C++? A monad is a a class, with no useful > interface for the end user, that looks roughly (i.e. I haven't tested > it) like: trying to implement it in other languages is a good idea for understanding monads. I've tried this with the Maybe monad in Lisp: http://groups.google.com/group/comp.lang.lisp/msg/3bd8ecfb6cfd6601 There are other tries in Scheme and Lisp, even a general Arrows approach IIRC. -- Frank Buss, fb@frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From westondan at imageworks.com Wed Aug 1 16:32:53 2007 From: westondan at imageworks.com (Dan Weston) Date: Wed Aug 1 16:25:14 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <46B0E6A0.3010707@imageworks.com> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> Message-ID: <46B0EDF5.4020304@imageworks.com> > The outermost monad (rightmost bound function) is in the driver seat, and is absolutely free to ignore the monad to its > left (which in turn encloses monads to its left)! This includes of > course the main input IO () monad. Don't believe me? > > Prelude> const 3 (return "Nuclear waste leaking..." >>= print) + 5 > 8 > > Phew, no nuclear waste leaked after all. What a relief! No, I don't believe you. It's true that the right monad instance can ignore its left sibling (same monad of course, just a different instance) to allow backtracking (the Const monad being a trivial example of this), but IO is not such a monad. Your example just shows that monad instance expressions (like any Haskell expression) are evaluated lazily in Haskell. I am relieved though, that no nuclear waste was leaked by your example. Dan Weston wrote: > Here's my rant about the way monads are explained in Haskell tutorials > (which are much too polluted with nuclear waste to be safely approached): > > It is a big mistake to start with the IO monad. It pollutes and > misdirects the understanding of what a monad is. The dreaded "nuclear > waste" metaphor is actually a red herring, having nothing do do with a > monad at all, merely the artifact of the absence of an exit function in > the IO monad (which actually does exist and is called unsafePerformIO, > but that is a secret. Shhh...), combined with Haskell's refusal to work > for free. > > Monads are required to have an extrance (reification/constructor > function) called return. They are *not* required to have an exit > (reflection/deconstructor function). > > They *do* combine (bind) together like links in a chain, which is not a > list but an equivalence class of trees, where the only thing that > matters is the order of the leaves, so unlike a list you don't have to > start at the tail and assemble one-by-one. [Actually, the compiler picks > just one of these trees (the singly-linked list) but expects that all > trees would evaluate the same.] > > They *do* bind only with flavors of themselves (State a cannot bind to > IO b, though a monad transformer can merge the two). The output type of > one monad instance must match the input type of another monad > reification function (e.g. return) that it wants to bind to. > > In compensation for this tribalism, those snobby monads that want to > clique off are out of luck: a monad cannot restrict what possible types > can be used to construct a monad instance. That would be discrimination, > and you must agree to accept all comers. > > Simple, no? Apparently not... > > Other things have nothing to do with monads per se gunk up the > descriptions about monads: > > One red herring (the nuclear waste metaphor) refers to the fact since > monads may or may not have an escape-clause (called variously runXXX, > evalXXX, unsafePerformXXX), and IO in particular does not. The presence > or absence of this has *nothing* to do with monads (only with IO), > participates in no monadic laws, and shouldn't even be in the chapter on > Monads. Whether nuclear waste seeps in (as in a State monad) or stays > out (IO monad) has nothing to do with their monadic property and is a > special property of those particular classes. > > Another even redder herring is the dreaded sequencing aspect. Monads do > sequence *denotationally*, the way any nested closures sequence, which > is exactly *backwards* from the naive understanding of sequencing: > symbols defined to the left are in the *inner* scope, those to the right > are in the *outer* scope. Perversely, when the symbols are evaluated, > the rightmost monad is evaluated first. The leftmost monad in the > program, the IO () passed in by main, is the *last* thing to be > evaluated, not the first. The outermost monad (rightmost bound function) > is in the driver seat, and is absolutely free to ignore the monad to its > left (which in turn encloses monads to its left)! This includes of > course the main input IO () monad. Don't believe me? > > Prelude> const 3 (return "Nuclear waste leaking..." >>= print) + 5 > 8 > > Phew, no nuclear waste leaked after all. What a relief! > > This sequencing then has nothing to do with *operational* sequencing. > When the symbols are evaluated is the basic call-by-need data-dependent > stuff of most Haskell symbols and again, has nothing to do with monads. > > I learned about the IO monad first and I regret it bitterly. It cost me > a years' worth of misunderstanding. I misapprehended that a monad had > something to do with nuclear waste and never escaping the > single-threadedness. I hope the new O'Reilly book doesn't make that > mistake. Teach IO right away, but just don't call it a monad. IO is the > exception, not the rule, in the menagerie of Haskell monads. > > How does all this map to C++? A monad is a a class, with no useful > interface for the end user, that looks roughly (i.e. I haven't tested > it) like: > > template > class Monad > { > public: > > virtual ~Monad() {} > > // return > Monad(T t) : t_(t) {} > > // bind operator (>>=), where > // F :: Monad -> (T -> Monad) -> Monad > virtual template Monad > operator>>(typename U::F f) = 0; > > private: > T t_; > }; > > C++ programmers will immediately see past the syntactic kruft to notice > that > 1) the constructor arg is not a value but an unevaluated function > object, that starts out unevaluated. > 2) The result of m >> f is a monad object, totally unevaluated. > 3) There is no member function to do anything with the monad at all! As > is, it is useless. > > Derivers of this class will naturally want to add such functionality: > > template > class MyMonad : public Monad > { > // The parent class needs to know what type of monad > // this can bind to > typedef someUnaryFunctionObjectTypeReturningB F; > > // There is no input, just an output! > // The input is via the constructor arg of the innermost monad > B operator()() { ... start the ball rolling ... } > }; > > Non-C++ programmers will be stunned that the above garbage can be > understood by anyone, compared to the simplicity of type classes in > Haskell. When all you have is a hammer... > > The moral of the story is that monads are less than meets the eye. You > can create them and concatenate them, but may not be able to do anything > with them (some monads do let you, some don't), though the runtime > system agrees to evaluate one special monad exactly once. > > What the rightmost monad does with its internals (including all > inner/left monads bound to it) has nothing to do with monads whatever, > except for the minimal requirement that they agree to be bound only to > other monads like themselves, and that as a group they all agree to not > form a clique (i.e. they are associative). > > What could be simpler that that? No please, no more nuclear waste! :) > > Dan > > peterv wrote: >> Kaveh> "A monad is like a loop that can run a new function against its >> variable in each iteration." >> I?m an imperative programmer learning Haskell, so I?m a newbie, but >> I?ll give it a try ? Making mistakes is the best way to learn it ;) >> >> There are lots of different kinds of monads, but let?s stick to the IO >> monad first, which you seem to refer to. >> >> No *an IO monad is not a loop at all*. Instead, from an imperative >> programmer?s point of view, the following might be better: >> >> ?an IO monad is a delayed action that will be executed as soon as that >> action is needed for further evaluation of the program.? >> >> The simple program >> >> main = getLine >>= putStrLn >> can be visually represented as (see attachment) >> >> The ?world? (=a representation of your computer?s hardware) is passed >> to the main function, which passes it to all actions that it >> encounters during its lazy evaluation, causing the executing of the >> actions as an effect. >> The red wire through which the ?world flows? is a ?single thread?, it >> cannot be split (because the physical world cannot be copied!!!), so >> no unwanted side effects can ever occur, making IO safe in Haskell. >> When you write your IO program, this world object is never available >> (the IO type is a special internal type), so the red wire is erased >> from the diagram, and the getLine and putStrLn boxes become ?delayed >> actions?. >> Imperative programmers like myself might initially be confused when >> they see Haskell?s do notation, because it looks like the actions are >> strict statements as in C/C++/Pascal/Java/C#/etc, but they are not. >> >> For example, try the following program: >> >> main = do last [ >> putStrLn "NOT executed although it is first in the list, as >> it is not used by the main function!", >> putStrLn "This action IS executed because it is evaluated >> by the main function." ] >> >> This is of course all due to Haskell?s laziness which only evaluates >> just those expressions that it needs to evaluate the main function. >> >> One thing to note in the diagram above is that the getLine box has TWO >> outputs, the String and the World. But functions can only have a >> single output, but this can be tuple. Hence the passing of the world >> from one box to the other is a bit more complicated. It is this >> pattern of extracting both values from the output and passing them to >> the next function and other related combinations that form the generic >> monad class, which can be used for many more things than IO. >> >> See http://haskell.org/haskellwiki/IO_inside for a much deeper and >> more correct explanation ? >> >> And for the pros here, did this newbie make any sense? Probably not ;-) >> Oh no, yet another monad explanation!!! Now the universe will most >> certainly collapse? >> >> No virus found in this outgoing message. >> Checked by AVG Free Edition. Version: 7.5.476 / Virus Database: >> 269.11.0/929 - Release Date: 31/07/2007 17:26 >> >> >> >> ------------------------------------------------------------------------ >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Haskell-Cafe mailing list >> Haskell-Cafe@haskell.org >> http://www.haskell.org/mailman/listinfo/haskell-cafe > > From westondan at imageworks.com Wed Aug 1 16:42:52 2007 From: westondan at imageworks.com (Dan Weston) Date: Wed Aug 1 16:35:16 2007 Subject: [Haskell-cafe] Cartesian product of a Set In-Reply-To: <20070801142801.GA7647@cspcag2.swan.ac.uk> References: <20070801142801.GA7647@cspcag2.swan.ac.uk> Message-ID: <46B0F04C.1090604@imageworks.com> Andy Gimblett wrote: > Hi all, > > Is this a reasonable way to compute the cartesian product of a Set? > >> cartesian :: Ord a => S.Set a -> S.Set (a,a) >> cartesian x = S.fromList [(i,j) | i <- xs, j <- xs] >> where xs = S.toList x > > It's a fairly "obvious" way to do it, but I wondered if there were any > hidden gotchas. I'm particularly concerned by toList (O(n)) fromList > (O(n log n)) - but for other reasons I'd really like to be using Set > rather than List for this (I think). > > Many thanks for any thoughts, > > -Andy > Your list comprehension always generates a sorted list, so changing S.fromList to its "unsafe" version (but guarateed by you) S.fromDistinctAscList should get you back to O(n). Of course the order of the generators was key (i before j). Dan From feeder.of.the.bears at gmail.com Wed Aug 1 16:48:07 2007 From: feeder.of.the.bears at gmail.com (David Pollak) Date: Wed Aug 1 16:40:27 2007 Subject: [Haskell-cafe] Some Haskell platformish questions Message-ID: Howdy, I'm considering building a desktop app using Haskell. The primary target for the app is Windows, but if it runs on Linux and Mac (Intel and PPC), that'd be a bonus. I've got a bunch of questions that hopefully folks can answer. Well, before I start, you might well be asking "Gee David, you're a Scala kind of guy... I mean, you're the primary contributor to lift... why not use Scala?" Well, I'm looking to build something that compiles down to native code and has a smaller download (and runtime) footprint than the JVM offers. I've come to love functional programming and am taking the current side project as an opportunity to learn Haskell. So... on to the questions: - Can GHC generate stand-alone executables with all the dependencies linked in such that I can distribute the single file without worrying about including a bunch of DLLs/SOs? The answer seems to be yes, but I wanted to confirm. - How much of a distribution footprint is the Haskell runtime? If I have a "Hello World" app, roughly how big will the EXE be (if one includes the JRE in the runtime, a Java/Scala program has a minimum footprint of 20M... that's big.) - Same goes for the runtime... I've looked at the stats on the Language Shootout home page and these look encouraging, but I wanted to see if the reasonable footprint is a reality. - How real/solid/stable is the wxHaskell widgets package? Is it being well maintained? Is there (okay... this is pie in the sky) an GUI Builder for it? - How are the Windows/COM bindings in Haskell... would it be possible to, for example, embed an IE Browser COM control in a a wxHaskell window? - I found a package to do HTTP requests in Haskell but it does not seem to support HTTPS. Is there an HTTPS client package for Haskell? - How are Strings internally represented? Are they single byte or multi-byte characters? How easy it is to translate to/from internal representation to UTF-8? - How's the XML support? Will the XML parser handle non-Latin characters and properly encode stuff? Does XML get parsed down into easily mappable/filterable collections? - Is there support for SHA256 (I saw an SSLeay package which had support for a lot of stuff, but not SHA256)? - I understand that Haskell has "a better approach" to parallelizing tasks, but I have not seen much about the actual manifestation of this... would someone be so kind as to give me a pointer? - On a related note, I have become a fan (via Scala) of Erlang-style Actors and asynchronous message passing. Are there any similar packages for Haskell? - I tend to do most of my coding in either Emacs or Eclipse... how's the Haskell support in either? Is there a preferred editor (I don't mean to start any wars here... :-) - Are there any production Haskell-based desktop apps of note? Anyway... sorry for the long list of questions. I look forward to hearing from you all and learning more about Haskell. Thanks, David -- lift, the fast, powerful, easy web framework http://liftweb.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/29d447b3/attachment-0001.htm From dm.maillists at gmail.com Wed Aug 1 16:51:26 2007 From: dm.maillists at gmail.com (Daniel McAllansmith) Date: Wed Aug 1 16:43:47 2007 Subject: [Haskell-cafe] Backpatching In-Reply-To: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> References: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> Message-ID: <200708020851.26324.dm.maillists@gmail.com> On Wednesday 01 August 2007 17:44, Thomas Conway wrote: > This sounds like a common problem type. Is there a well known solution > to this sort of problem? Have you looked into Tying the Knot? http://www.haskell.org/haskellwiki/Tying_the_Knot A simple example: module Knot where import Data.Char import Data.Maybe type Input = String type Output = [(Char, Int)] type Resolver = (Char -> Int) resolvingError c = error ("Couldn't resolve: " ++ [c]) parseInput :: Resolver -> Input -> Output parseInput _ [] = [] parseInput resolve (c:cs) | isUpper c = ((c, fromEnum c) : parseInput f cs) | otherwise = ((c, resolve c) : parseInput f cs) makeResolver :: Output -> Resolver makeResolver o c = fromMaybe (resolvingError c) (lookup (toUpper c) o) foo :: Input -> Output foo i = let o = parseInput (makeResolver o) i in o testGood = foo "CaBcbA" testBad = foo "CaBcb" From haskell at list.mightyreason.com Wed Aug 1 16:54:56 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Wed Aug 1 16:47:41 2007 Subject: [Haskell-cafe] Re: Knuth Morris Pratt for Lazy Bytestrings implementation In-Reply-To: <46B0CB29.5080101@list.mightyreason.com> References: <20070801020709.GF21697@cse.unsw.EDU.AU> <46B0CB29.5080101@list.mightyreason.com> Message-ID: <46B0F320.7090600@list.mightyreason.com> My optimized (and fixed) version of the code is attached. I benchmarked it with: > module Main(main) where > import KMPSeq > import qualified Data.ByteString.Lazy as B > import qualified Data.ByteString.Lazy.Char8 as BC > infile = "endo.dna" Modified by one character from the original copied from the endo.dna The leading "IIIII" is often overlapping with the suffix of a prefix of substring so KMP should help here > substring1 = BC.pack "IIIIIPIIIPIIIIIPIIIPFFICCPIIIPFFFFFPIIIPFFFFFPIIIPIIFIIPIIIPIIIIIPIIIPIIIIIPIIIPIIIIIPIIIPCCCCCPI" original "IIIIIPIIIPIIIIIPIIIPFFICCPIIIPFFFFFPIIIPFFFFFPIIIPIIIIIPIIIPIIIIIPIIIPIIIIIPIIIPIIIIIPIIIPCCCCCPI" > getSearch = do > B.readFile infile > main :: IO () > main = do > print . kmpMatch substring1 =<< getSearch The bug fix is actually a big speed win for this benchmark. The long commentary I wrote has been sent to Justin Bailey with each step I took and each measurement I made. (800 lines with all the pasted profiles). The speedup was from 18.5 seconds to 2.6 seconds on the above benchmark. Cheers, Chris Kuklewicz >From Martin Amis' short story "The Janitor on Mars": "...The War with the Scythers of the Orion Spur was hotly prosecuted for just over a billion years. Who won? We did. They're still there, the Scythers. Their planet is still there. The nature of war changed, during that trillennium. It was no longer nuclear or quantum-gravitational. It was neurological. Informational. Life goes on for the Scythers, but its quality has been subtly reduced. We fixed it so that they think they're simulations in a deterministic computer universe. It is believed that this is the maximum suffering you can visit on a type-v world." http://www.metafilter.com/mefi/18176 -------------- next part -------------- -- Code by Justin Bailey with optimizations by Chris Kuklewicz {-# OPTIONS_GHC -fbang-patterns #-} module KMPSeq (kmpMatch) where import qualified Data.Array.Base as Base (unsafeAt) import qualified Data.Array.Unboxed as Unboxed (UArray) import qualified Data.Array.IArray as IArray ((!), Array, array) import Data.List as List (map, filter, length, null, take, maximum, foldr, all, drop) import qualified Data.ByteString.Lazy as B import qualified Data.ByteString as S import qualified Data.ByteString.Base as B (unsafeHead,unsafeTail,unsafeDrop,unsafeIndex) import GHC.Int (Int64) import Test.QuickCheck import Data.ByteString as S (isSubstringOf, pack, ByteString) -- Only used during testing import Debug.Trace (trace) import System.IO.Unsafe import System.IO {- Returns the first index for which the pattern given is found in the string given, or -1 if the pattern does not appear. -} kmpMatch :: B.ByteString -- ^ The pattern -> B.ByteString -- ^ The string to search -> Int64 -- ^ Result kmpMatch patLazy search | B.null patLazy = 0 -- Empty pattern matches right away. | otherwise = let pat :: S.ByteString pat = S.concat (B.toChunks patLazy) lookupTable = computeLookupS pat patLen = fromIntegral $ S.length pat -- currPatIdx is our position in the pattern - sometimes we don't -- have to match the whole pattern again. -- -- currIdx is our position in the string. We B.drop elements from str -- on each iteration so have to track our position separately. kmpMatch' :: B.ByteString -> Int64 -> Int -> Int64 kmpMatch' !str !currIdx !patShift | B.null str = -1 | otherwise = -- Find length of prefix in our pattern which matches string (possibly zero) let matchLength :: Int matchLength = let matchLength' :: B.ByteString -> Int -> Int matchLength' !str !cnt | cnt == patLen = patLen | B.null str = 0 | B.unsafeIndex pat cnt == B.head str = matchLength' (B.tail str) (succ cnt) | otherwise = cnt in matchLength' str patShift shiftAmt = Base.unsafeAt lookupTable matchLength {-# INLINE matchLen64 #-} matchLen64 = fromIntegral (matchLength-patShift) in case matchLength of _ | matchLength == patLen -> currIdx - fromIntegral patShift -- found complete match | matchLength == patShift -> kmpMatch' (B.tail str) (currIdx + 1) 0 | shiftAmt > 0 -> kmpMatch' (B.drop matchLen64 str) (currIdx + matchLen64) shiftAmt | otherwise -> kmpMatch' (B.drop matchLen64 str) (currIdx + matchLen64) patShift in kmpMatch' search 0 0 -- These tests have failed in the past -- kmpMatch (toLazyBS "ccb") (toLazyBS "abcdcccb") == 5 -- kmpMatch (toLazyBS "bbaa") (toLazyBS "bdcdbbbbaa") == 6 -- kmpMatch (toLazyBS "cccadadc") (toLazyBS "adaccccadadc") == 4 -- This next one has caused an infinite loop previously. -- kmpMatch (toLazyBS "bbbb") (toLazyBS "dddcaaaddaaabdacbcccabbada") {-| Given our pattern, get all the prefixes of the pattern. For each of those prefixes, find the longest prefix from the original pattern that is also a suffix of the prefix segment being considered, and is not equal to it. The argument given to overlap is the length of the prefix matched so far, and the length of the longest prefix, which is a suffix and is not equal to it, is the value overlap returns. If a given prefix has no possible overlap, it is mapped to -1. -} overlap :: S.ByteString -> [(Int, Int)] overlap pat = let patternLength = S.length pat -- Necessary to reverse prefixes since 'isSuffixOf' not implemented for lazy bytestrings. prefixes = List.map S.reverse $ List.take (fromIntegral patternLength) $ S.inits pat longestPreSuffix prefix = -- Find prefixes that are a prefix of this suffix, but -- are not equal to it. let suffixes = List.filter (\p -> p `S.isPrefixOf` prefix && p /= prefix) prefixes in if S.null prefix || List.null suffixes then 0 else List.maximum (List.map S.length suffixes) in List.map (\prefix -> (fromIntegral $ S.length prefix, fromIntegral $longestPreSuffix prefix)) prefixes {- | Given a string representing a search pattern, this function returns a function which represents, for each prefix of that pattern, the maximally long prefix of the pattern which is a suffix of the indicated pattern segment. If there is no such prefix, 0 is returned. -} computeLookupS :: S.ByteString -> Unboxed.UArray Int Int computeLookupS pat = let patLen = fromIntegral $ S.length pat table :: Unboxed.UArray Int Int table = {-# SCC "computeLookup_table" #-} IArray.array (0, patLen - 1) (overlap pat) in table computeLookup :: B.ByteString -> (Int -> Int) computeLookup pat = let patLen = fromIntegral $ B.length pat table :: Unboxed.UArray Int Int table = {-# SCC "computeLookup_table" #-} IArray.array (0, patLen - 1) (overlap . S.concat . B.toChunks $ pat) in Base.unsafeAt table -- Types, instances and utility functions for testing purposes. newtype PatternChar = PatternChar Char deriving Show instance Arbitrary PatternChar where arbitrary = oneof (List.map (return . PatternChar) ['a', 'b', 'c', 'd']) patternsToString :: [PatternChar] -> B.ByteString patternsToString chars = B.pack $ List.foldr (\(PatternChar char) str -> (toEnum $ fromEnum char) : str) [] chars patternsToStrictString :: [PatternChar] -> S.ByteString patternsToStrictString chars = S.pack $ List.foldr (\(PatternChar char) str -> (toEnum $ fromEnum char) : str) [] chars toLazyBS :: String -> B.ByteString toLazyBS = B.pack . List.map (toEnum . fromEnum) toStrictBS :: String -> S.ByteString toStrictBS = S.pack . List.map (toEnum . fromEnum) -- Test that 0 and 1 element always return 0, if present. prop_testZero :: [PatternChar] -> Property prop_testZero pat = let lookup = computeLookup (patternsToString pat) in not (List.null pat) ==> if List.length pat > 1 then lookup 0 == 0 && lookup 1 == 0 else lookup 0 == 0 -- Test that all overlaps found are actually prefixes of the -- pattern string prop_testSubset :: [PatternChar] -> Property prop_testSubset pat = let patStr = patternsToString pat lookup = computeLookup patStr prefix len = B.take (fromIntegral len) testPrefix len = if lookup len == 0 then True else (prefix (lookup len) patStr) `B.isPrefixOf` (prefix len patStr) in not (List.null pat) ==> trivial (B.null patStr) $ List.all testPrefix [0 .. List.length pat - 1] -- Test that the prefix given is the maximal prefix. That is, -- add one more character makes it either equal to the string -- or not a prefix. prop_testCorrectPrefix :: [PatternChar] -> Property prop_testCorrectPrefix pat = let patStr = patternsToString pat lookup = computeLookup patStr isNeverSuffix len = let origPrefix = prefix len patStr -- Drop 1 to remove empty list allPrefixes = List.drop 1 $ B.inits origPrefix in List.all (\p -> B.null p || p == origPrefix || not ((B.reverse p) `B.isPrefixOf` (B.reverse origPrefix))) allPrefixes prefix len = B.take (fromIntegral len) -- True if the prefix returned from lookup for the length given produces -- a string which is a suffix of the original prefix. isRealSuffix len = (B.reverse (prefix (lookup len) patStr)) `B.isPrefixOf` (B.reverse $ prefix len patStr) isLongestSuffix len = let prefixPlus = prefix ((lookup len) + 1) patStr inputPrefix = prefix len patStr in prefixPlus == inputPrefix || not ((B.reverse prefixPlus) `B.isPrefixOf` (B.reverse inputPrefix)) testTable len = if lookup len == 0 then isNeverSuffix len else isRealSuffix len && isLongestSuffix len in not (List.null pat) ==> List.all testTable [0 .. List.length pat - 1] -- Verify that, if a match is found, it is where it's supposed to be in -- the string and it can be independently found by other means. prop_testMatch :: [PatternChar] -> [PatternChar] -> Property prop_testMatch pat search = let patStr = patternsToString pat searchStr = patternsToString search strictStr = patternsToStrictString search strictPat = patternsToStrictString pat patLen = B.length patStr searchLen = B.length searchStr matchIdx = kmpMatch patStr searchStr verify = if matchIdx > -1 then (B.take patLen $ B.drop matchIdx $ searchStr) == patStr && strictPat `S.isSubstringOf` strictStr else (B.null patStr && B.null searchStr) || not (strictPat `S.isSubstringOf` strictStr) in not (List.null pat) ==> trivial (B.null searchStr) $ classify (patLen > searchLen) "Bigger pattern than search" $ classify (patLen < searchLen) "Smaller pattern than search" $ classify (patLen == searchLen) "Equal pattern and search" $ classify (matchIdx > -1) "Match Exists" $ classify (matchIdx == -1) "Match Doesn't Exist" $ verify -- Test a pattern that was known to fail. prop_testBadPat :: [PatternChar] -> Property prop_testBadPat search = let patStr = toLazyBS "bbc" patLen = B.length patStr searchStr = patternsToString search matchIdx = kmpMatch patStr searchStr strictStr = patternsToStrictString search strictPat = toStrictBS "bbc" verify = if matchIdx > -1 then (B.take patLen $ B.drop matchIdx $ searchStr) == patStr && strictPat `S.isSubstringOf` strictStr else (B.null patStr && B.null searchStr) || not (strictPat `S.isSubstringOf` strictStr) in trivial (List.null search) $ verify -- Test that a pattern on the end of the string is found OK. prop_testEndPattern :: [PatternChar] -> [PatternChar] -> Property prop_testEndPattern pat search = let patStr = patternsToString pat searchStr = patternsToString (search ++ pat) matchIdx = kmpMatch patStr searchStr strictStr = patternsToStrictString (search ++ pat) strictPat = patternsToStrictString pat patLen = B.length patStr verify = if matchIdx > -1 then (B.take patLen $ B.drop matchIdx $ searchStr) == patStr && strictPat `S.isSubstringOf` strictStr else (B.null patStr && B.null searchStr) || not (strictPat `S.isSubstringOf` strictStr) in not (List.null pat) ==> trivial (B.null searchStr) $ classify (matchIdx > -1) "Match Exists" $ classify (matchIdx == -1) "Match Doesn't Exists" $ verify props1 = [ prop_testZero , prop_testSubset , prop_testCorrectPrefix , prop_testBadPat ] props2 = [ prop_testMatch , prop_testEndPattern ] allTests = do mapM_ quickCheck props1 mapM_ quickCheck props2 {- *KMPSeq> allTests OK, passed 100 tests. OK, passed 100 tests. OK, passed 100 tests. OK, passed 100 tests (15% trivial). OK, passed 100 tests. 41% Bigger pattern than search, Match Doesn't Exist. 24% Smaller pattern than search, Match Doesn't Exist. 12% trivial, Bigger pattern than search, Match Doesn't Exist. 11% Smaller pattern than search, Match Exists. 9% Equal pattern and search, Match Doesn't Exist. 3% Equal pattern and search, Match Exists. OK, passed 100 tests (100% Match Exists). -} From cgibbard at gmail.com Wed Aug 1 16:57:08 2007 From: cgibbard at gmail.com (Cale Gibbard) Date: Wed Aug 1 16:49:26 2007 Subject: [Haskell-cafe] monads and groups -- instead of loops In-Reply-To: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> References: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> Message-ID: <89ca3d1f0708011357x77e33686ja0248e849cdedc82@mail.gmail.com> On 01/08/07, Greg Meredith wrote: > Haskellians, > > Though the actual metaphor in the monads-via-loops doesn't seem to fly with > this audience, i like the spirit of the communication and the implicit > challenge: find a pithy slogan that -- for a particular audience, like > imperative programmers -- serves to uncover the essence of the notion. i > can't really address that audience as my first real exposure to programming > was scheme and i moved into concurrency and reflection after that and only > ever used imperative languages as means to an end. That said, i think i > found another metaphor that summarizes the notion for me. In the same way > that the group axioms organize notions of symmetry, including addition, > multiplication, reflections, translations, rotations, ... the monad(ic > axioms) organize(s) notions of snapshot (return) and update (bind), > including state, i/o, control, .... In short > > group : symmetry :: monad : update > > Best wishes, > > --greg Hello, I just wrote http://www.haskell.org/haskellwiki/Monads_as_computation after starting to reply to this thread and then getting sidetracked into writing a monad tutorial based on the approach I've been taking in the ad-hoc tutorials I've been giving on #haskell lately. :) It might be worth sifting through in order to determine an anthem for monads. Something along the lines of: "monads are just a specific kind of {embedded domain specific language, combinator library}" would work, provided that the person you're talking to knows what one of those is. :) I've found it very effective to explain those in general and then explain what a monad is in terms of them. I'm not certain that the article is completely finished. I'm a bit tired at the moment, and will probably return to polish the treatment some more when I'm more awake, but I think it's finished enough to usefully get the main ideas across. - Cale From dpiponi at gmail.com Wed Aug 1 16:57:56 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Wed Aug 1 16:50:16 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <46B0E6A0.3010707@imageworks.com> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> Message-ID: <625b74080708011357o5c85a0e9m71cd832e7d55a59b@mail.gmail.com> On 8/1/07, Dan Weston wrote: > The moral of the story is that monads are less than meets the eye. You > can create them and concatenate them I mostly sympathise with your rant, but I think you need to be clearer about what exactly is concatenated. In general you can't concatenate Monads. What you *can* concatenate are Kleisli arrows (ie. things of type Monad m => a -> m b). You can also apply Kleisli arrows to Monads, and that's what >>= does. I feel that talking about Monads without Kleisli arrows is like talking about category theory without arrows, or at least sets without functions. In each case, without the latter, the former is more or less useless. Also, I'm having a terminological difficulty that maybe someone can help with: 'Monad' is a type class. So what's 'IO'? Is the correct terminology 'instance' as in 'IO is an instance of Monad'. I consider 'IO' to be 'a monad' as that fits with mathematical terminology. But what about an actual object of type 'IO Int', say? Some people have been loosely calling such an object 'a monad'. That doesn't seem quite right. Maybe it's 'an instance of IO Int', though that's stretching the word 'instance' to meaning two different things. And if an object of type IO Int is in instance of IO Int, is it reasonable to also call it an 'instance of IO', or even 'an instance of Monad'? I'm sure there are proper words for all these things if someone fills me in. -- Dan From jeff.polakow at db.com Wed Aug 1 17:11:24 2007 From: jeff.polakow at db.com (Jeff Polakow) Date: Wed Aug 1 17:03:49 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <625b74080708011357o5c85a0e9m71cd832e7d55a59b@mail.gmail.com> Message-ID: Hello, > 'Monad' is a type class. > > So what's 'IO'? Is the correct terminology 'instance' as in 'IO is an > instance of Monad'. I consider 'IO' to be 'a monad' as that fits with > mathematical terminology. > I agree with this. >But what about an actual object of type 'IO > Int', say? > I usually describe the type resulting from applying a monad a computation. Then 'IO Int' would be something like an IO computation of an Int. This terminology also jibes well with, or rather comes from, Moggi's computational lambda calculus (one of the early papers showing uses of Monads to computer science). -Jeff --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/497e0f9b/attachment.htm From A.M.Gimblett at swansea.ac.uk Wed Aug 1 17:22:38 2007 From: A.M.Gimblett at swansea.ac.uk (Andy Gimblett) Date: Wed Aug 1 17:14:59 2007 Subject: [Haskell-cafe] Cartesian product of a Set In-Reply-To: <46B0F04C.1090604@imageworks.com> References: <20070801142801.GA7647@cspcag2.swan.ac.uk> <46B0F04C.1090604@imageworks.com> Message-ID: <20070801212238.GA28742@cspcag2.swan.ac.uk> On Wed, Aug 01, 2007 at 01:42:52PM -0700, Dan Weston wrote: > Andy Gimblett wrote: > > > >>cartesian :: Ord a => S.Set a -> S.Set (a,a) > >>cartesian x = S.fromList [(i,j) | i <- xs, j <- xs] > >> where xs = S.toList x > > Your list comprehension always generates a sorted list, so changing > S.fromList to its "unsafe" version (but guarateed by you) > S.fromDistinctAscList should get you back to O(n). That'll do it: with that change, my program runs eight times faster; according to the profiler, it's gone from spending ~85% of its time in cartesian to ~0%. :-) I don't see why my list comprehension always generates a sorted list, however: toList generates a sorted list? It doesn't claim to in the docs. Do I perhaps need to use toAscList instead? I happen to have put my data into the Set in order in this example, so maybe I just lucked out? Or am I missing something? > Of course the order of the generators was key (i before j). Lucky me. :-) Thanks! -Andy -- Andy Gimblett Computer Science Department University of Wales Swansea http://www.cs.swan.ac.uk/~csandy/ From stefanor at cox.net Wed Aug 1 17:24:08 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 1 17:16:28 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: References: Message-ID: <20070801212408.GA3691@localhost.localdomain> On Wed, Aug 01, 2007 at 01:48:07PM -0700, David Pollak wrote: > Howdy, > > I'm considering building a desktop app using Haskell. The primary target > for the app is Windows, but if it runs on Linux and Mac (Intel and PPC), > that'd be a bonus. I've got a bunch of questions that hopefully folks can > answer. I use a Unix; treat my answers as thus qualified. > Well, before I start, you might well be asking "Gee David, you're a Scala > kind of guy... I mean, you're the primary contributor to lift... why not use > Scala?" Well, I'm looking to build something that compiles down to native > code and has a smaller download (and runtime) footprint than the JVM > offers. I've come to love functional programming and am taking the current > side project as an opportunity to learn Haskell. > > So... on to the questions: > > - Can GHC generate stand-alone executables with all the dependencies > linked in such that I can distribute the single file without worrying about > including a bunch of DLLs/SOs? The answer seems to be yes, but I wanted to > confirm. Currently, GHC doesn't support generating shared libraries at all, so all you have to worry about is libc and friends, but that's usually pre-installled and some combination of -static -optl-static will fix it. > - How much of a distribution footprint is the Haskell runtime? If I > have a "Hello World" app, roughly how big will the EXE be (if one includes > the JRE in the runtime, a Java/Scala program has a minimum footprint of > 20M... that's big.) About 500kb. > - Same goes for the runtime... I've looked at the stats on the > Language Shootout home page and these look encouraging, but I wanted to see > if the reasonable footprint is a reality. It's pretty reasonable. I don't have exact numbers due to the vagarities of Linux demand loading, but Don reports that xmonad and dwm use very similar amounts of memory, ie whatever RTS overhead exists is swamped by the 2MB runtime footprint of Xlib. > - How real/solid/stable is the wxHaskell widgets package? Is it being > well maintained? Is there (okay... this is pie in the sky) an GUI Builder > for it? > - How are the Windows/COM bindings in Haskell... would it be possible > to, for example, embed an IE Browser COM control in a a wxHaskell window? Unknown. > - I found a package to do HTTP requests in Haskell but it does not > seem to support HTTPS. Is there an HTTPS client package for Haskell? Maybe soon; the current HTTP package is widely acknowledged as being in dire need of an overhaul, and Mietek Bak is doing exactly that as part of the SoC. > - How are Strings internally represented? Are they single byte or > multi-byte characters? How easy it is to translate to/from internal > representation to UTF-8? A cons-list of characters, so 12 bytes per character. Characters are internally memoized only if they are smaller than 256, so add 8 bytes for every non-latin1 character. Double the numbers for a 64-bit system. They can represent full Unicode, but there's none of the traditional "multi byte" stuff - one cell is one character. Quite easy, Mertens et al recently released a utf8-string library that should make it completely automatic. (I haven't used it yet) > - How's the XML support? Will the XML parser handle non-Latin > characters and properly encode stuff? Does XML get parsed down into easily > mappable/filterable collections? We have no less than three XML parsers, none of which I have experience using. > - Is there support for SHA256 (I saw an SSLeay package which had > support for a lot of stuff, but not SHA256)? Probably not. > - I understand that Haskell has "a better approach" to parallelizing > tasks, but I have not seen much about the actual manifestation of this... > would someone be so kind as to give me a pointer? http://www.macs.hw.ac.uk/~dsg/gph/papers/abstracts/strategies.html We also have ordinary threads with basic standard concurrency abstractions, Control.Concurrent.*. > - On a related note, I have become a fan (via Scala) of Erlang-style > Actors and asynchronous message passing. Are there any similar packages for > Haskell? Sure. Control.Concurrent.Chan gives asynchronous message passing. > - I tend to do most of my coding in either Emacs or Eclipse... how's > the Haskell support in either? Is there a preferred editor (I don't mean to > start any wars here... :-) Emacs and vi both have native support for Haskell. Emacs additionally has basic integration with the interactive environments (Reload buffer, stuff like that) and passable auto-indenting (hard to do right in a language with significant whitespace); B. Schmidt's "shim" package provides more, like automatic error highlighting. Eclipse supports Haskell via an addon-package "EclipseFP", I've only heard about it never used it. > - Are there any production Haskell-based desktop apps of note? > > Anyway... sorry for the long list of questions. I look forward to hearing > from you all and learning more about Haskell. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/1f39a0ba/attachment.bin From overdrigzed at gmail.com Wed Aug 1 17:37:03 2007 From: overdrigzed at gmail.com (Rodrigo Queiro) Date: Wed Aug 1 17:29:28 2007 Subject: [Haskell-cafe] Cartesian product of a Set In-Reply-To: <20070801212238.GA28742@cspcag2.swan.ac.uk> References: <20070801142801.GA7647@cspcag2.swan.ac.uk> <46B0F04C.1090604@imageworks.com> <20070801212238.GA28742@cspcag2.swan.ac.uk> Message-ID: <2eb8984a0708011437r27187a46na27b7a43ce8bb32f@mail.gmail.com> toList generates a sorted list since it is implemented as toList = toAscList, but it's probably bad form to rely on that. On 01/08/07, Andy Gimblett wrote: > On Wed, Aug 01, 2007 at 01:42:52PM -0700, Dan Weston wrote: > > > Andy Gimblett wrote: > > > > > >>cartesian :: Ord a => S.Set a -> S.Set (a,a) > > >>cartesian x = S.fromList [(i,j) | i <- xs, j <- xs] > > >> where xs = S.toList x > > > > Your list comprehension always generates a sorted list, so changing > > S.fromList to its "unsafe" version (but guarateed by you) > > S.fromDistinctAscList should get you back to O(n). > > That'll do it: with that change, my program runs eight times faster; > according to the profiler, it's gone from spending ~85% of its time in > cartesian to ~0%. :-) > > I don't see why my list comprehension always generates a sorted list, > however: toList generates a sorted list? It doesn't claim to in the > docs. Do I perhaps need to use toAscList instead? > > I happen to have put my data into the Set in order in this example, so > maybe I just lucked out? Or am I missing something? > > > Of course the order of the generators was key (i before j). > > Lucky me. :-) > > Thanks! > > -Andy > > -- > Andy Gimblett > Computer Science Department > University of Wales Swansea > http://www.cs.swan.ac.uk/~csandy/ > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From duncan.coutts at worc.ox.ac.uk Wed Aug 1 17:43:01 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 1 17:34:13 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: References: Message-ID: <1186004581.5989.139.camel@localhost> On Wed, 2007-08-01 at 13:48 -0700, David Pollak wrote: > So... on to the questions: First of all I recommend you check out these resources: The standard libraries: http://haskell.org/ghc/docs/latest/html/libraries/ A large collection of other libraries: http://hackage.haskell.org/ Another directory of apps and libraries, many of which are not yet available through hackage: http://haskell.org/haskellwiki/Applications_and_libraries > * Can GHC generate stand-alone executables with all the > dependencies linked in such that I can distribute the single > file without worrying about including a bunch of DLLs/SOs? The > answer seems to be yes, but I wanted to confirm. Yes, but the same is not true of any C dlls you link to, eg GUI libs like gtk or wx. > * How much of a distribution footprint is the Haskell runtime? > If I have a "Hello World" app, roughly how big will the EXE be > (if one includes the JRE in the runtime, a Java/Scala program > has a minimum footprint of 20M... that's big.) Statically linked hello world is 470K on my amd64 linux box. An equivalent GUI hello world with Gtk2Hs is 540K. These are still dynamically liked to libc and libgmp. > * Same goes for the runtime... I've looked at the stats on the > Language Shootout home page and these look encouraging, but I > wanted to see if the reasonable footprint is a reality. Not sure what you're asking here. The ghc rts is linked into the program. > * How real/solid/stable is the wxHaskell widgets package? Is it > being well maintained? Is there (okay... this is pie in the > sky) an GUI Builder for it? Perhaps someone who uses wxHaskell can help you with that. I help maintain Gtk2Hs so can tell you about that... Gtk2Hs is well maintained imho :-) We do releases roughly every 6 months. The last one was a couple weeks ago. It has an installer for Windows and it's included in several other platforms like debian, fedora, gentoo, freebsd and macports. The glade GUI builder can be used with Gtk2Hs on all platforms. > * How are the Windows/COM bindings in Haskell... would it be > possible to, for example, embed an IE Browser COM control in a > a wxHaskell window? There is a COM tool, not sure about embedding IE. Gtk2Hs supports embedding the mozilla rendering engine, though not on Windows at the moment. HDirect has not seen much maintenance but apparently there is an updated version that was used in VisualHaskell. Perhaps someone else can tell you more about HDirect, I'm not especially familiar with it. http://www.haskell.org/hdirect/ http://www.haskell.org/visualhaskell/ > * I found a package to do HTTP requests in Haskell but it does > not seem to support HTTPS. Is there an HTTPS client package > for Haskell? There's work on a libcurl binding going on at the moment. > * How are Strings internally represented? Are they single byte > or multi-byte characters? How easy it is to translate to/from > internal representation to UTF-8? Strings are represented as ordinary Haskell lists of Unicode code points. There are functions available for converting to and from byte sequences in UTF8 and other encodings (though not in the base packages at the moment). Both Gtk2Hs and wxHaskell support Unicode. > * How's the XML support? Will the XML parser handle non-Latin > characters and properly encode stuff? Does XML get parsed > down into easily mappable/filterable collections? There are 2 major xml packages, HaXml and HXT. You can download them and find their documentation on http://hackage.haskell.org/ > * Is there support for SHA256 (I saw an SSLeay package which had > support for a lot of stuff, but not SHA256)? The Crypto package supports SHA1. > * I understand that Haskell has "a better approach" to > parallelizing tasks, but I have not seen much about the actual > manifestation of this... would someone be so kind as to give > me a pointer? Look for Haskell's lightweight threads, STM and parallel strategies: Control.Concurrent Control.Concurrent.STM Control.Parallel.Strategies > * On a related note, I have become a fan (via Scala) of > Erlang-style Actors and asynchronous message passing. Are > there any similar packages for Haskell? Not so far as I know, though the concurrency library supports channels so you can use a pattern where a thread reads messages from a channel and post's messages to other channels. > * I tend to do most of my coding in either Emacs or Eclipse... > how's the Haskell support in either? Is there a preferred > editor (I don't mean to start any wars here... :-) Emacs, vim, nedit, gedit and others support Haskell syntax highlighting. Emacs has some additional ghci integration mode. There's a project to add Haskell support to Eclipse, though I'm not sure how mature it is. > * Are there any production Haskell-based desktop apps of note? xmonad, an X11 window manager VisualHaskell, a Haskell extension to VisualStudio There are a number of programs that use Gtk2Hs or wxHaskell which you can find linked from their websites including: dazzle, http://wxhaskell.sourceforge.net/applications.html pivotal, http://www.cs.kent.ac.uk/projects/pivotal/ himerge, http://fmap.us/himerge.html HRay, http://trappist.elis.ugent.be/~kehoste/Haskell/HRay/ Duncan From feeder.of.the.bears at gmail.com Wed Aug 1 17:45:46 2007 From: feeder.of.the.bears at gmail.com (David Pollak) Date: Wed Aug 1 17:38:09 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: <20070801212408.GA3691@localhost.localdomain> References: <20070801212408.GA3691@localhost.localdomain> Message-ID: Stefan, Thanks for the wicked quick response! On 8/1/07, Stefan O'Rear wrote: > > > > - I found a package to do HTTP requests in Haskell but it does not > > seem to support HTTPS. Is there an HTTPS client package for Haskell? > > Maybe soon; the current HTTP package is widely acknowledged as being in > dire need of an overhaul, and Mietek Bak is doing exactly that as part > of the SoC. Kewl. Are there any snapshots of his work? > > - How's the XML support? Will the XML parser handle non-Latin > > characters and properly encode stuff? Does XML get parsed down into > easily > > mappable/filterable collections? > > We have no less than three XML parsers, none of which I have experience > using. :-) Thanks, David -- lift, the fast, powerful, easy web framework http://liftweb.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/a2865e2f/attachment-0001.htm From claus.reinke at talk21.com Wed Aug 1 18:17:50 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Wed Aug 1 18:10:15 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> Message-ID: <039801c7d489$cd74a410$933b8351@cr3lt> a Monad is a type constructor with two operations, implementing a standard interface and following a few simple rules. the Monad type class tells you the interface (what operations you've got, and their types), the Monad laws tell you what all types implementing that interface should have in common. the monadic interface gives you two operations, one to throw things into a monad thing (return), and one to chain two monad things together (>>=). the chaining explicitly caters for information flowing from the first to the second parameter of (>>=). the monad laws tell you two useful facts about monad things thrown together in that way: whatever it is the monad does, anything just thrown into it will take no part in that action, and whichever way you use that chaining operation, the structure of chaining is irrelevant, only the ordering of chained monad things matters. there are usually other ways to create 'primitive' monadic things, which can be combined into complex monadic structures using the operations from the Monad interface. there is usually a way to interpret monadic structures built in this way (a 'run' operation of some kind). that's it, i think?-) claus examples include: - i/o: primitive monadic things are basic i/o operations, the 'run' operation is outside the language, applied to 'Main.main', and interprets (abstract) IO monad structures sequentially, starting with the leftmost innermost i/o operation in the structure and applying the second argument of (>>=) to the result of executing the first. - []: primitive monadic things are lists, the 'run' operation is the identity, ie, the lists are directly exposed as data structures, return creates a singleton list, (>>=) applies its second argument to each element of its first argument and concatenates the results (concatMap). - State: primitive monadic things are operations on a state type, returning a result and a state; return returns its parameter, passing its input state unchanged, (>>=) applies its first parameter to the input state, applies its second parameter to the result value and result state of the first. 'run' is runState and applies a (possibly) complex monadic thing to an input state, returning a result and a (modified) state. From feeder.of.the.bears at gmail.com Wed Aug 1 18:31:56 2007 From: feeder.of.the.bears at gmail.com (David Pollak) Date: Wed Aug 1 18:24:16 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: <1186004581.5989.139.camel@localhost> References: <1186004581.5989.139.camel@localhost> Message-ID: Duncan, Many thanks to you as well! On 8/1/07, Duncan Coutts wrote: > > On Wed, 2007-08-01 at 13:48 -0700, David Pollak wrote: > > > > * Can GHC generate stand-alone executables with all the > > dependencies linked in such that I can distribute the single > > file without worrying about including a bunch of DLLs/SOs? The > > answer seems to be yes, but I wanted to confirm. > > Yes, but the same is not true of any C dlls you link to, eg GUI libs > like gtk or wx. Okay... so I'll have to include the (for example GTK2 DLLs) with the distribution... > > * How real/solid/stable is the wxHaskell widgets package? Is it > > being well maintained? Is there (okay... this is pie in the > > sky) an GUI Builder for it? > > Perhaps someone who uses wxHaskell can help you with that. I help > maintain Gtk2Hs so can tell you about that... > > Gtk2Hs is well maintained imho :-) We do releases roughly every 6 > months. The last one was a couple weeks ago. It has an installer for > Windows and it's included in several other platforms like debian, > fedora, gentoo, freebsd and macports. I just grabbed a copy and installed it (on Ubuntu... my preferred development platform.) The glade GUI builder can be used with Gtk2Hs on all platforms. Very cool. I grabbed Glade as well. It's pretty sweet. > Both Gtk2Hs and wxHaskell support Unicode. Excellent. > > * Is there support for SHA256 (I saw an SSLeay package which had > > support for a lot of stuff, but not SHA256)? > > The Crypto package supports SHA1. > > * Are there any production Haskell-based desktop apps of note? > > xmonad, an X11 window manager > VisualHaskell, a Haskell extension to VisualStudio > > There are a number of programs that use Gtk2Hs or wxHaskell which you > can find linked from their websites including: > > dazzle, http://wxhaskell.sourceforge.net/applications.html > pivotal, http://www.cs.kent.ac.uk/projects/pivotal/ > himerge, http://fmap.us/himerge.html > HRay, http://trappist.elis.ugent.be/~kehoste/Haskell/HRay/ Thanks! David Duncan > > -- lift, the fast, powerful, easy web framework http://liftweb.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/874eba38/attachment.htm From stefanor at cox.net Wed Aug 1 18:41:53 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 1 18:34:14 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: References: <1186004581.5989.139.camel@localhost> Message-ID: <20070801224153.GA3938@localhost.localdomain> On Wed, Aug 01, 2007 at 03:31:56PM -0700, David Pollak wrote: > Duncan, > > Many thanks to you as well! > > On 8/1/07, Duncan Coutts wrote: > > > > On Wed, 2007-08-01 at 13:48 -0700, David Pollak wrote: > > > > > > > * Can GHC generate stand-alone executables with all the > > > dependencies linked in such that I can distribute the single > > > file without worrying about including a bunch of DLLs/SOs? The > > > answer seems to be yes, but I wanted to confirm. > > > > Yes, but the same is not true of any C dlls you link to, eg GUI libs > > like gtk or wx. > > > Okay... so I'll have to include the (for example GTK2 DLLs) with the > distribution... You can just use -static or -optl-static, which will cause C libraries like gtk or wx to be bundled statically. (Out of curiousity, what did I actually convey when I tried to express that in my last message?) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/fe80142f/attachment.bin From feeder.of.the.bears at gmail.com Wed Aug 1 18:49:13 2007 From: feeder.of.the.bears at gmail.com (David Pollak) Date: Wed Aug 1 18:41:32 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: <20070801224153.GA3938@localhost.localdomain> References: <1186004581.5989.139.camel@localhost> <20070801224153.GA3938@localhost.localdomain> Message-ID: On 8/1/07, Stefan O'Rear wrote: > > On Wed, Aug 01, 2007 at 03:31:56PM -0700, David Pollak wrote: > > Duncan, > > > > Many thanks to you as well! > > > > On 8/1/07, Duncan Coutts wrote: > > > > > > On Wed, 2007-08-01 at 13:48 -0700, David Pollak wrote: > > > > > > > > > > * Can GHC generate stand-alone executables with all the > > > > dependencies linked in such that I can distribute the single > > > > file without worrying about including a bunch of DLLs/SOs? > The > > > > answer seems to be yes, but I wanted to confirm. > > > > > > Yes, but the same is not true of any C dlls you link to, eg GUI libs > > > like gtk or wx. > > > > > > Okay... so I'll have to include the (for example GTK2 DLLs) with the > > distribution... > > You can just use -static or -optl-static, which will cause C libraries > like gtk or wx to be bundled statically. (Out of curiousity, what did I > actually convey when I tried to express that in my last message?) Stefan, >From your message, I understood that I could statically link the libraries and have a single large EXE. I understood from Duncan's message that I could not statically link to some DLLs. I was somewhat confused... :-) Thanks, David Stefan > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > > iD8DBQFGsQwxFBz7OZ2P+dIRAmYDAKC8VYaXv2O5q3ajHZibrABGh41E+ACgwcwA > EkZ3zGUYvJxu6zRF6CPBR8g= > =zCC2 > -----END PGP SIGNATURE----- > > -- lift, the fast, powerful, easy web framework http://liftweb.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/172e37b0/attachment.htm From duncan.coutts at worc.ox.ac.uk Wed Aug 1 18:55:04 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 1 18:46:16 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: References: <1186004581.5989.139.camel@localhost> Message-ID: <1186008904.5989.160.camel@localhost> On Wed, 2007-08-01 at 15:31 -0700, David Pollak wrote: > Duncan, > > Many thanks to you as well! > > On 8/1/07, Duncan Coutts wrote: > On Wed, 2007-08-01 at 13:48 -0700, David Pollak wrote: > > > * Can GHC generate stand-alone executables with all the > > dependencies linked in such that I can distribute the > single > > file without worrying about including a bunch of DLLs/SOs? > The > > answer seems to be yes, but I wanted to confirm. > > Yes, but the same is not true of any C dlls you link to, eg > GUI libs like gtk or wx. > > Okay... so I'll have to include the (for example GTK2 DLLs) with the > distribution... Yes. Those are available here: http://haskell.org/gtk2hs/win32/ As a demo of an windows installer for a prog that uses Gtk2Hs, see: http://haskell.org/~duncan/gtk2hs/LSystemSetup.exe (3.5Mb) At some point I intend to write some more detailed instructions on this, but in the mean time you can probably figure it out from the example. It's just a matter of putting the right dlls and other file in the right place, the .zip files have the right directory structure all ready, so that's pretty easy. > I just grabbed a copy and installed it (on Ubuntu... my preferred > development platform.) Note that it looks like Ubuntu doesn't have the latest version yet: http://packages.ubuntu.com/feisty/libdevel/libghc6-gtk-dev but that version should be ok for most stuff you want to do. Duncan From drtomc at gmail.com Wed Aug 1 19:00:24 2007 From: drtomc at gmail.com (Thomas Conway) Date: Wed Aug 1 18:52:44 2007 Subject: [Haskell-cafe] Backpatching In-Reply-To: <200708020851.26324.dm.maillists@gmail.com> References: <784a62100707312244gaaf478i41dba90d9b86dcd1@mail.gmail.com> <200708020851.26324.dm.maillists@gmail.com> Message-ID: <784a62100708011600y4e1dbfbp308cae32ca8bd3b4@mail.gmail.com> On 8/2/07, Daniel McAllansmith wrote: > On Wednesday 01 August 2007 17:44, Thomas Conway wrote: > > This sounds like a common problem type. Is there a well known solution > > to this sort of problem? > > Have you looked into Tying the Knot? > http://www.haskell.org/haskellwiki/Tying_the_Knot I'll need to look further, but I'd say this looks to be on the money. In many ways it's isomorphic to the logic variable solution (in Prolog) - it works so long as you don't look at the binding before the symbol table is complete (i.e. at the end of parsing). Neat. Except that the Haskell one does not require evil like var/1 to determine that there are missing bindings. That's pleasing - I knew I walked away from Prolog for a good reason[*]. T. [*] It did take a while though - my first Prolog interpreter was MicroProlog on the Sinclair Spectrum. And that was circa 1980. :-) -- Dr Thomas Conway drtomc@gmail.com Silence is the perfectest herald of joy: I were but little happy, if I could say how much. From westondan at imageworks.com Wed Aug 1 19:05:03 2007 From: westondan at imageworks.com (Dan Weston) Date: Wed Aug 1 18:57:42 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <625b74080708011357o5c85a0e9m71cd832e7d55a59b@mail.gmail.com> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> <625b74080708011357o5c85a0e9m71cd832e7d55a59b@mail.gmail.com> Message-ID: <46B1119F.5010808@imageworks.com> I knew someone was going to catch me wandering into the deep end of the pool! Having read large parts of your blog, I would never presume to tell you anything about Haskell or category theory, but what the hell... > I mostly sympathise with your rant, but I think you need to be clearer > about what exactly is concatenated. In general you can't concatenate > Monads. What you *can* concatenate are Kleisli arrows (ie. things of > type Monad m => a -> m b). You can also apply Kleisli arrows to > Monads, and that's what >>= does. > > I feel that talking about Monads without Kleisli arrows is like > talking about category theory without arrows, or at least sets without > functions. In each case, without the latter, the former is more or > less useless. OK, I'll be clearer. I did actually mean Kleisli arrows, though I disagree about your statement about concatenating monad instances and claims of "useless": Prelude> print "Hello" >> return 3 "Hello" 3 Granted, >> is not as "general" as >>=, so combining one monad instance with another is not as "general" as with a Kleisli arrow: concatenating degenerates to simple sequencing. Sequencing print statements is more rather than less useless to many people, but I see your point. Actually, you have made my point! :) The forgetful action of Kleisli arrows acting on a monad (or conversely the free algebra of a monad as a subspace of Kleisli arrows) is to my understanding intimately connected with the specialness of the IO monad. It is the continuous nature of Haskell monads that gives non-IO monads value. So I guess my rant really was about Kleisli arrows not all being forgetful functors, used only for their sequencing effect. It just sounded too hard to pull that argument off without reinforcing the myth that you need to know category theory to have a rant about Haskell tutorials. > Also, I'm having a terminological difficulty that maybe someone can help with: > > 'Monad' is a type class. Actually I thought it was a type class constructor. The monad Monad m => m a is continuous in its instance type a, which is important in establishing the relationship between >>= and >>. The Haskell type 'IO ()' is a monad instance that is also isomorphic to the discrete trivial monad, but that is not a Haskell Monad capital-M. I used the term "instance" because the type IO () is an instance of the typeclass IO, not for any more profound reason. Forgive the display of wanton ignorance above. After all, isn't that what ranting is all about? Dan Weston Dan Piponi wrote: > On 8/1/07, Dan Weston wrote: >> The moral of the story is that monads are less than meets the eye. You >> can create them and concatenate them > > I mostly sympathise with your rant, but I think you need to be clearer > about what exactly is concatenated. In general you can't concatenate > Monads. What you *can* concatenate are Kleisli arrows (ie. things of > type Monad m => a -> m b). You can also apply Kleisli arrows to > Monads, and that's what >>= does. > > I feel that talking about Monads without Kleisli arrows is like > talking about category theory without arrows, or at least sets without > functions. In each case, without the latter, the former is more or > less useless. > > Also, I'm having a terminological difficulty that maybe someone can help with: > > 'Monad' is a type class. > > So what's 'IO'? Is the correct terminology 'instance' as in 'IO is an > instance of Monad'. I consider 'IO' to be 'a monad' as that fits with > mathematical terminology. But what about an actual object of type 'IO > Int', say? Some people have been loosely calling such an object 'a > monad'. That doesn't seem quite right. Maybe it's 'an instance of IO > Int', though that's stretching the word 'instance' to meaning two > different things. And if an object of type IO Int is in instance of IO > Int, is it reasonable to also call it an 'instance of IO', or even 'an > instance of Monad'? I'm sure there are proper words for all these > things if someone fills me in. > -- > Dan > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From drtomc at gmail.com Wed Aug 1 19:20:26 2007 From: drtomc at gmail.com (Thomas Conway) Date: Wed Aug 1 19:12:45 2007 Subject: [Haskell-cafe] Re: Zippers, Random Numbers & Terrain In-Reply-To: References: <784a62100707292326u2b8fb37bl5fccb9b0c86ecf4c@mail.gmail.com> Message-ID: <784a62100708011620n40394375m5ffe46acb2da0ca1@mail.gmail.com> On 8/2/07, apfelmus wrote: > That concludes the infinite terrain generation for one dimension. For > higher dimension, one just needs to use 2D objects instead of intervals > to split into two or more pieces. For instance, one can divide > equilateral triangles into 4 smaller ones. In fact, it doesn't matter > whether the starting triangle is equilateral or not when using the > midpoints of the three sides to split it into four smaller triangles. Nice. The issue of the RNG running backwards was what made me realize that rather than using StdGen in the nodes, if you simply number them (Hmmm - the nodes are countably infinite :-)), you can then [e.g.] use a cryptographic hash or similar to turn them into random numbers. You can seed the hash to generate different terrains. You may be interested that in some of the code I wrote for the right angle isosceles triangle case, I got into precision problems. It turns out that all the vertices lie on positions with coordinates that are precisely sums of 2^-k (e.g. 0.5, 0.125, 0.625), yet each time you subdivide, the scaling factor on the side length is sqrt 2/2. The resultant rounding meant that instead of getting 0.5, I got 0.5000000003, or some such. After pondering on this for a while, I realized instead of representing the scale of the triangle as a Double, I could use (Either Double Double), with Left x representing the scale x, and Right x representing the scale x * sqrt 2 / 2. That way, all the rounding problems can be made to go away. Well, not all of them - after all Double has limited digits of mantissa, but down to quite small scales, the arithmetic will be precise. Actually, you could use (Either Rational Rational), except that performance would be [even more] atrocious. cheers, T. -- Dr Thomas Conway drtomc@gmail.com Silence is the perfectest herald of joy: I were but little happy, if I could say how much. From westondan at imageworks.com Wed Aug 1 19:34:32 2007 From: westondan at imageworks.com (Dan Weston) Date: Wed Aug 1 19:26:52 2007 Subject: [Haskell-cafe] Cartesian product of a Set In-Reply-To: <20070801212238.GA28742@cspcag2.swan.ac.uk> References: <20070801142801.GA7647@cspcag2.swan.ac.uk> <46B0F04C.1090604@imageworks.com> <20070801212238.GA28742@cspcag2.swan.ac.uk> Message-ID: <46B11888.9060802@imageworks.com> Since S.toAscList x is sorted (and yes, as another poster points out, you should use toAsciList to get that sorting guarantee), you can prove that your cartesian product list is also sorted. Data.Set will almost certainly always have access to the sorted list, but even if not, length x < length (cartesian x) for any nonempty list (n vs. n^2), so it's worth forcing it to sort. The Prelude defines the instance (Ord a, Ord b) => Ord (a, b), with the obvious lexicographic ordering that your list comprehension generates (fst varying more slowly than snd): sorted(xs) ==> sorted [(i,j) | i <- xs, j <- xs] >> This is *not* true if the generators are reversed: >> BAD: sorted(xs) =/=> sorted [(i,j) | j <- xs, i <- xs] This allows you to safely say: cartesian x = S.fromDistinctAscList [(i,j) | i <- xs, j <- xs] where xs = S.toAscList x -- fromDistinctAscList sorted precondition satisfied by construction with full confidence that (cartesian x) is a well-constructed set. It may be worth adding a comment that you have fulfilled your proof obligation in calling fromDistinctAscList, so others aren't left wondering. Dan Andy Gimblett wrote: > On Wed, Aug 01, 2007 at 01:42:52PM -0700, Dan Weston wrote: > >> Andy Gimblett wrote: >>>> cartesian :: Ord a => S.Set a -> S.Set (a,a) >>>> cartesian x = S.fromList [(i,j) | i <- xs, j <- xs] >>>> where xs = S.toList x >> Your list comprehension always generates a sorted list, so changing >> S.fromList to its "unsafe" version (but guarateed by you) >> S.fromDistinctAscList should get you back to O(n). > > That'll do it: with that change, my program runs eight times faster; > according to the profiler, it's gone from spending ~85% of its time in > cartesian to ~0%. :-) > > I don't see why my list comprehension always generates a sorted list, > however: toList generates a sorted list? It doesn't claim to in the > docs. Do I perhaps need to use toAscList instead? > > I happen to have put my data into the Set in order in this example, so > maybe I just lucked out? Or am I missing something? > >> Of course the order of the generators was key (i before j). > > Lucky me. :-) > > Thanks! > > -Andy > From isaacdupree at charter.net Wed Aug 1 19:28:08 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Wed Aug 1 19:28:15 2007 Subject: [Haskell-cafe] RE: Definition of the Haskell standard library In-Reply-To: References: <1185812841.5721.90.camel@localhost> <1185887417.5989.24.camel@localhost> Message-ID: <46B11708.50200@charter.net> Simon Peyton-Jones wrote: > When you install packages A,B,C, the documentation for A,B,C (and nothing > else) ought to be locally available as an integrated whole, much as at > the GHC web site. I don't know whether Cabal does, or could do, that, > but it's surely what one would expect. and would take some educating of users, like me who tend to use online resources even when there are equivalent local files available. Maybe mentioning it in the User's Guide or somewhere on the website would be enough. Actually sometimes I user-install library packages, not for the whole system; then should there be an integrated whole anywhere? Isaac From feeder.of.the.bears at gmail.com Wed Aug 1 20:29:15 2007 From: feeder.of.the.bears at gmail.com (David Pollak) Date: Wed Aug 1 20:21:34 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: <1186008904.5989.160.camel@localhost> References: <1186004581.5989.139.camel@localhost> <1186008904.5989.160.camel@localhost> Message-ID: Duncan, Okay... I'm pretty darned impressed. I downloaded the packages and got my first Haskell/Glade app running in about the same amount of time as it took me to get my first VS.Net app up and running. Thanks for the pointer to GTK2hs. I hope to have a nice app to add to the list of Haskell apps pretty soon. Thanks, David PS -- An extra big thanks to you and Stefan for your responsiveness! On 8/1/07, Duncan Coutts wrote: > > On Wed, 2007-08-01 at 15:31 -0700, David Pollak wrote: > > Duncan, > > > > Many thanks to you as well! > > > > On 8/1/07, Duncan Coutts wrote: > > On Wed, 2007-08-01 at 13:48 -0700, David Pollak wrote: > > > > > * Can GHC generate stand-alone executables with all the > > > dependencies linked in such that I can distribute the > > single > > > file without worrying about including a bunch of DLLs/SOs? > > The > > > answer seems to be yes, but I wanted to confirm. > > > > Yes, but the same is not true of any C dlls you link to, eg > > GUI libs like gtk or wx. > > > > Okay... so I'll have to include the (for example GTK2 DLLs) with the > > distribution... > > Yes. Those are available here: > http://haskell.org/gtk2hs/win32/ > > As a demo of an windows installer for a prog that uses Gtk2Hs, see: > http://haskell.org/~duncan/gtk2hs/LSystemSetup.exe > (3.5Mb) > > At some point I intend to write some more detailed instructions on this, > but in the mean time you can probably figure it out from the example. > It's just a matter of putting the right dlls and other file in the right > place, the .zip files have the right directory structure all ready, so > that's pretty easy. > > > I just grabbed a copy and installed it (on Ubuntu... my preferred > > development platform.) > > Note that it looks like Ubuntu doesn't have the latest version yet: > http://packages.ubuntu.com/feisty/libdevel/libghc6-gtk-dev > but that version should be ok for most stuff you want to do. > > Duncan > > -- lift, the fast, powerful, easy web framework http://liftweb.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/a7ccb872/attachment.htm From ninegua at gmail.com Wed Aug 1 20:55:41 2007 From: ninegua at gmail.com (Paul L) Date: Wed Aug 1 20:48:00 2007 Subject: [Haskell-cafe] GHC, GLUT and OS X Message-ID: <856033f20708011755l4cfc5ca2u9d1cff6eff915bc4@mail.gmail.com> I'm trying to get cross platform GLUT/OpenGL program to run, but even the simplest code hang on OS X with GHC 6.6 or GHC 6.6.1 import Graphics.UI.GLUT import Graphics.Rendering.OpenGL main = do getArgsAndInitialize createAWindow "Hello window" mainLoop createAWindow windowName = do createWindow windowName displayCallback $= clear [ColorBuffer] Has anyone been successful at getting GLUT to work on OS X? Regards, Paul L From duncan.coutts at worc.ox.ac.uk Wed Aug 1 21:03:19 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 1 20:54:29 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: References: <1186004581.5989.139.camel@localhost> <1186008904.5989.160.camel@localhost> Message-ID: <1186016599.5989.165.camel@localhost> On Wed, 2007-08-01 at 17:29 -0700, David Pollak wrote: > Duncan, > > Okay... I'm pretty darned impressed. > > I downloaded the packages and got my first Haskell/Glade app running > in about the same amount of time as it took me to get my first VS.Net > app up and running. Excellent :-) > Thanks for the pointer to GTK2hs. You're welcome. > I hope to have a nice app to add to the list of Haskell apps pretty > soon. We're always very happy to showcase applications of Gtk2Hs on the website: http://haskell.org/gtk2hs/archives/category/screenshots/ Duncan From ariep at xs4all.nl Wed Aug 1 21:06:51 2007 From: ariep at xs4all.nl (Arie Peterson) Date: Wed Aug 1 20:59:08 2007 Subject: [Haskell-cafe] Re: monads and groups -- instead of loops In-Reply-To: <5de3f5ca0708011223y322ec175p8b30422d5de76b3d@mail.gmail.com> References: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> <5de3f5ca0708011223y322ec175p8b30422d5de76b3d@mail.gmail.com> Message-ID: <5043.213.84.177.94.1186016811.squirrel@webmail.xs4all.nl> Math alert: mild category theory. Greg Meredith wrote: > But, along these lines i have been wondering for a while... the monad laws > present an alternative categorification of monoid. At least it's > alternative to monoidoid. I wouldn't call monads categorifications of monoids, strictly speaking. A monad is a monoid object in a category of endofunctors (which is a monoidal category under composition). What do you mean by a 'monoidoid'? I only know it as a perverse synonym of 'category' :-). > In the spirit of this thought, does anyone know of an > expansion of the monad axioms to include an inverse action? Here, i am > following an analogy > > monoidoid : monad :: groupoid : ??? First of all, I don't actually know the answer. The canonical option would be a group object in the endofunctor category (let's call the latter C). This does not make sense, however: in order to formulate the axiom for the inverse, we would need the monoidal structure of C (composition of functors) to behave more like a categorical product (to wit, it should have diagonal morphisms diag :: m a -> m (m a) ). Maybe there is a way to get it to work, though. After all, what we (in FP) call a commutative monad, is not commutative in the usual mathematical sense (again, C does not have enough structure to even talk about commutativity). > My intuition tells me this could be quite generally useful to computing in > situation where boxing and updating have natural (or yet to be discovered) > candidates for undo operations. i'm given to understand reversible > computing > might be a good thing to be thinking about if QC ever gets real... ;-) If this structure is to be grouplike, the inverse of an action should be not only a post-inverse, but also a pre-inverse. Is that would you have in mind? (If I'm not making sense, please shout (or ignore ;-) ).) Greetings, Arie From docmach at gmail.com Wed Aug 1 21:15:20 2007 From: docmach at gmail.com (Alan Mock) Date: Wed Aug 1 21:07:41 2007 Subject: [Haskell-cafe] GHC, GLUT and OS X In-Reply-To: <856033f20708011755l4cfc5ca2u9d1cff6eff915bc4@mail.gmail.com> References: <856033f20708011755l4cfc5ca2u9d1cff6eff915bc4@mail.gmail.com> Message-ID: <1B48BC84-F3CC-47BE-AF68-78562D0FA2AB@gmail.com> This works fine for me on PPC and x86 10.4.10. Which GLUT implementation are you using? Does the code hang or does it crash? Alan Mock On Aug 1, 2007, at 7:55 PM, Paul L wrote: > I'm trying to get cross platform GLUT/OpenGL program to run, but even > the simplest code hang on OS X with GHC 6.6 or GHC 6.6.1 > > import Graphics.UI.GLUT > import Graphics.Rendering.OpenGL > > main = do > getArgsAndInitialize > createAWindow "Hello window" > mainLoop > > createAWindow windowName = do > createWindow windowName > displayCallback $= clear [ColorBuffer] > > Has anyone been successful at getting GLUT to work on OS X? > > Regards, > Paul L > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From dry.green.tea at gmail.com Wed Aug 1 21:20:30 2007 From: dry.green.tea at gmail.com (Alexis Hazell) Date: Wed Aug 1 21:12:56 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <039801c7d489$cd74a410$933b8351@cr3lt> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> <039801c7d489$cd74a410$933b8351@cr3lt> Message-ID: <200708021120.31832.dry.green.tea@gmail.com> On Thursday 02 August 2007 08:17, Claus Reinke wrote: > a Monad is a type constructor with two operations, implementing > a standard interface and following a few simple rules. . . . . and this is one of the best definitions i've seen yet. Thanks Claus! i think we need to be looking at "What is a Monad?" issue from the point of view of putting together a Dictionary of Haskell. There's no room for long explanations - just a concise sentence or two that gets to the heart of what a Haskell Monad is. Personally, my feeling is that people are scared by Monads, not because of the name, but because whenever they ask about what a Monad essentially /is/, they get a plethora of less-than-concise explanations that often don't include the sort of straightforward starting definition than Claus has presented here. No wonder Monads seem scary when even experienced Haskell programmers put forward such a variety of attempts to describe what a Monad actually is! (In some ways, i'm reminded of discussions about what continuations are - many definitions are vague and involve hand-waving; only a few seem to provide a straightforward technical definition that doesn't skirt around the guts of the matter.) That's why i've banged on about presenting my own attempt at a concise definition - not because i think my definition is that great at all, but because it at least represents a starting point to work towards developing a concise definition that we can quote and /then/ elaborate on in the way that we think is most likely to convey how Monads work to the querent in question. And again, i really like Claus' elaboration: > the Monad type class tells you the interface (what operations > you've got, and their types), the Monad laws tell you what all > types implementing that interface should have in common. > > the monadic interface gives you two operations, one to throw > things into a monad thing (return), and one to chain two monad > things together (>>=). the chaining explicitly caters for information > flowing from the first to the second parameter of (>>=). > > the monad laws tell you two useful facts about monad things > thrown together in that way: whatever it is the monad does, > anything just thrown into it will take no part in that action, > and whichever way you use that chaining operation, the > structure of chaining is irrelevant, only the ordering of chained > monad things matters. > > there are usually other ways to create 'primitive' monadic things, > which can be combined into complex monadic structures using > the operations from the Monad interface. > > there is usually a way to interpret monadic structures built in > this way (a 'run' operation of some kind). Category theorists can define monads concisely using the language of their discipline - surely we can settle on a definition of Haskell Monads that would make sense to any programmer who has mastered basic programming concepts? i would suggest that Claus' definition, above, would be a great place to start. :-) Alexis. From westondan at imageworks.com Wed Aug 1 22:08:43 2007 From: westondan at imageworks.com (Dan Weston) Date: Wed Aug 1 22:01:03 2007 Subject: [Haskell-cafe] Re: monads and groups -- instead of loops In-Reply-To: <5de3f5ca0708011223y322ec175p8b30422d5de76b3d@mail.gmail.com> References: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> <5de3f5ca0708011223y322ec175p8b30422d5de76b3d@mail.gmail.com> Message-ID: <46B13CAB.5000502@imageworks.com> If you haven't read it, you might be interested in the paper Alimarine et al, "There and Back Again: Arrows for Invertible Programming" which can be found at http://www.st.cs.ru.nl/papers/2005/alia2005-biarrowsHaskellWorkshop.pdf Dan Weston Greg Meredith wrote: > Haskellians, > > But, along these lines i have been wondering for a while... the monad > laws present an alternative categorification of monoid. At least it's > alternative to monoidoid. In the spirit of this thought, does anyone > know of an expansion of the monad axioms to include an inverse action? > Here, i am following an analogy > > monoidoid : monad :: groupoid : ??? > > i did a search of the literature, but was probably using the wrong > terminology to try to find references. i would be very grateful for > anyone who might point me in the right direction. > > My intuition tells me this could be quite generally useful to computing > in situation where boxing and updating have natural (or yet to be > discovered) candidates for undo operations. i'm given to understand > reversible computing might be a good thing to be thinking about if QC > ever gets real... ;-) > > Best wishes, > > --greg From ajb at spamcop.net Wed Aug 1 22:10:27 2007 From: ajb at spamcop.net (ajb@spamcop.net) Date: Wed Aug 1 22:02:46 2007 Subject: [Haskell-cafe] Re: Knuth Morris Pratt for Lazy Bytestrings implementation In-Reply-To: <46B0F320.7090600@list.mightyreason.com> References: <20070801020709.GF21697@cse.unsw.EDU.AU> <46B0CB29.5080101@list.mightyreason.com> <46B0F320.7090600@list.mightyreason.com> Message-ID: <20070801221027.0wid9yxgkokw8ok0@webmail.spamcop.net> G'day all. Quoting ChrisK : > My optimized (and fixed) version of the code is attached. By the way. I don't know if this is relevant, but I'm curious if this approach is any faster: http://72.14.253.104/search?q=cache:kG4zvvkZPLYJ:www.haskell.org/hawiki/RunTimeCompilation I claim nothing except that it's an ugly hack. Cheers, Andrew Bromage From ninegua at gmail.com Wed Aug 1 22:11:58 2007 From: ninegua at gmail.com (Paul L) Date: Wed Aug 1 22:04:16 2007 Subject: [Haskell-cafe] GHC, GLUT and OS X In-Reply-To: <1B48BC84-F3CC-47BE-AF68-78562D0FA2AB@gmail.com> References: <856033f20708011755l4cfc5ca2u9d1cff6eff915bc4@mail.gmail.com> <1B48BC84-F3CC-47BE-AF68-78562D0FA2AB@gmail.com> Message-ID: <856033f20708011911j2babd825uc4f0e79393e2fa54@mail.gmail.com> I use x86 10.4.9, and loading it in GHCi doesn't work at all. It hang after the window pops up. BTW, compiling it using GHC to binary form seems to work. But unfortunately this is not acceptable as loading in GHCi is crucial for the purpose. I'm doing a port of the SOE Graphics from HGL to OpenGL/GLUT so that it could perform not only better but be truely cross-platform. Being able to load and run small code snippets from command line is likely a must-have for SOE users. The port is already working well on both Windows and Linux, and I'm hoping the same for OS X. Should I try another GLUT library instead? Or is it a problem of loading dynamic libraries on OS X? Regards, Paul L On 8/1/07, Alan Mock wrote: > This works fine for me on PPC and x86 10.4.10. Which GLUT > implementation are you using? Does the code hang or does it crash? > > Alan Mock > > On Aug 1, 2007, at 7:55 PM, Paul L wrote: > > > I'm trying to get cross platform GLUT/OpenGL program to run, but even > > the simplest code hang on OS X with GHC 6.6 or GHC 6.6.1 > > > > import Graphics.UI.GLUT > > import Graphics.Rendering.OpenGL > > > > main = do > > getArgsAndInitialize > > createAWindow "Hello window" > > mainLoop > > > > createAWindow windowName = do > > createWindow windowName > > displayCallback $= clear [ColorBuffer] > > > > Has anyone been successful at getting GLUT to work on OS X? > > > > Regards, > > Paul L > > _______________________________________________ > > Haskell-Cafe mailing list > > Haskell-Cafe@haskell.org > > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From ronguida at mindspring.com Wed Aug 1 22:24:45 2007 From: ronguida at mindspring.com (Ronald Guida) Date: Wed Aug 1 22:16:59 2007 Subject: [Haskell-cafe] Installing FreeGLUT Message-ID: <46B1406D.2000108@mindspring.com> Hi, I am trying to use freeglut with GHCi 6.6.1, and I'm stuck. I downloaded freeglut 2.4.0 and compiled it. I am on a Windows XP machine, and I found that freeglut compiled "out of the box" in MS Visual Studio.Net 2003. My difficulty is that GHCi is finding GLUT 2.2.1 and not freeglut. How do I get GHC and GHCi to recognize and use freeglut instead? Note: I'm using Windows XP; an upgrade to Linux is not an option. Thank you -- Ron From oleg at pobox.com Wed Aug 1 22:46:45 2007 From: oleg at pobox.com (oleg@pobox.com) Date: Wed Aug 1 22:42:34 2007 Subject: [Haskell-cafe] Parser inversions [Was: CC-delcont-0.1...] Message-ID: <20070802024645.64251AB53@Adric.metnet.fnmoc.navy.mil> Dan Doel wrote about `inverting' a parser -- first, a pure parser consuming a string and later a parser written in a monadic style and consuming a monadic list: data MList' m a = MNil | MCons a (MList m a) type MList m a = m (MList' m a) The second attempt proved fully successful: > So, success! Tokens are printed out as soon as the lexer is able to recognize > them, properly interleaved with other IO side effects, and resuming from an > intermediate parse does not cause duplication of output. Indeed, one may say `inverting' a parser is differentiating it. That is, we wish parse incrementally, to observe semantic actions as they are being performed. If the parser is a pure function then the only possible observation is that of its result given a specific input. To differentiate such a parser we feed it progressively longer inputs and observe differences in the output, the stream of parsed tokens. The first attempt followed this `classical calculus' recipe and wasn't fully successful, even though the parser used in that attempt was a good, _continuous_ parser. The parser for conventional arithmetic expressions such as "1+2" can generate parsed token 1 after it saw the first two characters, no matter what follows further in the input stream. Giving longer input to the parser will _progressively_ cause longer output. Alas, there are _discontinuous_ parsers, such XML DOM parsers. Let's consider the input text Until a pure parser sees (that is, the entire input document) it produces nothing at all (except errors that the XML document is ill-formed). Indeed, ill-formed documents have no Infoset (no `meaning') and hence DOM parsers must not return any parsed data for incomplete documents. As in calculus, differentiating such discontinuous functions is not helpful. Now, if the parser is monadic then effects and their sequence become observable too. We can truly observe the sequence of executed semantic actions. These actions are executed incrementally, as the parser recognized a part of input to which a semantic action applies. Delimited continuations, as a `scriptable debugger', let us observe the execution of the parser step by step. One way to differentiate is to embed `breakpoints' in the input stream, in the get-char-like routine the parser uses to obtain next piece of input. Such routines are typically under user control, who can embed breakpoints, aka shift. The MList data structure is a clever way to `hide' get-char routines out of sight. Another way to observe the sequence of actions is to embed breakpoints into semantic actions themselves. In many parsers, the grammar with semantic actions is provided by users and thus again under their control. This approach can `invert' a DOM XML parser into a streaming, pull-like SAX XML parser, provided the DOM parser exports suitable callbacks: http://okmij.org/ftp/Scheme/xml.html#SSAX-pull > So, that wasn't really that hard to hack up. However, I should mention > that it wasn't trivial, either. When converting list functions to > MList functions, you have to be very careful not to perform side > effects twice. Indeed: the major complexity of LogicT was making sure effects are not done twice. > ... many recursive data structures can be expressed as the fixed-point > of shape functors. The kicker is, you can get the monadic version for > free. Indeed, open recursion at the term level lets us transparently interpose, for example, memoization. The benefits of coding recursive data types with explicit open recursion have been described in Two-Level Types and Parameterized Modules Time Sheard and Emir Pasalic JFP v14 (5):547-587, Sept. 2004 http://web.cecs.pdx.edu/~sheard/papers/JfpPearl.ps In particular, please see the Section 8, History, near the end of the paper. Thank you indeed for packaging CC monad and LogicT! From ok at cs.otago.ac.nz Thu Aug 2 00:04:29 2007 From: ok at cs.otago.ac.nz (ok) Date: Wed Aug 1 23:56:52 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> <4c88418c0708010615y2e688376x3842746028c67183@mail.gmail.com> Message-ID: <8C2A96C0-9575-47CE-8750-8EEE46E61FF2@cs.otago.ac.nz> Someone asked about comparing monads to loops. If you are chiefly familiar with the i/o and state monads, that doesn't really make a lot of sense, but there IS a use of monads which IS a kind of loop. Only yesterday I was trying to read someone else's Haskell code where they had imported Control.Monad for the sake of >>= and liftM2. And how were they using >>= and liftM2? - they were using >>= on lists, where it means the same as concatMap To a beginner, I suggest that (concatMap f xs) is clearer than (xs >>= f) - they were using (liftM2 f xs ys) on lists, where it means the same as [f x y | x <- xs, y <- ys] No doubt there are people who find the monadic versions clearer. However, since the monadic operations *ARE* loops when applied to lists, it could very easily give rise to the misunderstanding that monads have something to do with looping. From ok at cs.otago.ac.nz Thu Aug 2 00:15:35 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 2 00:07:56 2007 Subject: [Haskell-cafe] Cartesian product of a Set In-Reply-To: <20070801142801.GA7647@cspcag2.swan.ac.uk> References: <20070801142801.GA7647@cspcag2.swan.ac.uk> Message-ID: On 2 Aug 2007, at 2:28 am, Andy Gimblett wrote: > Is this a reasonable way to compute the cartesian product of a Set? > >> cartesian :: Ord a => S.Set a -> S.Set (a,a) >> cartesian x = S.fromList [(i,j) | i <- xs, j <- xs] >> where xs = S.toList x Following up on my recent message about (ab)use of monadic operations, imagine presenting it this way: cartesian s = S.fromList $ liftM2 (,) s' s' where s' = S.toList s There are times to use monads and times not to. (One wonders whether S.Set is an instance of Monad, and if not, why not.) > > It's a fairly "obvious" way to do it, but I wondered if there were any > hidden gotchas. I'm particularly concerned by toList (O(n)) fromList > (O(n log n)) - but for other reasons I'd really like to be using Set > rather than List for this (I think). In fact it's worse than that. Given a set with n elements, the Cartesian product of that set with itself has n**2 elements, so S.fromList must take O(n**2.log(n**2)) = O(n**2.log n) time. If sets are represented as ordered lists, then the list comprehension above generates a suitably ordered result. On the other hand, I've usually found that it pays to avoid explicitly constructing things like Cartesian products. Could that be the case here? From ok at cs.otago.ac.nz Thu Aug 2 00:30:03 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 2 00:22:22 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: References: <00d401c7d447$fe1c1bd0$fa545370$@be> Message-ID: <319884CC-F3F6-4652-8BBF-20DDC029399D@cs.otago.ac.nz> On 2 Aug 2007, at 5:13 am, alpheccar wrote: > I think the problem is due to a few bad tutorial still available on > the web and which are making two mistakes: > > 1 - Focusing on the IO monad which is very special ; > 2 - Detailing the implementation. As a newie we don't care and we > would prefer to see how to use monads rather than how to develop > monads. > > When you look at monads you see they can be used for controlling > the evaluation order (list monad, error monad, IO monad). They can > be used for side effects (IO, state monad). They can be seen as > containers (list, Maybe). They can be used to provide a protected > environment (tainting). So, it is difficult to see what they have > in common. Of course, what they have in common is a set of > algebraic laws : the monadic laws but it does not help to know it. > > I think that a way to see monads (and a consequence of the monadic > laws) is that monads are interpreters for domain specific languages. And so on. But please, let's keep one foot in the real world if possible. Monads were invented to solve the "how do I do imperative programming in a pure functional language" problem. We teach schoolchildren how to add. They spend years counting and adding before we point out that x+y == y+x. Most people leave high school without EVER having to know that the whole numbers are a ring or what that means. When they DO learn that, the only way they can really make sense of it is to turn it back to front "a ring is a collection of things and operations that is rather like whole numbers". In order to get almost anything *done* in a Haskell program, you HAVE to learn about the IO monad. You can get an amazing amount of useful stuff done without EVER learning about any other monad at all. The IO monad gets in your face all the time. You teach the IO monad before anything else about monads because if you *don't* teach about that, if you delay it any longer than you have to, the students become convinced that you can't do anything useful in Haskell and lose interest in learning anything else about it. Focussing on the implementation? Well, I believe in giving my students the original papers. One of them is "How to Declare an Imperative". Telling the students about the implementation is *important* to *gain their trust*. There's magic in Haskell, but THIS isn't magic. I go over it again and again: ">>= acts like semicolon; it's all about sequencing." If you've read the Science of Discworld books you will be familiar with the phrase 'lies-to-children'. You DON'T tell them the full truth, because it would take a long time, confuse the marrow out of their bones, and leave them feeling this was masturbatory mathematics, not real programming, having no connection with real world interests. Once they are reasonably comfortable with the IO monad, you can introduce ST. Once they are reasonably comfortable with the use of ST for arrays, you can show them the axioms that are required for monads to work the way we expect. Once they have got *that*, you can then show them that Maybe is a monad in that we can define the operations in a useful way that also satisfies the axioms. Then we can go onto other monads, except that in a first course, there isn't time for that. But at least we haven't scared them off completely by telling them that monads are interpreters. From ninegua at gmail.com Thu Aug 2 00:48:04 2007 From: ninegua at gmail.com (Paul L) Date: Thu Aug 2 00:40:23 2007 Subject: [Haskell-cafe] GHC, GLUT and OS X In-Reply-To: <856033f20708011911j2babd825uc4f0e79393e2fa54@mail.gmail.com> References: <856033f20708011755l4cfc5ca2u9d1cff6eff915bc4@mail.gmail.com> <1B48BC84-F3CC-47BE-AF68-78562D0FA2AB@gmail.com> <856033f20708011911j2babd825uc4f0e79393e2fa54@mail.gmail.com> Message-ID: <856033f20708012148y1899fdn2bfc9abd326e1b4d@mail.gmail.com> Ok, a bit hacking reveals that GLUT on Mac OS X performs differently in GHCi and when compiled. I use the following code: ==== import Graphics.UI.GLUT import Graphics.Rendering.OpenGL main = do getArgsAndInitialize createAWindow "Hello window" mainLoop createAWindow windowName = do createWindow windowName displayCallback $= (clear [ColorBuffer] >> swapBuffers) --idleCallback $= Just (postRedisplay Nothing) passiveMotionCallback $= Just (putStrLn . show) ==== When compiled, it renders a black screen and prints the event when you move mouse over. It's crucial to have swapBuffers in displayCallback, otherwise it will not render. But if run in GHCi, it won't render a thing unless idleCallback line is uncommented. Also, it won't produce any output at mouse over. Another strange thing is with idleCallback set and swapBuffers removed, it still renders black screen in GHCi, but will not render when compiled. I wonder why the event callback is blocked when using GLUT in GHCi? Regards, Paul L From allbery at ece.cmu.edu Thu Aug 2 00:51:58 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Thu Aug 2 00:44:20 2007 Subject: [Haskell-cafe] GHC, GLUT and OS X In-Reply-To: <856033f20708012148y1899fdn2bfc9abd326e1b4d@mail.gmail.com> References: <856033f20708011755l4cfc5ca2u9d1cff6eff915bc4@mail.gmail.com> <1B48BC84-F3CC-47BE-AF68-78562D0FA2AB@gmail.com> <856033f20708011911j2babd825uc4f0e79393e2fa54@mail.gmail.com> <856033f20708012148y1899fdn2bfc9abd326e1b4d@mail.gmail.com> Message-ID: <3632AF21-36CC-429A-A620-9A32549DAB38@ece.cmu.edu> On Aug 2, 2007, at 0:48 , Paul L wrote: > Ok, a bit hacking reveals that GLUT on Mac OS X performs differently > in GHCi and when compiled. Hm, isn't there a problem with shared library initialization in GHCi? (In a compiled program it's handled by ld.so or equivalent; ghci loads shared objects dynamically.) -- 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 ok at cs.otago.ac.nz Thu Aug 2 01:57:25 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 2 01:49:46 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <200708021120.31832.dry.green.tea@gmail.com> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> <039801c7d489$cd74a410$933b8351@cr3lt> <200708021120.31832.dry.green.tea@gmail.com> Message-ID: <77F1AB62-B76D-4E60-9B3B-7FDE9547EB63@cs.otago.ac.nz> On 2 Aug 2007, at 1:20 pm, Alexis Hazell wrote: > Category theorists can define monads concisely using the language > of their > discipline - surely we can settle on a definition of Haskell Monads > that > would make sense to any programmer who has mastered basic programming > concepts? It all depends on what you mean "make sense to". I can tell my student that (an instance of Monad) is a type constructor applications of which support certain operations that must satisfy certain operations. They can memorise that. But it remains meaningless noise to them. What matters is not what monads *ARE* but what they are *FOR*. Why should anyone care what monads are until they know why monads matter? One of my colleagues here, who has worked in logic for many years, is fond of saying that there are "set theory" people who like to have their feet on the ground and "category theory" people who like to have their heads in the air. There's no dispute that you get a much better view with your head in the air; there is no dispute that the general definitions and understandings of monads have power and utility. Me, I'm a set theory person. I have no trouble with fields, got my head around tensors and Lie groups (or very nearly), and I even know what a fibre bundle is (got an A for that). All of this is *grounded*. But I have repeatedly hit category theory and as repeatedly bounced. Chapter 1? No trouble. Chapter 2? No trouble. Chapter 3? Bounce. If a "category theory" person wants to understand monads, they will be happy with an abstract approach and work down from there. But if a "set theory" person wants to understand monads, they have to start with simple specific cases. The IO monad first. The ST monad. Then perhaps Maybe and []. And then start learning about monad transformers. The understanding of monads as such will grow out of this; by the time they are ready to cope with these compact high level definitions people are talking about they won't need it any more. I don't have any numbers. It would be interesting if someone did a survey. But I suspect that "category theory" people are a minority even among functional programmers. How many O'Caml programmers worry about the definition of monads? So go on arguing about how to define monads for Haskell, but consider your audience. From ccshan at post.harvard.edu Thu Aug 2 01:30:18 2007 From: ccshan at post.harvard.edu (Chung-chieh Shan) Date: Thu Aug 2 01:51:55 2007 Subject: [Haskell-cafe] Re: Zippers, Random Numbers & Terrain References: <784a62100707292326u2b8fb37bl5fccb9b0c86ecf4c@mail.gmail.com> <784a62100708011620n40394375m5ffe46acb2da0ca1@mail.gmail.com> Message-ID: Thomas Conway wrote in article <784a62100708011620n40394375m5ffe46acb2da0ca1@mail.gmail.com> in gmane.comp.lang.haskell.cafe: > On 8/2/07, apfelmus wrote: > > That concludes the infinite terrain generation for one dimension. For > > higher dimension, one just needs to use 2D objects instead of intervals > > to split into two or more pieces. For instance, one can divide > > equilateral triangles into 4 smaller ones. In fact, it doesn't matter > > whether the starting triangle is equilateral or not when using the > > midpoints of the three sides to split it into four smaller triangles. > Nice. Nice indeed! The infinite binary tree of the terrain intervals reminds me of the hyperbolic plane, of course, and its use in arbitrary-precision real arithmetic (cue a real mathematician). > The issue of the RNG running backwards was what made me realize > that rather than using StdGen in the nodes, if you simply number them > (Hmmm - the nodes are countably infinite :-)), you can then [e.g.] use > a cryptographic hash or similar to turn them into random numbers. You > can seed the hash to generate different terrains. Isn't the whole point of a good RNG that running it forwards and backwards should be statistically the same? > You may be interested that in some of the code I wrote for the right > angle isosceles triangle case, I got into precision problems. [...] > After pondering on this for a while, I realized instead of > representing the scale of the triangle as a Double, I could use > (Either Double Double), with Left x representing the scale x, and > Right x representing the scale x * sqrt 2 / 2. That way, all the > rounding problems can be made to go away. Well, not all of them - > after all Double has limited digits of mantissa, but down to quite > small scales, the arithmetic will be precise. Actually, you could use > (Either Rational Rational), except that performance would be [even > more] atrocious. What about a possibly infinite list of binary digits in base sqrt(2)? Surely the beauty would overshadow any performance problems. (: -- Edit this signature at http://www.digitas.harvard.edu/cgi-bin/ken/sig "Elegance is optional." -- Richard A. O'Keefe From lgreg.meredith at biosimilarity.com Thu Aug 2 02:09:10 2007 From: lgreg.meredith at biosimilarity.com (Greg Meredith) Date: Thu Aug 2 02:01:30 2007 Subject: [Haskell-cafe] Re: monads and groups -- instead of loops Message-ID: <5de3f5ca0708012309h425e5e5dl7db1c9c5890dfbd9@mail.gmail.com> Arie, Thanks for your thoughtful reply. Comments in-lined. Best wishes, --greg Date: Thu, 2 Aug 2007 03:06:51 +0200 (CEST) > From: "Arie Peterson" > Subject: Re: [Haskell-cafe] Re: monads and groups -- instead of loops > To: haskell-cafe@haskell.org > Message-ID: < 5043.213.84.177.94.1186016811.squirrel@webmail.xs4all.nl> > Content-Type: text/plain;charset=iso-8859-1 > > Math alert: mild category theory. > > Greg Meredith wrote: > > > But, along these lines i have been wondering for a while... the monad > laws > > present an alternative categorification of monoid. At least it's > > alternative to monoidoid. > > I wouldn't call monads categorifications of monoids, strictly speaking. > A monad is a monoid object in a category of endofunctors (which is a > monoidal category under composition). Sorry, i was being as fast and loose with the term as the rest of the communities concerned with 'categorification' seem to be. What do you mean by a 'monoidoid'? I only know it as a perverse synonym of > 'category' :-). Indeed. > In the spirit of this thought, does anyone know of an > > expansion of the monad axioms to include an inverse action? Here, i am > > following an analogy > > > > monoidoid : monad :: groupoid : ??? > > First of all, I don't actually know the answer. > > The canonical option would be a group object in the endofunctor category > (let's call the latter C). This does not make sense, however: in order to > formulate the axiom for the inverse, we would need the monoidal structure > of C (composition of functors) to behave more like a categorical product > (to wit, it should have diagonal morphisms diag :: m a -> m (m a) ). It seems to me that there are two basic possibilities, here. One is that the ambient categories over which one formulates computational monads are almost always some type of Linear-Cartesian situation. So, you can possibly exploit the additional structure there. That's certainly been the general flavor of the situation that motivates me. Otherwise, you can go the route of trying to excavate structure that might give meaningful interpretations. This has appeal in that it is more general and might actually uncover something, but as you observe it's not immediate. i haven't wrestled with the idea in anger, yet, because i thought it such an obvious thing to try that someone would have already done the work and was hoping just to get a reference. Your note suggests that it might be worth digging a little. i wonder... does a Hopf algebra-like structure do the job? Maybe there is a way to get it to work, though. After all, what we (in FP) > call a commutative monad, is not commutative in the usual mathematical > sense (again, C does not have enough structure to even talk about > commutativity). > > > > My intuition tells me this could be quite generally useful to computing > in > > situation where boxing and updating have natural (or yet to be > discovered) > > candidates for undo operations. i'm given to understand reversible > > computing > > might be a good thing to be thinking about if QC ever gets real... ;-) > > If this structure is to be grouplike, the inverse of an action should be > not only a post-inverse, but also a pre-inverse. Is that would you have in > mind? > > > (If I'm not making sense, please shout (or ignore ;-) ).) > > > Greetings, > > Arie > -- L.G. Meredith Managing Partner Biosimilarity LLC 505 N 72nd St Seattle, WA 98103 +1 206.650.3740 http://biosimilarity.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070801/0b9dd62f/attachment-0001.htm From lgreg.meredith at biosimilarity.com Thu Aug 2 03:05:08 2007 From: lgreg.meredith at biosimilarity.com (Greg Meredith) Date: Thu Aug 2 02:57:33 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative Message-ID: <5de3f5ca0708020005o27974426g2038f68512447be3@mail.gmail.com> Ok, You wrote But please, let's keep one foot in the real world if possible. > Monads were invented to solve the "how do I do imperative programming > in a pure functional language" problem. > This is more than a little revisionist. Monads have been the subject of mathematical study before people had an inkling that they might apply to problems in computer science. Moggi didn't invent them, but noticed that they might have an application to issues of composition in computation. It is really intriguing that they do such a remarkable job of organizing notions of update and were not invented with this application in mind. So, revising history thus would be a real loss. Best wishes, --greg -- L.G. Meredith Managing Partner Biosimilarity LLC 505 N 72nd St Seattle, WA 98103 +1 206.650.3740 http://biosimilarity.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070802/99abd5c4/attachment.htm From bulat.ziganshin at gmail.com Thu Aug 2 04:10:01 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 2 04:05:42 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: References: Message-ID: <1052223849.20070802121001@gmail.com> Hello David, Thursday, August 2, 2007, 12:48:07 AM, you wrote: about concurrency - necessarily read paper "Tackling the awkward squad: monadic input/output, concurrency, exceptions, and foreign-language calls in Haskell" http://research.microsoft.com/Users/simonpj/papers/marktoberdorf/marktoberdorf.ps.gz one of current GSOC projects is the binding to LibCurl about SHA256 - if it's missed in Crypto package, you can use FFI to import this function from any C library -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From dry.green.tea at gmail.com Thu Aug 2 04:26:19 2007 From: dry.green.tea at gmail.com (Alexis Hazell) Date: Thu Aug 2 04:18:51 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <77F1AB62-B76D-4E60-9B3B-7FDE9547EB63@cs.otago.ac.nz> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <200708021120.31832.dry.green.tea@gmail.com> <77F1AB62-B76D-4E60-9B3B-7FDE9547EB63@cs.otago.ac.nz> Message-ID: <200708021826.21456.dry.green.tea@gmail.com> On Thursday 02 August 2007 15:57, ok wrote: > It all depends on what you mean "make sense to". > I can tell my student that (an instance of Monad) is a type constructor > applications of which support certain operations that must satisfy > certain operations. They can memorise that. But it remains meaningless > noise to them. What matters is not what monads *ARE* but what they are > *FOR*. Why should anyone care what monads are until they know why monads > matter? Well, i would argue that people learning Haskell come to quite quickly appreciate that these 'monad' things are very important in Haskell; that they have to learn about them in order to perform IO and maintain state[1]; and that it's for those reasons at least that they matter. In my experience, many programmers - including myself! :-) - then try to get their head around what a Haskell Monad "is", and start asking questions of more experienced Haskellers, trying to get some sense of a possible answer. It's at this point that i feel there's an issue. Haskell Monads are used FOR many many things. And rather than get to the core of what a Monad is, many people provide two or three motivating examples - examples which merely serve to show /some/ of what Monads are about, but which will lead astray any person who incorrectly assumes that these two or three examples constitute the totality of the Monadic universe, and who makes inferences about Monads accordingly. (To me, the notion that a Monad is merely a kind of loop is an example of this.) This is why i feel it's important to provide an agreed-upon minimalist definition of a Monad - it can serve as a /correct/ starting point (to be elaborated on, of course - as Claus did), rather than forcing the programmer new to Haskell to /guess/ what a Monad might "be". We keep trying to suggest that Monads aren't really that scary, but the fact that we can't seem to agree upon a straightforward definition of what a Monad "is" belies that - i feel it tends to convey that in fact Monads /are/ a very complex concept, that asking what Monads are is like asking what God is or something. :-P And in my opinion, feeling that a given topic is overwhelming complex can become a block to further learning. Alexis. [1] Yes, they're obviously used for many other things besides those two things; but it's these two cases that are often of most interest to programmers coming from a non-functional background. From wss at cs.nott.ac.uk Thu Aug 2 05:08:04 2007 From: wss at cs.nott.ac.uk (Wouter Swierstra) Date: Thu Aug 2 05:00:24 2007 Subject: [Haskell-cafe] Re: monads and groups -- instead of loops In-Reply-To: <5de3f5ca0708011223y322ec175p8b30422d5de76b3d@mail.gmail.com> References: <5de3f5ca0708010748t2251bea9pa5a04ae227fb4ac0@mail.gmail.com> <5de3f5ca0708011223y322ec175p8b30422d5de76b3d@mail.gmail.com> Message-ID: <35E53080-F1D5-447E-876D-5AEA60341E43@cs.nott.ac.uk> On 1 Aug 2007, at 21:23, Greg Meredith wrote: > But, along these lines i have been wondering for a while... the > monad laws present an alternative categorification of monoid. At > least it's alternative to monoidoid. In the spirit of this thought, > does anyone know of an expansion of the monad axioms to include an > inverse action? Here, i am following an analogy > > monoidoid : monad :: groupoid : ??? I'm not sure that's the right question. A monoid is a category with one object. A group is a category with one object, where every arrow is an iso. A groupoid is a category (with potentially more than one object), where every arrow is an iso. A monad is monoid in the category of endofunctors. Your "groupad", i.e. a group in the category of endofunctors, would boil down to having a monad m that has an unreturn :: m a -> a. In the light of things like unsafePerformIO, this is maybe not what you want. More interesting, however, is generalizing a monad to a monoid in functor categories in general, as opposed to just endofunctors. You could call this a "monadoid". I've heard Tarmo Uustalu talk about this once (Kan-extensions, coends, *mumble mumble mumble*). Mike Spivey's MSFP paper (http://spivey.oriel.ox.ac.uk/mike/msfp.pdf) mentions A-monads, which is a step in that direction. Anyhow, just a thought. Wouter From A.M.Gimblett at swansea.ac.uk Thu Aug 2 05:14:04 2007 From: A.M.Gimblett at swansea.ac.uk (Andy Gimblett) Date: Thu Aug 2 05:06:26 2007 Subject: [Haskell-cafe] Cartesian product of a Set In-Reply-To: References: <20070801142801.GA7647@cspcag2.swan.ac.uk> Message-ID: <20070802091404.GB32367@cspcag2.swan.ac.uk> On Thu, Aug 02, 2007 at 04:15:35PM +1200, ok wrote: > > On the other hand, I've usually found that it pays to avoid > explicitly constructing things like Cartesian products. Could that > be the case here? Quite possibly, though for my purposes I don't _think_ it's worth routing around it. I'm using it in a naive (and intentionally so) algorithm to search for "local top elements" in a partial order. That is, we require that the PO satisfies the property: for all a,b,c in PO . a <= b and a <= c => exists d in PO . b <= d and c <= d where a is a "local bottom element" for b and c, and d is the corresponding "local top element". Given a PO, for every such a, I want the set of corresponding d's. If any such set is empty, a big red "NO" lights up elsewhere in the program. My algorithm is the simplest thing I could think of that works: represent the PO as a Set of (a,a), then simply search its cartesian product, a Set of ((a,a),(a,a)), for elements of the right shape. It works, in only a few lines of code, and really looks a lot like the definition given above. It also seems to be fast enough for reasonably sized examples - for a PO with ~40 elements it's instantaneous. That's at the bottom end of "realistic" for my application, and I need to check it for ~100 elements (which is more like my reality), but I think it ought to be fine/usable. If, with real data, it turns out to be too slow then yes, I'll ditch this naive method and look at graph algorithms, which is of course the Smart thing to do. However, it's beautiful (to me) code right now, which strongly reflects the definition of the problem, so I'd be happy not to. :-) Cheers, -Andy -- Andy Gimblett Computer Science Department University of Wales Swansea http://www.cs.swan.ac.uk/~csandy/ From ithika at gmail.com Thu Aug 2 06:07:59 2007 From: ithika at gmail.com (Dougal Stanton) Date: Thu Aug 2 06:00:19 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <200708021826.21456.dry.green.tea@gmail.com> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <200708021120.31832.dry.green.tea@gmail.com> <77F1AB62-B76D-4E60-9B3B-7FDE9547EB63@cs.otago.ac.nz> <200708021826.21456.dry.green.tea@gmail.com> Message-ID: <2d3641330708020307y32fb614sb36ada9a218b4522@mail.gmail.com> On 02/08/07, Alexis Hazell wrote: > It's at this point that i feel there's an issue. Haskell Monads are used FOR > many many things. And rather than get to the core of what a Monad is, many > people provide two or three motivating examples - examples which merely serve > to show /some/ of what Monads are about, but which will lead astray any > person who incorrectly assumes that these two or three examples constitute > the totality of the Monadic universe, and who makes inferences about Monads > accordingly. (To me, the notion that a Monad is merely a kind of loop is an > example of this.) I agree with this very much. Monads are used for a great deal of things, some of which seem related (IO/State, []/Maybe) while others are utterly disconnected. Simon Peyton Jones has jokingly said that "warm fuzzy things" would have been a better choice of name. In seriousness, though, I think the exact name is not the problem. I would suggest that *having a name* is the problem. In imperative programming there are many idioms we would recognise. Take the "do something to an array" idiom: for (int i = 0; i < arr.length; i++) { arr[i] = foo(arr[i]); } This is a pretty obvious pattern. Some might say it's so obvious that it doesn't need a name. Yet we've got one in functional programming because we can. Without higher-order functions it's not possible to encapsulate and name such common idioms. It seems a bit superfluous to name something if you can't do anything with the name. But with higher-order functions we *can* encapsulate these ideas, and that means we *must* name them. Add to that the insatiable mathematical desire to abstract, abstract, abstract... Intuitively it seems that monads are similar, except the instances are much less obviously connected. It's easy to see the connection between State and IO. But those two to []? Do I have an suggestions? Well, maybe the right way would be to do as we do with map and fold, etc: show the explicitly recursive example, then generalise. So, show how we could we would thread state in Haskell, or how we would do optional (Maybe-style) values, then generalise, *slowly* coalescing the more similar monads first before reaching the 'top' of the monadic phylogenetic tree. Hmm, I can see that previous paragraph is not as clear as it could be. But anyway: has anyone used this approach before? Cheers, D. From niko.korhonen at gmail.com Thu Aug 2 06:28:59 2007 From: niko.korhonen at gmail.com (Niko Korhonen) Date: Thu Aug 2 06:21:26 2007 Subject: [Haskell-cafe] Re: Some Haskell platformish questions In-Reply-To: References: Message-ID: My answers apply to Windows/GHC. David Pollak wrote: > * Can GHC generate stand-alone executables with all the dependencies > linked in such that I can distribute the single file without > worrying about including a bunch of DLLs/SOs? The answer seems to > be yes, but I wanted to confirm. Yes. > * How much of a distribution footprint is the Haskell runtime? If I > have a "Hello World" app, roughly how big will the EXE be (if one > includes the JRE in the runtime, a Java/Scala program has a > minimum footprint of 20M... that's big.) A hello world application executable on Windows/GHC 6.6.1 is 592,385 bytes. But the size grows very quickly to 1-2 MB when you start including the basic libraries. > * Same goes for the runtime... I've looked at the stats on the > Language Shootout home page and these look encouraging, but I > wanted to see if the reasonable footprint is a reality. The memory footprint of a well-written Haskell program seems to be very small. I once wrote a text parser that only used a maximum of 2 MB of memory while processing an infinite stream. This is much less than the minimum footprint of the JVM. One reason for this is that the GHC garbage collector officially kicks ass. However, it is exceedingly easy to write memory-leaking programs in Haskell. Fortunately memory leaks usually manifest themselves as a program crash (stack overflow) or very high heap usage (easy to monitor in task explorer). In any case, the memory usage is pretty easy to monitor with GHC's built-in profiling facilities. Now fixing Haskell memory leaks... a completely different story. It's nothing short of black magic. Performing the simplest program optimizations and fixing the simplest of memory leaks generally requires a level of gurudom that is not even possible to achieve just with Java/C/C++ programming. Fixing a Haskell program usually involves performing a couple of sacred rites, sacrifices, voodoo rituals (you can consult your preferred deity, it doesn't matter). When that doesn't help, approach the Gurus of this forun, place the ritual Offering and plead for help. If they are satisfied with you, they might, just might, throw you a scrap of wisdom from their infinite mental capacity, which upon receiving will shock and humble you for life. Usually it sounds like this: "Here's a one line fold that replaces your entire program and doesn't have the memory leak." > * I tend to do most of my coding in either Emacs or Eclipse... how's > the Haskell support in either? Is there a preferred editor (I > don't mean to start any wars here... :-) Yes, there's a plugin for Eclipse. It's actually slightly better than the Scala plugin you're probably familiar with :) There's also a good syntax highlighting file for jEdit. Niko From scs4cajf at comp.leeds.ac.uk Thu Aug 2 06:44:19 2007 From: scs4cajf at comp.leeds.ac.uk (C Flynn) Date: Thu Aug 2 06:36:39 2007 Subject: [Haskell-cafe] Re: [HOpenGL] renderString problems In-Reply-To: References: Message-ID: On Wed, 1 Aug 2007, Dave Tapley wrote: > Hi all, > > I'm having a lot of trouble using renderString from Graphics.UI.GLUT.Fonts. > All my attempts to render a StrokeFont have so far failed. > Using a BitmapFont I can get strings to appear but they demonstrate > the odd behaviour of translating themselves a distance equal to their > length every time my displayCallback function is evaluated. > > My requests are: > * Does anyone know how to keep the position fixed? > * Are there any good examples of (working) GLUT code available on > the web, I'm finding it very hard to make any progress at the moment. > Certainly not at Haskell speed :( > > I am using the following code: > >> import Graphics.UI.GLUT >> main = do >> getArgsAndInitialize >> createWindow "" >> displayCallback $= update >> actionOnWindowClose $= ContinueExectuion >> mainLoop >> >> update = do >> clear [ColorBuffer] >> renderString Fixed8By13 $ "Test string" >> flush > > Cheers, > Dave > _______________________________________________ > HOpenGL mailing list > HOpenGL@haskell.org > http://www.haskell.org/mailman/listinfo/hopengl > I had a similar problem with stroke fonts. Try scaling by a low number (such as 0.01) and see where that gets you. The problem was it was rendering them at a size much bigger than my coordinate space that I just couldn't see them. I'm not convinced you need that $ there either but I don't suppose it hurts. Charles From bf3 at telenet.be Thu Aug 2 07:01:05 2007 From: bf3 at telenet.be (peterv) Date: Thu Aug 2 06:53:25 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <039801c7d489$cd74a410$933b8351@cr3lt> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> <039801c7d489$cd74a410$933b8351@cr3lt> Message-ID: <001701c7d4f4$6c83e380$458baa80$@be> IMHO although this is a great explanation of what a monad is (as far as I understand it), for newbies I think it helps a lot to first look at the specific cases where monads are used and why they are invented, as explained in http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html and then looking at http://haskell.org/haskellwiki/IO_inside for the IO thingy. However, one thing which I find annoying is that a "classic pure" function cannot evaluate an IO function unless you use unsafePerformIO; one must "promote" (?demote) the pure function into the IO monad. For example, as an exercise I tried to convert the Monte Carlo experiment as demonstrated in http://mitpress.mit.edu/sicp/full-text/sicp/book/node53.html into Haskell (warning: newbie code ahead, should be much nicer when I once become a real Haskeller in a million years ;-) In the code below I had to change the monteCarlo1 into a completely different monteCarlo2 in order to use the IO random facility. Okay, this is "expected behavior", but for an imperative programmer, this is quite a shock! Any ways of "promoting" such a pure function into the monadic one automatically? I tried playing with "liftM", without succes. import Data.Ratio import Data.List import System.Random import Control.Monad -- Monte Carlo using "pure" functions monteCarlo1 :: Integral n => n -> (a -> (a,Bool)) -> a -> Ratio n monteCarlo1 trials experiment startValue = trialsPassed % trials where trialsPassed = genericLength $ filter id outcomes outcomes = snd $ unzip $ genericTake trials $ iterate (experiment . fst) (experiment startValue) cesaroTest1 :: StdGen -> (StdGen, Bool) cesaroTest1 gen0 = (gen2, (gcd rand1 rand2) == 1) where (rand1, gen1) = random gen0 (rand2, gen2) = random gen1 estimatePi1 trials = sqrt $ 6 / (fromRational $ monteCarlo1 trials cesaroTest1 (mkStdGen 0)) -- Monte Carlo using monadic IO -- no genericReplicateM, so must use Int monteCarlo2 :: Int -> IO Bool -> IO (Ratio Integer) monteCarlo2 trials experiment = do outcomes <- replicateM trials experiment return $ fromIntegral (genericLength $ filter id outcomes) % fromIntegral trials cesaroTest2 = do rand1 <- getStdRandom random rand2 <- getStdRandom random return $ (gcd rand1 rand2) == 1 estimatePi2 trials = do mc <- monteCarlo2 trials cesaroTest2 return $ sqrt $ 6 / (fromRational mc) main = let pi1 = estimatePi1 50000 in do pi2 <- estimatePi2 50000 putStrLn (show pi1) >> putStrLn (show pi2) -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Claus Reinke Sent: Thursday, August 02, 2007 12:18 AM To: haskell-cafe@haskell.org Subject: Re: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer a Monad is a type constructor with two operations, implementing a standard interface and following a few simple rules. the Monad type class tells you the interface (what operations you've got, and their types), the Monad laws tell you what all types implementing that interface should have in common. the monadic interface gives you two operations, one to throw things into a monad thing (return), and one to chain two monad things together (>>=). the chaining explicitly caters for information flowing from the first to the second parameter of (>>=). the monad laws tell you two useful facts about monad things thrown together in that way: whatever it is the monad does, anything just thrown into it will take no part in that action, and whichever way you use that chaining operation, the structure of chaining is irrelevant, only the ordering of chained monad things matters. there are usually other ways to create 'primitive' monadic things, which can be combined into complex monadic structures using the operations from the Monad interface. there is usually a way to interpret monadic structures built in this way (a 'run' operation of some kind). that's it, i think?-) claus examples include: - i/o: primitive monadic things are basic i/o operations, the 'run' operation is outside the language, applied to 'Main.main', and interprets (abstract) IO monad structures sequentially, starting with the leftmost innermost i/o operation in the structure and applying the second argument of (>>=) to the result of executing the first. - []: primitive monadic things are lists, the 'run' operation is the identity, ie, the lists are directly exposed as data structures, return creates a singleton list, (>>=) applies its second argument to each element of its first argument and concatenates the results (concatMap). - State: primitive monadic things are operations on a state type, returning a result and a state; return returns its parameter, passing its input state unchanged, (>>=) applies its first parameter to the input state, applies its second parameter to the result value and result state of the first. 'run' is runState and applies a (possibly) complex monadic thing to an input state, returning a result and a (modified) state. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From Alistair_Bayley at invescoperpetual.co.uk Thu Aug 2 07:17:07 2007 From: Alistair_Bayley at invescoperpetual.co.uk (Bayley, Alistair) Date: Thu Aug 2 07:09:26 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <001701c7d4f4$6c83e380$458baa80$@be> Message-ID: <125EACD0CAE4D24ABDB4D148C4593DA901BDFBD0@GBLONXMB02.corp.amvescap.net> > From: haskell-cafe-bounces@haskell.org > [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of peterv > > However, one thing which I find annoying is that a "classic > pure" function cannot evaluate an IO function unless you use > unsafePerformIO; one must "promote" (?demote) the pure > function into the IO monad. That's just a property of the IO monad, rather than monads in general: http://www.haskell.org/all_about_monads/html/laws.html#nowayout > Any ways of "promoting" such a pure function into the monadic > one automatically? I tried playing with "liftM", without succes. This is where Claus plugs HaRe :-) (although liftM + friends is normally what one uses). You might find this relevant: http://www.cs.kent.ac.uk/projects/refactor-fp/catalogue/Monadification1. html Some people (but I'm not sure who) probably write most of their Haskell code in a monadic style, so as to make conversion between various monads less painful. It's still pure... Alistair ***************************************************************** Confidentiality Note: The information contained in this message, and any attachments, may contain confidential and/or privileged material. It is intended solely for the person(s) or entity to which it is addressed. Any review, retransmission, dissemination, or taking of any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you received this in error, please contact the sender and delete the material from any computer. ***************************************************************** From scook0 at gmail.com Thu Aug 2 07:31:47 2007 From: scook0 at gmail.com (Stuart Cook) Date: Thu Aug 2 07:24:04 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <2d3641330708020307y32fb614sb36ada9a218b4522@mail.gmail.com> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <200708021120.31832.dry.green.tea@gmail.com> <77F1AB62-B76D-4E60-9B3B-7FDE9547EB63@cs.otago.ac.nz> <200708021826.21456.dry.green.tea@gmail.com> <2d3641330708020307y32fb614sb36ada9a218b4522@mail.gmail.com> Message-ID: <49b351060708020431s3cb01ef2m7c4c25f886c3cbe8@mail.gmail.com> On 8/2/07, Dougal Stanton wrote: > Do I have an suggestions? Well, maybe the right way would be to do as > we do with map and fold, etc: show the explicitly recursive example, > then generalise. So, show how we could we would thread state in > Haskell, or how we would do optional (Maybe-style) values, then > generalise, *slowly* coalescing the more similar monads first before > reaching the 'top' of the monadic phylogenetic tree. > > Hmm, I can see that previous paragraph is not as clear as it could be. > But anyway: has anyone used this approach before? These immediately came to mind: "You Could Have Invented Monads! (And Maybe You Already Have.)" http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html [http://tinyurl.com/ecqzl] "Monads for Functional Programming" http://citeseer.ist.psu.edu/wadler95monads.html [http://tinyurl.com/2foj46] I personally received my first monadic enlightenment from Bird's "Introduction to Functional Programming using Haskell", which also uses the same approach. I think it's an excellent way to approach the topic. Stuart Cook From scook0 at gmail.com Thu Aug 2 07:41:33 2007 From: scook0 at gmail.com (Stuart Cook) Date: Thu Aug 2 07:33:49 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <46B0B732.1010905@ropine.com> References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> <46B0B732.1010905@ropine.com> Message-ID: <49b351060708020441l73215edeyc7f369f352c8f7f3@mail.gmail.com> On 8/2/07, Seth Gordon wrote: > Haskell solves the "how can I do I/O in a pure functional language" > problem by *turning the world inside-out*. Instead of taking data from > the mutable outside world, using functions to manipulate it, and > depositing results back into that world, you put your functions into the > IO monad. That's a very interesting perspective. One of the questions often asked by Haskell newcomers is "how do I turn an IO a into an a?". The correct answer is that you don't; instead, you use a function (a -> m b) to indicate what you would have done with that a, and the bind operator takes care of the messy details for you. Stuart From scook0 at gmail.com Thu Aug 2 08:15:15 2007 From: scook0 at gmail.com (Stuart Cook) Date: Thu Aug 2 08:07:32 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <625b74080708011357o5c85a0e9m71cd832e7d55a59b@mail.gmail.com> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> <625b74080708011357o5c85a0e9m71cd832e7d55a59b@mail.gmail.com> Message-ID: <49b351060708020515g6a99219bne6bc7c543df92469@mail.gmail.com> On 8/2/07, Dan Piponi wrote: > I feel that talking about Monads without Kleisli arrows is like > talking about category theory without arrows, or at least sets without > functions. In each case, without the latter, the former is more or > less useless. The chapter on monads in Bird's "Introduction to Functional Programming using Haskell" introduces an operator (<>) that's equivalent to (>>>) on Kleisli arrows, without the intermediate newtype. One nice property of this operator is that it turns "return" into a genuine identity, rather than the weird pseudo-identity that it forms with (>>=). Sadly I don't actually own a copy of the book, so most of this is from memory. > Also, I'm having a terminological difficulty that maybe someone can help with: > > [snip][What's a good word for an object of type IO Int?] I tend to call it a "value in the [IO] monad". I don't claim to be a canonical reference, though. Stuart From scook0 at gmail.com Thu Aug 2 08:28:23 2007 From: scook0 at gmail.com (Stuart Cook) Date: Thu Aug 2 08:20:40 2007 Subject: [Haskell-cafe] renderString problems In-Reply-To: References: Message-ID: <49b351060708020528m5a70861fka76738a9fb4d69e6@mail.gmail.com> On 8/2/07, Dave Tapley wrote: > Using a BitmapFont I can get strings to appear but they demonstrate > the odd behaviour of translating themselves a distance equal to their > length every time my displayCallback function is evaluated. I've never used OpenGL from Haskell, but it sounds like renderString is modifying your modelview matrix with each call, presumably to make it easier to chain lots of text together in one frame. Since the matrix never gets reset, the translation effect accumulates each time the scene is redrawn. The quick fix would be to call loadIdentity (i.e. glLoadIdentity) each time you update, before drawing anything. Stuart From claudiusmaximus at goto10.org Thu Aug 2 09:07:58 2007 From: claudiusmaximus at goto10.org (Claude Heiland-Allen) Date: Thu Aug 2 09:00:56 2007 Subject: [Haskell-cafe] renderString problems In-Reply-To: References: Message-ID: <46B1D72E.8030204@goto10.org> Hi Dave, everyone... Dave Tapley wrote: > Hi all, > > I'm having a lot of trouble using renderString from Graphics.UI.GLUT.Fonts. > All my attempts to render a StrokeFont have so far failed. > Using a BitmapFont I can get strings to appear but they demonstrate > the odd behaviour of translating themselves a distance equal to their > length every time my displayCallback function is evaluated. > > My requests are: > * Does anyone know how to keep the position fixed? One way is to wrap the drawing action with preservingMatrix : http://cvs.haskell.org/Hugs/pages/libraries/OpenGL/Graphics-Rendering-OpenGL-GL-CoordTrans.html#v%3ApreservingMatrix (re-exported from the main GLUT module, if I read the docs correctly) This pushes the transformation state to a stack, executes the action, and restores the transformation state from the stack. More useful when you have complex scenes/subscenes/subsubscenes etc, but should work here too. > [snip] Claude -- http://claudiusmaximus.goto10.org From ninegua at gmail.com Thu Aug 2 10:12:04 2007 From: ninegua at gmail.com (Paul L) Date: Thu Aug 2 10:04:22 2007 Subject: [Haskell-cafe] renderString problems In-Reply-To: References: Message-ID: <856033f20708020712g477674acm96bbd724782af2d1@mail.gmail.com> Your code is not rendering stroke font, but bitmap. Use the following code to render str at x and y position. GL.currentRasterPosition $= vertex4 x y 0 1 GLUT.renderString GLUT.Fixed8By13 str where vertex4 is defined as: vertex4 :: Float -> Float -> Float -> Float -> GL.Vertex4 Float vertex4 = GL.Vertex4 Note that the coordinate system for rasterization is different from GL's transformation matrix. If you really want the stroke font, you should use Roman or MonoRoman, then you may transform your position using GL.translate (GL.Vector3 x y 0). Regards, Paul L On 8/1/07, Dave Tapley wrote: > Hi all, > > I'm having a lot of trouble using renderString from Graphics.UI.GLUT.Fonts. > All my attempts to render a StrokeFont have so far failed. > Using a BitmapFont I can get strings to appear but they demonstrate > the odd behaviour of translating themselves a distance equal to their > length every time my displayCallback function is evaluated. > > My requests are: > * Does anyone know how to keep the position fixed? > * Are there any good examples of (working) GLUT code available on > the web, I'm finding it very hard to make any progress at the moment. > Certainly not at Haskell speed :( > > I am using the following code: > > > import Graphics.UI.GLUT > > main = do > > getArgsAndInitialize > > createWindow "" > > displayCallback $= update > > actionOnWindowClose $= ContinueExectuion > > mainLoop > > > > update = do > > clear [ColorBuffer] > > renderString Fixed8By13 $ "Test string" > > flush > > Cheers, > Dave > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From jeremy.odonoghue at gmail.com Thu Aug 2 10:37:09 2007 From: jeremy.odonoghue at gmail.com (Jeremy O'Donoghue) Date: Thu Aug 2 10:29:32 2007 Subject: [Haskell-cafe] Some Haskell platformish questions In-Reply-To: References: Message-ID: Hi David, On 01/08/07, David Pollak wrote: [snip] > Can GHC generate stand-alone executables with all the dependencies linked in > such that I can distribute the single file without worrying about including > a bunch of DLLs/SOs? The answer seems to be yes, but I wanted to confirm. Yes - and I've found it to be easy (on Windows) to wrap the whole thing in an InnoSetup installer. > How much of a distribution footprint is the Haskell runtime? If I have a > "Hello World" app, roughly how big will the EXE be (if one includes the JRE > in the runtime, a Java/Scala program has a minimum footprint of 20M... > that's big.) I wrote a moderately complex GUI application for exploring and viewing the contents of ELF binaries. It comes up as an 8MB executable with another 4.6MB of DLLs (wxWidgets at 2.7MB and the wxWidgets wrapper for wxhaskell at 1.8 MB). This makes pretty extensive use of various Haskell libraries, and is probably realistic for a GUI app of moderate complexity. > Same goes for the runtime... I've looked at the stats on the Language > Shootout home page and these look encouraging, but I wanted to see if the > reasonable footprint is a reality. Footprint is actually very reasonable. While browsing ELF binaries of around 100MB, footprint is about 50MB, and I didn't try optimizing very hard - it was 'good enough' out of the box. > How real/solid/stable is the wxHaskell widgets package? Is it being well > maintained? Is there (okay... this is pie in the sky) an GUI Builder for > it? I'm one of the maintainers of wxHaskell. It is maintained, but none of us has anywhere near as much time as we would like (everyone has day jobs...). It is very stable and reliable, but currently not much fun to build (although watch this space...). There's no GUI builder, I'm afraid. The big bonus is that it runs well, and natively, on Windows, OS X and Linux. > How are the Windows/COM bindings in Haskell... would it be possible to, for > example, embed an IE Browser COM control in a a wxHaskell window? I've yet to manage such a thing. My impression is that most of the COM tools for Haskell suffer bit-rot to some degree or another. I've never managed to get any of them to work properly. > I understand that Haskell has "a better approach" to parallelizing tasks, > but I have not seen much about the actual manifestation of this... would > someone be so kind as to give me a pointer? Note that some care is needed with GUI packages (wxhaskell for sure, and I think Gtk2Hs also) when used in multi-threaded environment. > I tend to do most of my coding in either Emacs or Eclipse... how's the > Haskell support in either? Is there a preferred editor (I don't mean to > start any wars here... :-) Emacs support is very good. It's where I spend my life (although sadly more often in C++-mode than Haskell-mode right now...) > Are there any production Haskell-based desktop apps of note? The ELF explorer I mentioned early is deployed to about 100 people at the company where I work, and has required almost no support as it 'just works'. I think this is due more to the excellence of Haskell type checker than anything I did right... Sadly I can't open-source it. I can confirm that it took about 20% of the time to write and debug than it would have in C++, despite the fact that I've been programming in C and C++ for 20 years, and didn't know my monads from my functors when I started :-) From ninegua at gmail.com Thu Aug 2 10:43:33 2007 From: ninegua at gmail.com (Paul L) Date: Thu Aug 2 10:35:50 2007 Subject: [Haskell-cafe] Installing FreeGLUT In-Reply-To: <46B1406D.2000108@mindspring.com> References: <46B1406D.2000108@mindspring.com> Message-ID: <856033f20708020743p15a7bd4cx16ff2322a44540a2@mail.gmail.com> GHC as of now won't be able to recognize your change to the dynamic libraries on the fly. So if you want to use new features, you'll have to compile GLUT package for GHC freshly on top of your new freeglut. Get the GLUT source from hackage.haskell.org and do the cabal installation. GHC will then be able to recognize the freeglut, at least confirmed by experiments on my Linux box a few days ago. Regards, Paul L On 8/1/07, Ronald Guida wrote: > Hi, > > I am trying to use freeglut with GHCi 6.6.1, and I'm stuck. I > downloaded freeglut 2.4.0 and compiled it. I am on a Windows XP > machine, and I found that freeglut compiled "out of the box" in MS > Visual Studio.Net 2003. > > My difficulty is that GHCi is finding GLUT 2.2.1 and not freeglut. How > do I get GHC and GHCi to recognize and use freeglut instead? > > Note: I'm using Windows XP; an upgrade to Linux is not an option. > > Thank you > -- Ron > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From ninegua at gmail.com Thu Aug 2 10:51:11 2007 From: ninegua at gmail.com (Paul L) Date: Thu Aug 2 10:43:29 2007 Subject: [Haskell-cafe] Exiting GLUT application In-Reply-To: References: <200707312316.09949.coeus@gmx.de> Message-ID: <856033f20708020751h4d64cac9l6d2eb57c72b20685@mail.gmail.com> Are you trying it on Linux? I had exactly the same problem. I believe it's with with X11/OpenGL. I've written C programs using GLUT, freeGLUT and GLFW (another OpenGL Window Kit) to re-open window after first one is closed. Unfortunately all gave the same fault. So it leads me to believe the problem is not really GLUT specific. I've not tried other platforms. So I ended up using a trick that always keeps the first window and reuse it for GHCi session. Just hide it and show it would make no difference to the end user, at least true on both Windows and Linux. Mac now has a problem prevents getting GLUT event when loaded in GHCi. Regards, Paul Liu On 8/1/07, Dave Tapley wrote: > Unfortunately whilst the new code is returning me to a 'Main >' prompt > as required another problem has come up. > > The issue here is found when the code is executed in both GHCi (6.6) > and hugs (20050308). > Once the code below is loaded evaluating main opens an unfilled window > as required. > > However if this window is closed and main is evaluated again both GHCi > and hugs die thus: > > GHCi: Illegal instruction (core dumped) > hugs: Unexpected signal > > Any thoughts? > > > On 31/07/07, Dave Tapley wrote: > > Excellent, thank you Marc your advice worked perfectly. > > > > For reference the corrected code reads: > > > > > import Graphics.UI.GLUT > > > main = do > > > getArgsAndInitialize > > > createWindow "" > > > actionOnWindowClose $= ContinueExectuion > > > mainLoop > > > > Dave, > > > > > > On 31/07/07, Marc A. Ziegert wrote: > > > in old glut, the main loop was the core of the single threaded program. exiting it did mean to exit the program completely. > > > in freeglut, you have alternatives. but for compatibility, it defaults to the old behaviour. > > > > > > > > > > > > - marc > > > > > > > > > Am Dienstag, 31. Juli 2007 19:16 schrieb Dave Tapley: > > > > Hi everyone, I have the following skeleton GLUT code: > > > > > > > > > import Graphics.UI.GLUT > > > > > main = do > > > > > getArgsAndInitialize > > > > > createWindow "" > > > > > mainLoop > > > > > > > > It loads into both hugs and ghci fine and when 'main' is evaluated an > > > > empty window opens as expected. > > > > However when closing the window (clicking the window manager's x > > > > button) both hugs and ghci exit with the window, as opposed to > > > > returning to the the 'Main>' prompt. > > > > > > > > I suspect I need some callback to exit the GUI cleanly? > > > > > > > > Cheers, > > > > Dave > > > > _______________________________________________ > > > > Haskell-Cafe mailing list > > > > Haskell-Cafe@haskell.org > > > > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > > > > > > > > > > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From simonpj at microsoft.com Thu Aug 2 12:51:43 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Thu Aug 2 12:44:02 2007 Subject: [Haskell-cafe] Re: how to see operators precedence in GHCi In-Reply-To: <20070726000034.GA5201@localhost.localdomain> References: <163915359.20070725193617@gmail.com> <363931575.20070725213538@gmail.com> <20070725175556.GA3505@localhost.localdomain> <20070725180102.GA3541@localhost.localdomain> <20070726000034.GA5201@localhost.localdomain> Message-ID: Hmm. Good point. Fixed. Smion | -----Original Message----- | From: Stefan O'Rear [mailto:stefanor@cox.net] | Sent: 26 July 2007 01:01 | To: Simon Peyton-Jones | Cc: Bulat Ziganshin; haskell-cafe@haskell.org; Jon Fairbairn | Subject: Re: [Haskell-cafe] Re: how to see operators precedence in GHCi | | On Thu, Jul 26, 2007 at 12:42:52AM +0100, Simon Peyton-Jones wrote: | > | > | Uhm... that didn't work :) | > | | > | Not quite as nice: | > | | > | stefan@stefans:~$ ghci -ddump-rn-trace | > | > You probably wanted -ddump-rn | | Seemed so, but that option has no effect (bug?): | | stefan@stefans:~$ ghci -ddump-rn | GHCi, version 6.7.20070712: http://www.haskell.org/ghc/ :? for help | Loading package base ... linking ... done. | Prelude> 2 + 2 | 4 | Prelude> | | Stefan From duncan.coutts at worc.ox.ac.uk Thu Aug 2 12:56:44 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Thu Aug 2 12:47:52 2007 Subject: [Haskell-cafe] Re: [Haskell] ANN: encoding-0.1 release In-Reply-To: <200708021844.40272.g9ks157k@acme.softbase.org> References: <1186050176.5778.27.camel@pandemonium.gnet> <200708021844.40272.g9ks157k@acme.softbase.org> Message-ID: <1186073804.5989.189.camel@localhost> On Thu, 2007-08-02 at 18:44 +0200, Wolfgang Jeltsch wrote: > Am Donnerstag, 2. August 2007 12:22 schrieb Henning G?nther: > > [?] > > > ISO 8859-* (alias latin-*) > > Not every ISO-8859-* encoding is a Latin-* encoding. > > > [?] > > Wouldn?t it be good to use some already existing library like iconv or do you > think, this is not feasible (because you want to support lazyness, for > example)? Yes, I was talking to Henning about this. I've got an iconv binding[1] that use lazy bytestrings (so it does support lazyness of course) and is pretty quick. Henning has been thinking much more about what the appropriate api should be, I've just got: type Encoding = String convert :: Encoding -> Encoding -> Lazy.ByteString -> Lazy.ByteString so we might be able to use iconv underneath (if it's available). Duncan [1] darcs get http://haskell.org/~duncan/iconv/ From alexteslin at yahoo.co.uk Thu Aug 2 13:33:59 2007 From: alexteslin at yahoo.co.uk (Alexteslin) Date: Thu Aug 2 13:26:15 2007 Subject: [Haskell-cafe] Primitive Recursive Algebraic Types Message-ID: <11969026.post@talk.nabble.com> Hi, I am doing some simple exercises about recursive algebraic types and this particular exercise asks to define a function which counts the number of operators in an expression. I defined the function below, but i am not sure if on the second line changing from "evalLength (Lit n) = n" to "(Lit n) = 0" is the right solution. although the function produces correct result. data Expr = Lit Int | Add Expr Expr | Sub Expr Expr deriving (Eq, Show) evalLength :: Expr -> Int evalLength (Lit n) = 0 evalLength (Add e1 e2) = 1 + (evalLength e1) + (evalLength e2) evalLength (Sub e1 e2) = 1 + (evalLength e1) - (evalLength e2) Thank you -- View this message in context: http://www.nabble.com/Primitive-Recursive-Algebraic-Types-tf4207521.html#a11969026 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From jon at ffconsultancy.com Thu Aug 2 13:32:33 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu Aug 2 13:33:49 2007 Subject: [Haskell-cafe] Polymorphic variants In-Reply-To: <8dde104f0707251607i14400bc7y338e4dc20796387@mail.gmail.com> References: <200707252304.17136.jon@ffconsultancy.com> <8dde104f0707251607i14400bc7y338e4dc20796387@mail.gmail.com> Message-ID: <200708021832.33331.jon@ffconsultancy.com> On Thursday 26 July 2007 00:07:23 Josef Svenningsson wrote: > On 7/26/07, Jon Harrop wrote: > > Does Haskell have anything similar to OCaml's polymorphic variants? > > No as such, but it's possible to simulate them. As always Oleg was the > one to demonstrate how: > http://okmij.org/ftp/Haskell/generics.html Thank you. Is there any interest in adding polymorphic variants to Haskell? I think it is fair to say that OCaml has shown them to be an extremely useful construct (more common than objects in OCaml, for example). -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/?e From dan.doel at gmail.com Thu Aug 2 14:18:40 2007 From: dan.doel at gmail.com (Dan Doel) Date: Thu Aug 2 14:06:34 2007 Subject: [Haskell-cafe] Polymorphic variants In-Reply-To: <200708021832.33331.jon@ffconsultancy.com> References: <200707252304.17136.jon@ffconsultancy.com> <8dde104f0707251607i14400bc7y338e4dc20796387@mail.gmail.com> <200708021832.33331.jon@ffconsultancy.com> Message-ID: <200708021418.40858.dan.doel@gmail.com> On Thursday 02 August 2007, Jon Harrop wrote: > On Thursday 26 July 2007 00:07:23 Josef Svenningsson wrote: > > On 7/26/07, Jon Harrop wrote: > > > Does Haskell have anything similar to OCaml's polymorphic variants? > > > > No as such, but it's possible to simulate them. As always Oleg was the > > one to demonstrate how: > > http://okmij.org/ftp/Haskell/generics.html > > Thank you. > > Is there any interest in adding polymorphic variants to Haskell? I think it > is fair to say that OCaml has shown them to be an extremely useful > construct (more common than objects in OCaml, for example). I think this topic goes along with the oft-discussed issue of what should be done about Haskell's record system. Several of the papers in that area use row polymorphism for typing extensible records, and the same thing can be used for typing polymorphic variants. Unfortunately, I guess it's hard to get everyone nailed down on what exactly the right solution is (and I guess there are also people who aren't interested in scrapping the existing record system), so not much has been done outside proposals. To my knowledge, no one has gone as far as implementing the proposals yet (which is a requirement for getting into Haskell', if that matters), although Hugs reportedly has a record system extension that inspired the newer proposals to some extent (I haven't used it myself). -- Dan P.S.: Some papers: http://www.cse.ogi.edu/PacSoft/publications/2000/extensiblerecords.pdf http://research.microsoft.com/users/daan/download/papers/scopedlabels.pdf The second actually discusses all the operations on variants and whatnot. The first just mentions that it's a related topic. From alexteslin at yahoo.co.uk Thu Aug 2 14:15:01 2007 From: alexteslin at yahoo.co.uk (Alexteslin) Date: Thu Aug 2 14:07:17 2007 Subject: [Haskell-cafe] Primitive Recursive Algebraic Types In-Reply-To: <11969026.post@talk.nabble.com> References: <11969026.post@talk.nabble.com> Message-ID: <11969804.post@talk.nabble.com> Alexteslin wrote: > > Hi, I am doing some simple exercises about recursive algebraic types and > this particular exercise asks to define a function which counts the number > of operators in an expression. I defined the function below, but i am not > sure if on the second line changing from "evalLength (Lit n) = n" to "(Lit > n) = 0" is the right solution. although the function produces correct > result. > > data Expr = Lit Int | Add Expr Expr | > Sub Expr Expr > deriving (Eq, Show) > > evalLength :: Expr -> Int > evalLength (Lit n) = 0 > evalLength (Add e1 e2) = 1 + (evalLength e1) + (evalLength e2) > evalLength (Sub e1 e2) = 1 + (evalLength e1) - (evalLength e2) > > > Thank you > It actually doesn't work. Initially i tested on Add operator only. But whith Sub operator it produces wrong result. -- View this message in context: http://www.nabble.com/Primitive-Recursive-Algebraic-Types-tf4207521.html#a11969804 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From jon at ffconsultancy.com Thu Aug 2 15:02:14 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu Aug 2 15:03:26 2007 Subject: [Haskell-cafe] Perfect example Message-ID: <200708022002.14755.jon@ffconsultancy.com> Any suggestions for a perfect example that uniquely demonstrates the benefits of the Haskell language compared to other languages? -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/?e From clawsie at fastmail.fm Thu Aug 2 15:17:06 2007 From: clawsie at fastmail.fm (brad clawsie) Date: Thu Aug 2 15:09:27 2007 Subject: [Haskell-cafe] positive Int Message-ID: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> as far as i know, the haskell standard does not define a basic Int type that is limited to positive numbers. would a type of this kind not potentially allow us to make stronger verification statements about certain functions? for example, 'length' returns an Int, but in reality it must always return a value 0 or greater. a potential counter-argument would be the need to possibly redefine Ord etc for this more narrow type... From clawsie at fastmail.fm Thu Aug 2 15:29:46 2007 From: clawsie at fastmail.fm (brad clawsie) Date: Thu Aug 2 15:22:07 2007 Subject: [Haskell-cafe] positive Int In-Reply-To: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> References: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> Message-ID: <20070802192946.GF62676@jobbicycle.corp.yahoo.com> On Thu, Aug 02, 2007 at 12:17:06PM -0700, brad clawsie wrote: > as far as i know, the haskell standard does not define a basic Int > type that is limited to positive numbers. > > would a type of this kind not potentially allow us to make stronger > verification statements about certain functions? > > for example, 'length' returns an Int, but in reality it must always > return a value 0 or greater. a potential counter-argument would be the > need to possibly redefine Ord etc for this more narrow type... i suppose one could also say that the range [0..] of return values is *implicit* in the function definition, so there is little value in explicitly typing it given all of the hassle of specifying a new typeclass etc sorry, yes i am talking to myself From cdsmith at twu.net Thu Aug 2 15:39:36 2007 From: cdsmith at twu.net (Chris Smith) Date: Thu Aug 2 15:33:36 2007 Subject: [Haskell-cafe] monad subexpressions Message-ID: I've heard Simon (Peyton-Jones) twice now mention the desire to be able to embed a monadic subexpression into a monad. That would be http://article.gmane.org/gmane.comp.lang.haskell.prime/2267 and in the recent OSCON video. Is someone working on implementing this? If no, I'll take a crack at it. If yes, I'd be slower than someone else, since I'm new to GHC. This seems like something a tad easier than type system extensions and the like since it's just desugaring... but a little harder than my "remove the GHCi banner" patch! In other words, a perfect step for me. Also, I got so frustrated that I ended up abandoning some code recently because STM is, in the end, so darn hard to use as a result of this issue. I'd love to see this solved, and I'm quite eager to do it. Proposals for syntax I've seen include: $( expr ) -- conflicts with template haskell ( <- expr ) -- makes sense, and I think it's unambiguous Other ideas: ``expr`` -- back-ticks make sense for UNIX shell scripters (| expr |) -- I don't think anything uses this yet Thoughts? -- Chris Smith From bjorn.buckwalter at gmail.com Thu Aug 2 16:27:47 2007 From: bjorn.buckwalter at gmail.com (=?ISO-8859-1?Q?Bj=F6rn_Buckwalter?=) Date: Thu Aug 2 16:20:03 2007 Subject: [Haskell-cafe] ANNOUNCE: Dimensional 0.6 -- Statically checked physical dimensions Message-ID: <8b2a1a960708021327u39dc798dga71913c40553def5@mail.gmail.com> Dear all, I am pleased to announce version 0.6 of the Dimensional library. Dimensional is a library providing data types for performing arithmetic with physical quantities and units. Information about the physical dimensions of the quantities/units is embedded in their types and the validity of operations is verified by the type checker at compile time. The boxing and unboxing of numerical values as quantities is done by multiplication and division with units. The library is designed to, as far as is practical, enforce/encourage best practices [1] of unit usage. Noteworthy changes/additions since the previous formal announcement (version 0.4) are: - All quantities and SI units from [1] have been added. - A Prelude replacement with the SI units and dimensional operators (+, *, ^...) is provided for convenience. - Interface to Data.Time using 'fromDiffTime' and 'toDiffTime'. - Phantom type tags make extended dimensions safer. - Experimental CGS units with type safe conversions to/from SI. See appended literate Haskell module for details. Additional information and code is available from the project web site [3]. Thank you, Bjorn Buckwalter [1] http://physics.nist.gov/Pubs/SP811/ [2] http://www.haskell.org/pipermail/haskell/2007-May/019496.html [3] http://code.google.com/p/dimensional/ ~~~~~~~~~~ BEGIN 'Buckwalter/Dimensional/CGS.lhs' ~~~~~~~~~~ Buckwalter.Dimensional.CGS -- CGS system of units Bjorn Buckwalter, bjorn.buckwalter@gmail.com License: BSD3 *** EXPERIMENTAL *** = Introduction = This module was prompted by an email from Chuck Blake[1]. He asked if the Dimensional library could support other systems of units than SI, in particular systems such as the centimeter-gram-second (CGS) system where fractional exponents of dimensions occur. He also wondered whether it was possible to convert quantities between different systems while statically ensuring that a given conversion was valid. In this module we show that we can in a straight forward manner support systems with rational exponents, provided that the rationals that may be encountered are known a priori. As an example we provide a rudimentary implementation of the CGS system. We also show that we can indeed statically prohibit invalid conversions between different systems. = Caveats = I'm ignorantly assuming that when working with the CGS (or MKS) system you will only (meaningfully?) encounter half-exponents and only of the length and mass dimensions. Of course, in other systems other rational exponents may be encountered. I am also assuming that the CGS system would not be employed when working with temperature, amount or luminosity. This is evident in the below type signatures where I have assumed zero extent in the temperature, amount and luminosity dimensions. If this is incorrect I would appreciate pointers to the CGS representation of these dimensions. Please correct and inform me if my assumptions are wrong! = Preliminaries = > {-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances #-} > module Buckwalter.Dimensional.CGS where > import Prelude ( undefined, Num, Fractional, Floating, Show, recip, Double ) > import qualified Prelude > import Buckwalter.Dimensional hiding ( DLength, DMass, DTime, DElectricCurrent ) > import Buckwalter.Dimensional.Quantities as SIQ > import qualified Buckwalter.Dimensional.SIUnits as SI > import qualified Buckwalter.NumType as N > import Buckwalter.NumType ( Neg2, Neg1, Zero, Pos, Pos1, Pos2, Pos3, NumType ) > import Buckwalter.NumType ( neg2, neg1, zero, pos1, pos2, pos3 ) > import Data.Maybe (catMaybes) = Dimensions = Analogously with the SI we collect the base dimensions of the CGS system in the data type 'CGSDim'. > data CGSDim lh mh t In the above 'lh' and 'mh' represent the number of half-exponents of length and mass respectively while 't' represents the number of whole-exponents. The base dimensions illustrate this. > type DLength = CGSDim Pos2 Zero Zero > type DMass = CGSDim Zero Pos2 Zero > type DTime = CGSDim Zero Zero Pos1 We add a few non-base dimensions for the sake of example. Charge is particularly interesting as it illustrates the need for half-exponents as described in [2]. > type DElectricCurrent = CGSDim Pos3 Pos1 Neg2 > type DCharge = CGSDim Pos3 Pos1 Neg1 = 'Mul', 'Div', 'Pow' and 'Root' instances = The 'Mul', 'Div', 'Pow' and 'Root' instances are strictly analogous with the SI. > instance ( N.Sum lh lh' lh'' > , N.Sum mh mh' mh'' > , N.Sum t t' t'' ) => Mul (CGSDim lh mh t) > (CGSDim lh' mh' t') > (CGSDim lh'' mh'' t'') > instance ( N.Sum lh lh' lh'' > , N.Sum mh mh' mh'' > , N.Sum t t' t'' ) => Div (CGSDim lh'' mh'' t'') > (CGSDim lh' mh' t') > (CGSDim lh mh t) > instance ( N.Mul lh x lh' > , N.Mul mh x mh' > , N.Mul t x t' ) => Pow (CGSDim lh mh t) x > (CGSDim lh' mh' t') > instance ( N.Div lh x lh' > , N.Div mh x mh' > , N.Div t x t' ) => Root (CGSDim lh mh t) x > (CGSDim lh' mh' t') = Units = We define the base units of the system. By defining 'meter' with a "scale" of 100 we get a scale of one for 'centi meter'. > meter :: Num a => Unit DLength a > meter = Dimensional 100 > gram :: Num a => Unit DMass a > gram = Dimensional 1 > second :: Num a => Unit DTime a > second = Dimensional 1 We continue by defining the CGS equivalents of the other base SI units. Actually we limit ourselves to 'ampere' since I am not sure if or how the SI base dimensions other than current are expressed in CGS. > ampere :: Floating a => Unit DElectricCurrent a > ampere = prefix (recip 3.33564e-10) ((SI.centi meter ^ pos3) ^/ pos2 * gram ^/ pos2 * second ^ neg2) We also define the preferred CGS unit for charge. > franklin :: Floating a => Unit DCharge a -- Also known as "esu". > franklin = gram ^/ pos2 * (SI.centi meter ^ pos3) ^/ pos2 / second = Conversion from SI = At some point we may wish to convert an SI quantity to a CGS quantity or vice versa. In order to convert a 'Quantity' from the SI system to the CGS system we use the strategy of dividing the quantity by the SI base unit and multiplying the resulting number (sans dimension) by the equivalent CGS unit. To realize this strategy we must be able to obtain the SI base unit and the equivalent CGS unit for a given quantity. We start with the SI unit since it is trivial. > unit_SI :: Num a => Quantity (Dim l m t i th n j) a -> Unit (Dim l m t i th n j) a > unit_SI _ = Dimensional 1 (Perhaps the above function would be better defined in another module.) Obtaining the CGS unit corresponding to the SI base unit of a Quantity isn't quite as trivial. The function body itself is straight-forward enough, the hairy part is the type signature. > unit_CGS :: forall a l m t i l2 m2 il it l' m' t'. > ( Floating a > , N.Mul Zero l Zero, N.Mul Pos2 l l2 > , N.Mul Zero m Zero, N.Mul Pos2 m m2 > , N.Mul Zero t Zero, N.Mul Pos1 t t > , N.Sum l2 Zero l2 > , N.Sum Zero m2 m2, N.Sum m2 Zero m2 > , N.Sum Zero t t > , N.Mul Pos3 i il > , N.Mul Pos1 i i > , N.Mul Neg2 i it > , N.Sum l2 il l' > , N.Sum m2 i m' > , N.Sum t it t' > ) => Quantity (Dim l m t i Zero Zero Zero) a -> Unit (CGSDim l' m' t') a > unit_CGS _ = meter ^ (undefined :: l) > * SI.kilo gram ^ (undefined :: m) > * second ^ (undefined :: t) > * ampere ^ (undefined :: i) Note that since the base dimensions of the CGS are a subset of those of the SI the mapping of types from SI to CGS is unambiguous. Also note that complex as the type signature may be producing it is a mostly mechanical process. With the above two functions we can define the function that converts a unit from the SI. We omit the type signature since it is hairy but can be readily inferred. > fromSI x = x /~ unit_SI x *~ unit_CGS x = Conversion to SI = We use the same strategy to convert from CGS to SI. However, when converting from CGS to SI there may be several valid SI dimensionalities for any given CGS dimensionality. We will handle this ambiguity by requiring the user to specify the desired type (except when it is inferable) of the resulting quantity. For example: ] toSI (3.2 *~ centi meter) :: Length Double In order to do this we must employ lexically scoped type variables and provide the hairy type signature for the 'toSI' function. > toSI :: forall a l m t i l2 m2 il it l' m' t'. > ( Floating a > , N.Mul Zero l Zero, N.Mul Pos2 l l2 > , N.Mul Zero m Zero, N.Mul Pos2 m m2 > , N.Mul Zero t Zero, N.Mul Pos1 t t > , N.Sum l2 Zero l2 > , N.Sum Zero m2 m2, N.Sum m2 Zero m2 > , N.Sum Zero t t > , N.Mul Pos3 i il > , N.Mul Pos1 i i > , N.Mul Neg2 i it > , N.Sum l2 il l' > , N.Sum m2 i m' > , N.Sum t it t' > ) => Quantity (CGSDim l' m' t') a -> Quantity (Dim l m t i Zero Zero Zero) a > toSI x = x /~ unit_CGS (undefined :: Quantity (Dim l m t i Zero Zero Zero) a) > *~ unit_SI (undefined :: Quantity (Dim l m t i Zero Zero Zero) a) Again, the type signature is complex but deriving it is a mechanical process. = 'Show' instance = We round off by writing 'Show' instance for 'CGSDim' analogous to that of 'Dim'. Out of laziness we use the notation "sqrt(cm)" to represent halves of integral dimensions. Nothing is technically keeping us from doing a better job here. > instance forall lh mh t. > ( NumType lh > , NumType mh > , NumType t > ) => Show (CGSDim lh mh t) where > show _ = (Prelude.unwords Prelude.. catMaybes) > [ dimUnit "sqrt(cm)" (undefined :: lh) > , dimUnit "sqrt(g)" (undefined :: mh) > , dimUnit "s" (undefined :: t) > ] = Examples = Let us try the Coulomb attraction example from [2]. We start by performing the calculation in the SI. > q_si = 1.6021773e-19 *~ SI.coulomb -- Elementary charge in SI. > r_si = 0.1 *~ SI.nano SI.meter -- Distance in SI > f_si = q_si ^ pos2 / (_4 * pi * e0 * r_si ^ pos2) > where > e0 = 8.8541878e-12 *~ (SI.ampere * SI.second / (SI.volt * SI.meter)) The same calculation in the CGS system. > q_cgs = fromSI q_si -- Elementary charge in CGS. > r_cgs = fromSI r_si -- Distance in CGS > f_cgs = q_cgs ^ pos2 / r_cgs ^ pos2 Inspecting the values in GHCi shows us that the results are consistent (within reasonable accuracy) with [2]. *Buckwalter.Dimensional.CGS> f_si 2.3070794737101255e-8 m kg s^-2 *Buckwalter.Dimensional.CGS> f_cgs 2.30708078598602e-3 sqrt(cm)^2 sqrt(g)^2 s^-2 To convert from CGS to SI we must specify the type of the SI 'Quantity'. > f_si' = toSI f_cgs :: SIQ.Force Double *Buckwalter.Dimensional.CGS> f_si' 2.3070807859860202e-8 m kg s^-2 We follow up with another conversion example demonstrating the ambiguity in the conversion from CGS to SI. > c = 1 *~ SI.farad -- A SI capacitance. > c_cgs = fromSI c -- Capacitance has dimensionality L in CGS. > c' = toSI c_cgs :: SIQ.Capacitance Double > c'' = toSI c_cgs :: Length Double *Buckwalter.Dimensional.CGS> c 1.0 m^-2 kg^-1 s^4 A^2 *Buckwalter.Dimensional.CGS> c_cgs 8.98755691740885e11 sqrt(cm)^2 *Buckwalter.Dimensional.CGS> c' 1.0 m^-2 kg^-1 s^4 A^2 *Buckwalter.Dimensional.CGS> c'' 8.98755691740885e9 m = Future work = This is a very rudimentary implementation. To make it more practical a significant number of quantities and units, in particularly those commonly used with the CGS, would need to be added. In the mean time all units defined for the SI can be used with the CGS by applying 'fromSI' to quantities defined from the SI units. If anyone is willing to add quantities/units (or other enhancements) I will happily to accept patches. Personally I do not expect to use this module and therefore do not intend to invest much more time in it. If the module has other users I might reconsider. And of course, another direction of future work is to define additional systems (e.g. natural, relativistic) using this module as a template. I imagine this should be fairly straight forward. = References = [1] http://code.google.com/p/dimensional/wiki/ChuckBlake20070611 [2] http://www.tf.uni-kiel.de/matwis/amat/mw1_ge/kap_2/basics/b2_1_14.html ~~~~~~~~~~ END 'Buckwalter/Dimensional/CGS.lhs' ~~~~~~~~~~ From westondan at imageworks.com Thu Aug 2 16:19:13 2007 From: westondan at imageworks.com (Dan Weston) Date: Thu Aug 2 16:46:10 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <319884CC-F3F6-4652-8BBF-20DDC029399D@cs.otago.ac.nz> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <319884CC-F3F6-4652-8BBF-20DDC029399D@cs.otago.ac.nz> Message-ID: <46B23C41.2000305@imageworks.com> Ok, I am guessing that if you were Neo in The Matrix, you would have taken the Blue Pill. Blue Pill people ask How. I suspect most people attracted to Haskell have already taken the Red Pill. Red Pill people ask Why. It is compulsion, not self-interest, that drives Red Pill people to look under the hood of their programming language. If you are a Blue Pill person, you will never understand. If you were a Red Pill person, you would never have written the following paragraph. ok wrote: > If you've read the Science of Discworld books you will be familiar with the > phrase 'lies-to-children'. You DON'T tell them the full truth, because it > would take a long time, confuse the marrow out of their bones, and leave > them feeling this was masturbatory mathematics, not real programming, > having no connection with real world interests. Your students can choose for themselves whether to take the Blue Pill or Red Pill. The least you can do is offer them the choice. Dan From droundy at darcs.net Thu Aug 2 17:08:33 2007 From: droundy at darcs.net (David Roundy) Date: Thu Aug 2 17:00:51 2007 Subject: [Haskell-cafe] positive Int In-Reply-To: <20070802192946.GF62676@jobbicycle.corp.yahoo.com> References: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> <20070802192946.GF62676@jobbicycle.corp.yahoo.com> Message-ID: <20070802210832.GD11377@darcs.net> On Thu, Aug 02, 2007 at 12:29:46PM -0700, brad clawsie wrote: > On Thu, Aug 02, 2007 at 12:17:06PM -0700, brad clawsie wrote: > > as far as i know, the haskell standard does not define a basic Int > > type that is limited to positive numbers. > > > > would a type of this kind not potentially allow us to make stronger > > verification statements about certain functions? > > > > for example, 'length' returns an Int, but in reality it must always > > return a value 0 or greater. a potential counter-argument would be the > > need to possibly redefine Ord etc for this more narrow type... > > i suppose one could also say that the range [0..] of return values is > *implicit* in the function definition, so there is little value in > explicitly typing it given all of the hassle of specifying a new > typeclass etc This would be a very nice type to have (natural numbers), but is a tricky type to work with. Subtraction, for instance, wouldn't be possible as a complete function... or one might say that if you included subtraction you're even less safe: negative results either must throw an exception or be impossible to catch. You might point out that overflow in an Int is similar (uncatchable), but overflow is much harder to accidentally run into than negative values. A nicer option would be some sort of "extra" proof rather than a new type. But that sort of work is rather tricky, as I understand it. -- David Roundy Department of Physics Oregon State University From mvanier at cs.caltech.edu Thu Aug 2 17:13:00 2007 From: mvanier at cs.caltech.edu (Michael Vanier) Date: Thu Aug 2 17:05:36 2007 Subject: [Haskell-cafe] positive Int In-Reply-To: <20070802210832.GD11377@darcs.net> References: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> <20070802192946.GF62676@jobbicycle.corp.yahoo.com> <20070802210832.GD11377@darcs.net> Message-ID: <46B248DC.1080705@cs.caltech.edu> Of course, you can always do this: data Nat = Zero | Succ Nat but it's not very much fun to work with, and not very efficient. Mike David Roundy wrote: > On Thu, Aug 02, 2007 at 12:29:46PM -0700, brad clawsie wrote: >> On Thu, Aug 02, 2007 at 12:17:06PM -0700, brad clawsie wrote: >>> as far as i know, the haskell standard does not define a basic Int >>> type that is limited to positive numbers. >>> >>> would a type of this kind not potentially allow us to make stronger >>> verification statements about certain functions? >>> >>> for example, 'length' returns an Int, but in reality it must always >>> return a value 0 or greater. a potential counter-argument would be the >>> need to possibly redefine Ord etc for this more narrow type... >> i suppose one could also say that the range [0..] of return values is >> *implicit* in the function definition, so there is little value in >> explicitly typing it given all of the hassle of specifying a new >> typeclass etc > > This would be a very nice type to have (natural numbers), but is a tricky > type to work with. Subtraction, for instance, wouldn't be possible as a > complete function... or one might say that if you included subtraction > you're even less safe: negative results either must throw an exception or > be impossible to catch. You might point out that overflow in an Int is > similar (uncatchable), but overflow is much harder to accidentally run into > than negative values. > > A nicer option would be some sort of "extra" proof rather than a new type. > But that sort of work is rather tricky, as I understand it. From nicolas.frisby at gmail.com Thu Aug 2 17:16:28 2007 From: nicolas.frisby at gmail.com (Nicolas Frisby) Date: Thu Aug 2 17:08:45 2007 Subject: [Haskell-cafe] Primitive Recursive Algebraic Types In-Reply-To: <11969804.post@talk.nabble.com> References: <11969026.post@talk.nabble.com> <11969804.post@talk.nabble.com> Message-ID: <5ce89fb50708021416l505b42d8w2fb609b2f55010fb@mail.gmail.com> It seems you are confusing the notion of counting the number of operators in the expression with actually evaluating the expression. Your evalLength function does both. It may help to consider counting the number of operators in the expression to be the same as calculating the height of the syntax tree representing the expression. This is why when we are counting the operators in the expression, there is no need to distinguish Add and Sub; they are both just operators for this analysis and their different semantics are not yet a concern. The "countOperators" function need not distinguish between Add and Sub since we're not yet evaluating. Similarly, a literal is not an operator; the integer it contains is a value, not an operator. In this case the type Int is being used for two different reasons; you'll need to be able recognize it when this happens. Here's the correct version; you were quite close! In terms of types and recursive structure, you had it correct. By separating "counting operators" from evaluation, I think you'll clearly see the reasons for the definition. countOperators :: Expr -> Int countOperators = heightOfTree heightOfTree (Lit n) = 0 heightOfTree (Add e1 e2) = 1 + (heightOfTree e1) + (heightOfTree e2) heightOfTree (Sub e1 e2) = 1 + (heightOfTree e1) + (heightOfTree e2) On 8/2/07, Alexteslin wrote: > > > > Alexteslin wrote: > > > > Hi, I am doing some simple exercises about recursive algebraic types and > > this particular exercise asks to define a function which counts the number > > of operators in an expression. I defined the function below, but i am not > > sure if on the second line changing from "evalLength (Lit n) = n" to "(Lit > > n) = 0" is the right solution. although the function produces correct > > result. > > > > data Expr = Lit Int | Add Expr Expr | > > Sub Expr Expr > > deriving (Eq, Show) > > > > evalLength :: Expr -> Int > > evalLength (Lit n) = 0 > > evalLength (Add e1 e2) = 1 + (evalLength e1) + (evalLength e2) > > evalLength (Sub e1 e2) = 1 + (evalLength e1) - (evalLength e2) > > > > > > Thank you > > > > > It actually doesn't work. Initially i tested on Add operator only. But > whith Sub operator it produces wrong result. > -- > View this message in context: http://www.nabble.com/Primitive-Recursive-Algebraic-Types-tf4207521.html#a11969804 > Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From la at iki.fi Thu Aug 2 17:25:19 2007 From: la at iki.fi (Lauri Alanko) Date: Thu Aug 2 17:17:36 2007 Subject: [Haskell-cafe] positive Int In-Reply-To: <20070802210832.GD11377@darcs.net> References: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> <20070802192946.GF62676@jobbicycle.corp.yahoo.com> <20070802210832.GD11377@darcs.net> Message-ID: <20070802212519.GA25277@cs.helsinki.fi> On Thu, Aug 02, 2007 at 02:08:33PM -0700, David Roundy wrote: > This would be a very nice type to have (natural numbers), but is a tricky > type to work with. Subtraction, for instance, wouldn't be possible as a > complete function... Of course it would. It would just have the type Nat -> Nat -> Integer. This of course means that Nat wouldn't be an instance of Num. Tough luck, and one more reason for more fine-grained algebraic class hierarchy: Nat would be a semiring (as would booleans and finite sets and regular expressions and whatnot). Lauri From droundy at darcs.net Thu Aug 2 17:44:43 2007 From: droundy at darcs.net (David Roundy) Date: Thu Aug 2 17:37:00 2007 Subject: [Haskell-cafe] ANNOUNCE: Dimensional 0.6 -- Statically checked physical dimensions In-Reply-To: <8b2a1a960708021327u39dc798dga71913c40553def5@mail.gmail.com> References: <8b2a1a960708021327u39dc798dga71913c40553def5@mail.gmail.com> Message-ID: <20070802214443.GE11377@darcs.net> On Thu, Aug 02, 2007 at 10:27:47PM +0200, Bj?rn Buckwalter wrote: > I am also assuming that the CGS system would not be employed when > working with temperature, amount or luminosity. This is evident in > the below type signatures where I have assumed zero extent in the > temperature, amount and luminosity dimensions. If this is incorrect > I would appreciate pointers to the CGS representation of these > dimensions. > > Please correct and inform me if my assumptions are wrong! The temperature units are the same in CGS as in MKS (Kelvin). > This is a very rudimentary implementation. To make it more practical > a significant number of quantities and units, in particularly those > commonly used with the CGS, would need to be added. In the mean > time all units defined for the SI can be used with the CGS by > applying 'fromSI' to quantities defined from the SI units. > > If anyone is willing to add quantities/units (or other enhancements) > I will happily to accept patches. Personally I do not expect to use > this module and therefore do not intend to invest much more time > in it. If the module has other users I might reconsider. > > And of course, another direction of future work is to define > additional systems (e.g. natural, relativistic) using this module > as a template. I imagine this should be fairly straight forward. When atomic units are implemented, this could be useful for me... but alas I very seldom use Haskell for physics, and the effort to learn these modules seems unlikely to pay off soon. :( -- David Roundy Department of Physics Oregon State University From drl at cs.cmu.edu Thu Aug 2 17:53:13 2007 From: drl at cs.cmu.edu (Dan Licata) Date: Thu Aug 2 17:46:03 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: References: Message-ID: <20070802215313.GA27205@cs.cmu.edu> Hi Chris, Simon mentioned this to me as a possible project when I started my internship here at MSR, so I'm pretty sure this is both on the wish-list and not already taken (but we should check with Simon to make sure). I've since wished for it a few times as I've been implementing view patterns, so I personally think it would be a great thing for you to implement! If you're interested in doing this, I'd be happy to give you an overview of what pieces of GHC you'll need to touch and to answer your questions (as best I can!) as you work on the implementation. I've gotten to know the front end of GHC a little over the past few weeks. Let me know, -Dan On Aug02, Chris Smith wrote: > I've heard Simon (Peyton-Jones) twice now mention the desire to be able > to embed a monadic subexpression into a monad. That would be > http://article.gmane.org/gmane.comp.lang.haskell.prime/2267 and in the > recent OSCON video. Is someone working on implementing this? > > If no, I'll take a crack at it. > If yes, I'd be slower than someone else, since I'm new to GHC. > > This seems like something a tad easier than type system extensions and > the like since it's just desugaring... but a little harder than my > "remove the GHCi banner" patch! In other words, a perfect step for me. > Also, I got so frustrated that I ended up abandoning some code recently > because STM is, in the end, so darn hard to use as a result of this > issue. I'd love to see this solved, and I'm quite eager to do it. > > Proposals for syntax I've seen include: > > $( expr ) -- conflicts with template haskell > ( <- expr ) -- makes sense, and I think it's unambiguous > > Other ideas: > > ``expr`` -- back-ticks make sense for UNIX shell scripters > (| expr |) -- I don't think anything uses this yet > > Thoughts? > From igloo at earth.li Thu Aug 2 18:07:29 2007 From: igloo at earth.li (Ian Lynagh) Date: Thu Aug 2 17:59:48 2007 Subject: [Haskell-cafe] positive Int In-Reply-To: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> References: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> Message-ID: <20070802220729.GA31392@matrix.chaos.earth.li> On Thu, Aug 02, 2007 at 12:17:06PM -0700, brad clawsie wrote: > as far as i know, the haskell standard does not define a basic Int > type that is limited to positive numbers. Haskell 98 doesn't have such a type, no, but in today's libraries there is Data.Word.Word. Operations like subtraction will just wrap around when they would otherwise go negative, though ("All arithmetic is performed modulo 2^n"). > for example, 'length' returns an Int, but in reality it must always > return a value 0 or greater. a potential counter-argument would be the > need to possibly redefine Ord etc for this more narrow type... The main worry I can see with doing that is, would you need to keep explicitly converting between Int and Word? It might be possible to convert enough things to Word that it doesn't matter. You'd also break lots of programs, of course. Thanks Ian From ok at cs.otago.ac.nz Thu Aug 2 19:02:53 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 2 18:55:15 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative In-Reply-To: <5de3f5ca0708020005o27974426g2038f68512447be3@mail.gmail.com> References: <5de3f5ca0708020005o27974426g2038f68512447be3@mail.gmail.com> Message-ID: I wrote: But please, let's keep one foot in the real world if possible. Monads were invented to solve the "how do I do imperative programming in a pure functional language" problem. On 2 Aug 2007, at 7:05 pm, Greg Meredith wrote: > This is more than a little revisionist. Monads have been the > subject of mathematical study before people had an inkling that > they might apply to problems in computer science. Moggi didn't > invent them, but noticed that they might have an application to > issues of composition in computation. It is really intriguing that > they do such a remarkable job of organizing notions of update and > were not invented with this application in mind. So, revising > history thus would be a real loss. I apologise for the unclarity of what I wrote. I should have said something like "Monads-in-computing were adopted to solve..." It is considerably more than a little revisionist to identify Haskell monads with Category Theory monads. Quoting the Wikipedia article on monads: "If F and G are a pair of adjoint functors, with F left adjoint to G, then the composition G o F will be a monad. Note that therefore a monad is a functor from a category to itself; and that if F and G were actually inverses as functors the corresponding monad would be the identity functor." So a category theory monad is a functor from some category to itself. How is IO a a functor? Which category does it operate on? What does it do to the points of that category? What does it do to the arrows? Let's turn to the formal definition: "If C is a category, a monad on C consists of a functor T : C ? C together with two natural transformations: ? : 1 ? T (where 1 denotes the identity functor on C) and ? : T2 ? T (where T2 is the functor T o T from C to C). These are required to fulfill [some] axioms:" What are the natural transformations for the IO monad? I suppose there is a vague parallel to return and >>=, but that's about all you can claim for it. If we are not to be revisionist, then we must admit that Haskell monads were *inspired* by category theory monads, but went through a couple of rounds of change of notation before becoming the Monad class we know and love today. What we have *was* invented for functional programming and its category theory roots are not only useless to most programmers but quite unintelligible. We cannot (and I do not) expect our students to *care* about monads because of their inspiration in category theory but because they WORK for a problem that had been plaguing the functional programming community for a long time. This is why I say you must consider your audience. One of the unusual things about Haskell is the strength and breadth of its links to theory and the number of people who are *interested* in that theory as an aid to finding ways to make new kinds of programming thinkable. I don't suppose we'd have had Arrows without this kind of background. But few students in most Computer Science departments take category theory, and those people need monads explained in terms they will be able to understand and to grasp the *practical* significance of. Once they catch the Haskell "spirit" they may well become interested in the theory, but that stuff doesn't belong in tutorials. From bjorn.buckwalter at gmail.com Thu Aug 2 19:36:08 2007 From: bjorn.buckwalter at gmail.com (=?ISO-8859-1?Q?Bj=F6rn_Buckwalter?=) Date: Thu Aug 2 19:28:23 2007 Subject: [Haskell-cafe] ANNOUNCE: Dimensional 0.6 -- Statically checked physical dimensions Message-ID: <8b2a1a960708021636w25d6bf2bp97cb81261e7538e5@mail.gmail.com> David Roundy wrote: > On Thu, Aug 02, 2007 at 10:27:47PM +0200, Bj?rn Buckwalter wrote: > > I am also assuming that the CGS system would not be employed when > > working with temperature, amount or luminosity. This is evident in > > the below type signatures where I have assumed zero extent in the > > temperature, amount and luminosity dimensions. If this is incorrect > > I would appreciate pointers to the CGS representation of these > > dimensions. > > > > Please correct and inform me if my assumptions are wrong! > > The temperature units are the same in CGS as in MKS (Kelvin). Which implies that CGS is applicable to temperatures... what is the (conventional) dimension of temperature in CGS? Is it the same as for Energy (L^2 M^1 T^-2)? > > This is a very rudimentary implementation. To make it more practical > > a significant number of quantities and units, in particularly those > > commonly used with the CGS, would need to be added. In the mean > > time all units defined for the SI can be used with the CGS by > > applying 'fromSI' to quantities defined from the SI units. > > > > If anyone is willing to add quantities/units (or other enhancements) > > I will happily to accept patches. Personally I do not expect to use > > this module and therefore do not intend to invest much more time > > in it. If the module has other users I might reconsider. > > > > And of course, another direction of future work is to define > > additional systems (e.g. natural, relativistic) using this module > > as a template. I imagine this should be fairly straight forward. > > When atomic units are implemented, this could be useful for me... but alas > I very seldom use Haskell for physics, and the effort to learn these > modules seems unlikely to pay off soon. :( Learning to use the modules should require little effort. Learning enough to implement the atomic system of units would require significant effort though. Unfortunately I don't see myself implementing atomic units, at lease not anytime soon. Thanks, Bjorn From dpiponi at gmail.com Thu Aug 2 19:50:09 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Thu Aug 2 19:42:24 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative In-Reply-To: References: <5de3f5ca0708020005o27974426g2038f68512447be3@mail.gmail.com> Message-ID: <625b74080708021650qd0ac264s22b3cecfb7c72a65@mail.gmail.com> ok wrote: > It is considerably more than a little revisionist to identify Haskell > monads with Category Theory monads. > So a category theory monad is a functor from some category to itself. > How is IO a a functor? Which category does it operate on? What does it > do to the points of that category? What does it do to the arrows? IO is a fully paid up Monad in the categorical sense. The category is the category whose objects are types and whose arrows are functions between those types. IO is a functor. The object a maps to IO a. An arrow f::a->b maps to (>>= return . f)::IO a -> IO b and that can be used to make IO an instance of Functor. The natural transforms eta and mu are called return and join. I make no claim that beginners need to know this stuff, but it's useful to understand when you start having to compose monads and create new monads. -- Dan From westondan at imageworks.com Thu Aug 2 19:51:00 2007 From: westondan at imageworks.com (Dan Weston) Date: Thu Aug 2 19:43:17 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative In-Reply-To: References: <5de3f5ca0708020005o27974426g2038f68512447be3@mail.gmail.com> Message-ID: <46B26DE4.2010105@imageworks.com> My category theory is pretty weak, but I'll take a stab (others can correct me if I say something stupid): ok wrote: > It is considerably more than a little revisionist to identify Haskell > monads with Category Theory monads. > > Quoting the Wikipedia article on monads: > > "If F and G are a pair of adjoint functors, with F left adjoint to G, > then the composition G o F will be a monad. > Note that therefore a monad is a functor from a category to itself; > and that if F and G were actually inverses as functors the corresponding > monad would be the identity functor." > > So a category theory monad is a functor from some category to itself. > How is IO a a functor? It is an endofunctor in the category whose objects are Haskell types and whose arrows are Haskell functions. > Which category does it operate on? What does it > do to the points of that category? What does it do to the arrows? It maps objects (Haskell types) to boxed types (Haskell monads), i.e. sets of values of a certain type to sets of computations resulting in a value of that type. It maps arrows (Haskell functions) to Kleisli arrows, i.e. it maps the set of functions {f : a -> b} into the set of functions {f : a -> m b}. > Let's turn to the formal definition: > > "If C is a category, a monad on C consists of a functor T : C ? C > together with two natural transformations: ? : 1 ? T (where 1 > denotes the identity functor on C) and ? : T2 ? T (where T2 is > the functor T o T from C to C). These are required to fulfill > [some] axioms:" > > What are the natural transformations for the IO monad? ? is the unit Kleisli arrow: return :: (Monad m) => a -> m a ? : T2 ? T is the join function join :: (Monad m) => m (m a) -> m a > I suppose there > is a vague parallel to return and >>=, but that's about all you can claim > for it. There is more than a vague claim. From http://www.haskell.org/haskellwiki/Monads_as_containers: (>>=) :: (Monad m) => m a -> (a -> m b) -> m b xs >>= f = join (fmap f xs) join :: (Monad m) => m (m a) -> m a join xss = xss >>= id > If we are not to be revisionist, then we must admit that Haskell monads > were *inspired* by category theory monads, but went through a couple of > rounds of change of notation before becoming the Monad class we know and > love today. Apparently only some of use love Haskell monads! :) The notation seems like a pretty straightforward mapping to me. > What we have *was* invented for functional programming and > its category theory roots are not only useless to most programmers but > quite unintelligible. I would say "applied" rather than "invented". Clearly "useless" and "unintelligible" are predicates of the programmer. > We cannot (and I do not) expect our students to > *care* about monads because of their inspiration in category theory but > because they WORK for a problem that had been plaguing the functional > programming community for a long time. Maybe you should raise your expectations? > This is why I say you must consider your audience. On second thought, maybe I should have considered my audience before replying to your email. The prior probability of persuasion occurring is maybe somewhat small, but I'm a sucker for lost causes... Dan Weston From bjpop at csse.unimelb.edu.au Thu Aug 2 20:33:23 2007 From: bjpop at csse.unimelb.edu.au (Bernie Pope) Date: Thu Aug 2 20:22:23 2007 Subject: [Haskell-cafe] Perfect example In-Reply-To: <200708022002.14755.jon@ffconsultancy.com> References: <200708022002.14755.jon@ffconsultancy.com> Message-ID: <59D666C6-D735-4B52-B3B1-3434C1A508FF@csse.unimelb.edu.au> That's a tough one, If I want a small example to show to people I usually use zipWith. It is higher-order and lazy, and I include a discussion of "lists as loops", which means zipWith is a loop combiner. When my audience is C programmers I ask them to implement it in C, which is always amusing. As an added bonus it has a lovely type signature, which can be used as a lead-in to a discussion on types. If I want a more "realistic" example, then I usually show people a piece of haskell gtk code, again comparing it to C or whatever language the audience knows. The Haskell gtk code tends to read very nicely, and it is type safe. It also emphasises the fact that Haskell is not only able to to "real things", but able to do them "really well". I doubt either are "perfect", but maybe they will inspire you to dream up something which suits your needs. Cheers, Bernie. On 03/08/2007, at 5:02 AM, Jon Harrop wrote: > > Any suggestions for a perfect example that uniquely demonstrates > the benefits > of the Haskell language compared to other languages? > > -- > Dr Jon D Harrop, Flying Frog Consultancy Ltd. > OCaml for Scientists > http://www.ffconsultancy.com/products/ocaml_for_scientists/?e > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From ndmitchell at gmail.com Thu Aug 2 20:40:32 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Thu Aug 2 20:32:48 2007 Subject: [Haskell-cafe] Perfect example In-Reply-To: <200708022002.14755.jon@ffconsultancy.com> References: <200708022002.14755.jon@ffconsultancy.com> Message-ID: <404396ef0708021740k581b8111n4d919015e058cbd0@mail.gmail.com> Hi I know that Audrey Tang (the Pugs project) has used hamming numbers for this, see http://www.perl.com/lpt/a/959 Thanks Neil On 8/2/07, Jon Harrop wrote: > > Any suggestions for a perfect example that uniquely demonstrates the benefits > of the Haskell language compared to other languages? > > -- > Dr Jon D Harrop, Flying Frog Consultancy Ltd. > OCaml for Scientists > http://www.ffconsultancy.com/products/ocaml_for_scientists/?e > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From ndmitchell at gmail.com Thu Aug 2 20:45:03 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Thu Aug 2 20:37:19 2007 Subject: [Haskell-cafe] positive Int In-Reply-To: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> References: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> Message-ID: <404396ef0708021745k50081320w39ff930c537206f6@mail.gmail.com> Hi Catch (www.cs.york.ac.uk/~ndm/catch) can infer that certain uses of numbers fit into the {Neg, Zero, One, Pos} abstraction - so for example it can infer that length returns {Zero, One, Pos}, but not Neg. If you then do: xs !! length ys It will detect that length ys is natural, and will be safe. However, if you pass any arbitrary value as the index to !! it will warn of a possible pattern match error. You can of course use type Nat = Int, and write additional documentation, even if this documentation isn't a static guarantee. Thanks Neil On 8/2/07, brad clawsie wrote: > as far as i know, the haskell standard does not define a basic Int > type that is limited to positive numbers. > > would a type of this kind not potentially allow us to make stronger > verification statements about certain functions? > > for example, 'length' returns an Int, but in reality it must always > return a value 0 or greater. a potential counter-argument would be the > need to possibly redefine Ord etc for this more narrow type... > > > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From stefanor at cox.net Thu Aug 2 20:49:23 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 2 20:41:41 2007 Subject: [Haskell-cafe] positive Int In-Reply-To: <404396ef0708021745k50081320w39ff930c537206f6@mail.gmail.com> References: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> <404396ef0708021745k50081320w39ff930c537206f6@mail.gmail.com> Message-ID: <20070803004923.GA4852@localhost.localdomain> On Fri, Aug 03, 2007 at 01:45:03AM +0100, Neil Mitchell wrote: > Hi > > Catch (www.cs.york.ac.uk/~ndm/catch) can infer that certain uses of > numbers fit into the {Neg, Zero, One, Pos} abstraction - so for > example it can infer that length returns {Zero, One, Pos}, but not > Neg. If you then do: > > xs !! length ys > > It will detect that length ys is natural, and will be safe. However, > if you pass any arbitrary value as the index to !! it will warn of a > possible pattern match error. I hope catch doesn't actually think that's safe, because it's not - set ys = xs = [1,2,3,4,5], you'll get an index out of range error. (Yes, I deliberately chose a list longer than 4 elements). Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070802/1f3fb573/attachment.bin From ndmitchell at gmail.com Thu Aug 2 20:56:09 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Thu Aug 2 20:48:25 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: References: Message-ID: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> Hi Chris, > I've heard Simon (Peyton-Jones) twice now mention the desire to be able > to embed a monadic subexpression into a monad. I think this is a fantastic idea, please do so! > $( expr ) -- conflicts with template haskell > ( <- expr ) -- makes sense, and I think it's unambiguous > > Other ideas: > > ``expr`` -- back-ticks make sense for UNIX shell scripters > (| expr |) -- I don't think anything uses this yet This final (| one |) looks way too much like template haskell, it has the feel of template haskell, even if it isn't yet in the syntax. Your (<- proposal) feels a bit like an operator section - I'm not sure if that is a good thing or a bad thing, but for some reason feels slightly clunky and high-syntax overhead, perhaps because of the inevitable space between the <- and expr, and that ()<- are all fairly high semantic value currently in Haskell, while this extension should blend in, rather than stand out. The `` syntax is clever, and I like it, but I worry that its quite a long way from the current use of ` as infix, although I'm not sure if that is a particular issue given - (negation/subtraction) and -- (comment) couldn't be more different. Thanks Neil From zednenem at psualum.com Thu Aug 2 20:56:29 2007 From: zednenem at psualum.com (David Menendez) Date: Thu Aug 2 20:48:44 2007 Subject: [Haskell-cafe] positive Int In-Reply-To: <20070802210832.GD11377@darcs.net> References: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> <20070802192946.GF62676@jobbicycle.corp.yahoo.com> <20070802210832.GD11377@darcs.net> Message-ID: <49a77b7a0708021756yf1385f5jfcd5abeedae1cdd@mail.gmail.com> On 8/2/07, David Roundy wrote: > This would be a very nice type to have (natural numbers), but is a tricky > type to work with. Subtraction, for instance, wouldn't be possible as a > complete function... There is a subtraction-like operation for naturals, where a - b = 0 if a <= b. This is analogous to the way that "drop n xs" returns [] if n >= length xs, but using it in a Num instance would probably violate too many assumptions. The desire to support naturals was the motivation for including semirings in my Num refactoring thought-experiment. From ndmitchell at gmail.com Thu Aug 2 20:59:05 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Thu Aug 2 20:51:20 2007 Subject: [Haskell-cafe] positive Int In-Reply-To: <20070803004923.GA4852@localhost.localdomain> References: <20070802191706.GE62676@jobbicycle.corp.yahoo.com> <404396ef0708021745k50081320w39ff930c537206f6@mail.gmail.com> <20070803004923.GA4852@localhost.localdomain> Message-ID: <404396ef0708021759l660599a4p87f662264b7ba4b3@mail.gmail.com> Hi > > It will detect that length ys is natural, and will be safe. However, > > if you pass any arbitrary value as the index to !! it will warn of a > > possible pattern match error. > > I hope catch doesn't actually think that's safe, because it's not - set > ys = xs = [1,2,3,4,5], you'll get an index out of range error. (Yes, I > deliberately chose a list longer than 4 elements). Of course, it doesn't, I abstracted for the sake of simplicity :-) The !! operator has two entirely separate pattern match errors, one is "negative index", one is "ran off the end of the list". The length xs will satisfy the first one by proving that length is always a natural, but the only proof of the other condition is that either the list is infinite, or that the index is Zero/One, and the list is bigger than this. Thanks Neil From ok at cs.otago.ac.nz Thu Aug 2 21:43:32 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 2 21:35:51 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative In-Reply-To: <625b74080708021650qd0ac264s22b3cecfb7c72a65@mail.gmail.com> References: <5de3f5ca0708020005o27974426g2038f68512447be3@mail.gmail.com> <625b74080708021650qd0ac264s22b3cecfb7c72a65@mail.gmail.com> Message-ID: <8575BD1C-2113-4D48-A3D4-BDFF41238BB9@cs.otago.ac.nz> I asked "How is IO a functor"? On 3 Aug 2007, at 11:50 am, Dan Piponi wrote: > IO is a fully paid up Monad in the categorical sense. The category is > the category whose objects are types and whose arrows are functions > between those types. IO is a functor. The object a maps to IO a. An > arrow f::a->b maps to (>>= return . f)::IO a -> IO b and that can be > used to make IO an instance of Functor. The natural transforms eta and > mu are called return and join. Please go over this again, but slowly this time. You have convinced me, but I'd like to understand the details a little better. I see that any type constructor TC :: * -> * is halfway to being a functor on this category of types. It acts on the objects in the obvious way, so the next step is to see about the arrows. If f :: a -> b then we want TC f :: TC a -> TC b such that TC (f . g) = TC f . TC g and TC (id::a->a) = id :: TC a -> TC a Now this is precisely the Haskell Functor class, so TC is the object part and fmap is the arrow part. You say that (>>= return . f) can be used to make [a Monad] an instance of Functor. Try it... by golly it's true. I see: fmap f = (>>= return . f). So why *aren't* Monads already set up using the type class machinery to always *be* Functors in Haskell? Isn't it bound to confuse people if monads are functors but Monads are not Functors? This is especially puzzling because Maybe, [], and IO already *are* Functors, but the way this is done makes it look accidental, not like the fundamental property of Monads it apparently is. (By the way, I note that the on-line documentation for Control.Monad glosses >>= as "Sequentially composes two actions...".) From dpiponi at gmail.com Thu Aug 2 22:55:36 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Thu Aug 2 22:47:52 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative In-Reply-To: <8575BD1C-2113-4D48-A3D4-BDFF41238BB9@cs.otago.ac.nz> References: <5de3f5ca0708020005o27974426g2038f68512447be3@mail.gmail.com> <625b74080708021650qd0ac264s22b3cecfb7c72a65@mail.gmail.com> <8575BD1C-2113-4D48-A3D4-BDFF41238BB9@cs.otago.ac.nz> Message-ID: <625b74080708021955y7948ea40sf7f9ef5bf09896d1@mail.gmail.com> On 8/2/07, ok wrote: > I asked "How is IO a functor"? > Please go over this again, but slowly this time. > Try it... by golly it's true. I'm not fibbing. I was surprised as you when I found out about this stuff! > So why *aren't* Monads already set up using the type class machinery > to always *be* Functors in Haskell? Isn't it bound to confuse people > if monads are functors but Monads are not Functors? I think it's simply an uncorrected mistake in the prelude. Also, check out Eric Kidd's "lesser known laws" here: http://www.randomhacks.net/articles/2007/03/15/data-set-monad-haskell-macros These follow from the category theory. I personally find the join/return version of the monad laws easier to think about than any other formulation. BTW Natural transformations are particularly nice in the category of types and functions. They're essentially just polymorphic functions of a certain type. But this means that they're candidates for "Theorems for Free!" http://homepages.inf.ed.ac.uk/wadler/topics/parametricity.html so they have good properties. So there's a nice little collection of small but useful theorems about >>=, return, join, fmap and so on that you can deduce from a small amount of category theory. You can deduce them all without the category theory, but I find it useful to see these things in a wider context as they no longer seem like these random identities that hold for no apparent reason. I completely agree with you that beginners don't need to know the category theory. But I highly recommend the first couple of chapters of your favourite CT textbook (up to natural transformations at least, and up to adjoints if you can stand it) to Haskellers with a mathematics background as soon as they are beyond the beginnings. It really does give a bit of insight into a few areas of Haskell. (Oh, that Eric Kidd web page will also answer your earlier question about why Data.Set isn't a Haskell Monad even though the powerset functor is a monad in the category Set.) -- Dan From cdsmith at twu.net Thu Aug 2 23:29:40 2007 From: cdsmith at twu.net (Chris Smith) Date: Thu Aug 2 23:22:03 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> Message-ID: Neil Mitchell wrote: > I think this is a fantastic idea, please do so! > Okay, I'll do it then. If I have a good weekend, perhaps I'll volunteer a talk at AngloHaskell after all! :) So what about syntax? I agree with your objections, so we've got ( <- expr ) -- makes sense, and I think it's unambiguous ``expr`` -- back-ticks make sense for UNIX shell scripters The first is something Simon Peyton-Jones came up with (probably on-the- fly) at OSCON, and I rather like it a lot; but I'm concerned about ambiguity. The latter seems sensible as well. Any other ideas? -- Chris Smith From ninegua at gmail.com Thu Aug 2 23:40:28 2007 From: ninegua at gmail.com (Paul L) Date: Thu Aug 2 23:32:44 2007 Subject: [Haskell-cafe] GHC, GLUT and OS X In-Reply-To: <856033f20708012148y1899fdn2bfc9abd326e1b4d@mail.gmail.com> References: <856033f20708011755l4cfc5ca2u9d1cff6eff915bc4@mail.gmail.com> <1B48BC84-F3CC-47BE-AF68-78562D0FA2AB@gmail.com> <856033f20708011911j2babd825uc4f0e79393e2fa54@mail.gmail.com> <856033f20708012148y1899fdn2bfc9abd326e1b4d@mail.gmail.com> Message-ID: <856033f20708022040i7167648ap8757924a0012c835@mail.gmail.com> Ok, after spending some time looking for a solution, here is a stroke of genius by wxHaskell folks at http://wxhaskell.sourceforge.net/building-macosx.html I've tried this enableGUI trick using GHCi, it works with my GLFW interface to Haskell which suffered from the same problem as GLUT on OS X, but then it still won't work with GLUT. So, does anyone have a clue of what's going on with GLUT on OS X? Regards, Paul Liu From derek.a.elkins at gmail.com Thu Aug 2 23:40:26 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Thu Aug 2 23:32:51 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> Message-ID: <1186112426.6796.4.camel@derek-laptop> On Thu, 2007-08-02 at 21:29 -0600, Chris Smith wrote: > Neil Mitchell wrote: > > I think this is a fantastic idea, please do so! > > > > Okay, I'll do it then. If I have a good weekend, perhaps I'll volunteer > a talk at AngloHaskell after all! :) > > So what about syntax? I agree with your objections, so we've got > > ( <- expr ) -- makes sense, and I think it's unambiguous > ``expr`` -- back-ticks make sense for UNIX shell scripters > > The first is something Simon Peyton-Jones came up with (probably on-the- > fly) at OSCON, and I rather like it a lot; but I'm concerned about > ambiguity. The latter seems sensible as well. Any other ideas? The latter is not sensible to me at all. It doesn't nest well. Neither does the former for that matter, but it forces parenthesizing. You will find that being clear on nesting is very important. From bayer at math.columbia.edu Thu Aug 2 23:52:53 2007 From: bayer at math.columbia.edu (Dave Bayer) Date: Thu Aug 2 23:45:22 2007 Subject: [Haskell-cafe] When is waitForProcess not necessary? Message-ID: If one is calling runInteractiveCommand for a "sure-thing" returning a small amount of output (say, "ls" for a modest directory"), is it necessary to call waitForProcess? My waitForProcess calls came under scrutiny when I tried to GHC profile a threaded process, which isn't possible. It turns out that my programs run faster if they don't call waitForProcess, and it sure seems empirically that they never fail to run correctly. It would seem to me that in a lazy language, later code wouldn't presume it was looking at an entire string until the actual EOF came through, completing the string. So at the end of a program, with nothing else to do but wait, why not wait "implicitly" rather than via an explicit call to waitForProcess? What am I missing? (I've searched this forum; an interesting example is runCommand in http://happs.org/HAppS/src/HAppS/Util/Common.hs but I'm asking why this isn't overkill in my scenario. I'm actually calling Markdown.pl on tiny files (source code of lengths a human would read), and it is certainly sluggish enough to be a fair test.) From allbery at ece.cmu.edu Thu Aug 2 23:57:51 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Thu Aug 2 23:50:10 2007 Subject: [Haskell-cafe] When is waitForProcess not necessary? In-Reply-To: References: Message-ID: <90F1F5A9-5FF0-481D-B0E0-D996BEEDB371@ece.cmu.edu> On Aug 2, 2007, at 23:52 , Dave Bayer wrote: > If one is calling runInteractiveCommand for a "sure-thing" > returning a small > amount of output (say, "ls" for a modest directory"), is it > necessary to call > waitForProcess? Most operating systems only let you have a small number of outstanding child processes; once you hit it, you'll need to wait() (aka waitForProcess) to reap the dead children before you can launch any more. If you're only doing it once, you can ignore waitForProcess and let the OS's process exit stuff reap the child for you --- but I suggest documenting that you've done this, in case you later change the program to run more children and they start failing with "Too many processes". -- 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 dons at cse.unsw.edu.au Thu Aug 2 23:58:20 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Thu Aug 2 23:50:37 2007 Subject: [Haskell-cafe] When is waitForProcess not necessary? In-Reply-To: References: Message-ID: <20070803035819.GB23359@cse.unsw.EDU.AU> bayer: > If one is calling runInteractiveCommand for a "sure-thing" returning a small > amount of output (say, "ls" for a modest directory"), is it necessary to call > waitForProcess? > > My waitForProcess calls came under scrutiny when I tried to GHC profile a > threaded process, which isn't possible. It turns out that my programs run > faster if they don't call waitForProcess, and it sure seems empirically > that they never fail to run correctly. It would seem to me that in a lazy > language, later code wouldn't presume it was looking at an entire string > until the actual EOF came through, completing the string. > > So at the end of a program, with nothing else to do but wait, why not wait > "implicitly" rather than via an explicit call to waitForProcess? What am I > missing? > > (I've searched this forum; an interesting example is runCommand in > > > http://happs.org/HAppS/src/HAppS/Util/Common.hs > > but I'm asking why this isn't overkill in my scenario. I'm actually calling > Markdown.pl on tiny files (source code of lengths a human would read), and > it is certainly sluggish enough to be a fair test.) > > _______________________________________________ You might be interested in : http://www.cse.unsw.edu.au/~dons/code/newpopen/ In particular, readProcess :: FilePath -- ^ command to run -> [String] -- ^ any arguments -> String -- ^ standard input -> IO (Either ExitCode String) -- ^ either the stdout, or an exitcode Strict String IO for processes, without the zombies. -- Don Stewart (Authorised by the "People for System.IO.Strict" party) From cdsmith at twu.net Fri Aug 3 00:24:01 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 00:16:32 2007 Subject: [Haskell-cafe] Re: Re: monad subexpressions References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> <1186112426.6796.4.camel@derek-laptop> Message-ID: Derek Elkins wrote: > > ( <- expr ) -- makes sense, and I think it's unambiguous > > ``expr`` -- back-ticks make sense for UNIX shell scripters > The latter is not sensible to me at all. It doesn't nest well. Ah, excellent point! Okay, it's gone then. Everything will then need some kind of bracketing -- (), [], or {}. I dislike [] out of hand, simply because this has nothing to do with lists. > Neither does the former for that matter, but it forces parenthesizing. I'm unclear on whether you still have an objection, given that yes it does force parenthesizing. -- Chris Smith From bulat.ziganshin at gmail.com Fri Aug 3 01:11:35 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Fri Aug 3 01:07:26 2007 Subject: [Haskell-cafe] Perfect example In-Reply-To: <200708022002.14755.jon@ffconsultancy.com> References: <200708022002.14755.jon@ffconsultancy.com> Message-ID: <176095581.20070803091135@gmail.com> Hello Jon, Thursday, August 2, 2007, 11:02:14 PM, you wrote: > Any suggestions for a perfect example that uniquely demonstrates the benefits > of the Haskell language compared to other languages? http://www.haskell.org/haskellwiki/Simple_unix_tools -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From miguelimo38 at yandex.ru Fri Aug 3 01:59:34 2007 From: miguelimo38 at yandex.ru (Miguel Mitrofanov) Date: Fri Aug 3 01:53:14 2007 Subject: [Haskell-cafe] Perfect example In-Reply-To: <59D666C6-D735-4B52-B3B1-3434C1A508FF@csse.unimelb.edu.au> References: <200708022002.14755.jon@ffconsultancy.com> <59D666C6-D735-4B52-B3B1-3434C1A508FF@csse.unimelb.edu.au> Message-ID: <1327857.20070803095934@yandex.ru> BP> If I want a small example to show to people I usually use zipWith. I'd suggest unfoldr + lazyness, such as hammings = 1 : unfoldr (Just . generator) (map (\n -> map (n*) hammings) [2,3,5]) where generator xss = let x = minimum $ map head xss in (x, map (dropWhile (x==)) xss) I guess, it's tough to reproduce even in languages like Prolog. From simonpj at microsoft.com Fri Aug 3 04:04:36 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Fri Aug 3 03:56:52 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> Message-ID: See also this thread http://www.haskell.org/pipermail/haskell-prime/2007-July/002269.html Magnus made a TH library that does something similar, see http://www.haskell.org/pipermail/haskell-prime/2007-July/002275.html Nesting is important. Consider do { a <- f x ; b <- g a ; return (2*b) } Then you'd like to linearise this to give do { return (2 * $(g $(f x))) } The hardest thing about this project is finding a suitable syntax! You can't use the same syntax as TH, but it does have a "splice-like" flavour, so something similar would make sense. $[ thing ] perhaps? Or %( thing )? Avoid anything that looks like a TH *quotation* because that suggests the wrong thing. (| thing |) is bad. A good plan can be to start a Wiki page that describes the problem, then the proposed extension, gives lots of exmaples, etc. Simon | -----Original Message----- | From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Chris | Smith | Sent: 03 August 2007 04:30 | To: haskell-cafe@haskell.org | Subject: [Haskell-cafe] Re: monad subexpressions | | Neil Mitchell wrote: | > I think this is a fantastic idea, please do so! | > | | Okay, I'll do it then. If I have a good weekend, perhaps I'll volunteer | a talk at AngloHaskell after all! :) | | So what about syntax? I agree with your objections, so we've got | | ( <- expr ) -- makes sense, and I think it's unambiguous | ``expr`` -- back-ticks make sense for UNIX shell scripters | | The first is something Simon Peyton-Jones came up with (probably on-the- | fly) at OSCON, and I rather like it a lot; but I'm concerned about | ambiguity. The latter seems sensible as well. Any other ideas? | | -- | Chris Smith From apfelmus at quantentunnel.de Fri Aug 3 04:05:22 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Fri Aug 3 03:57:47 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: Message-ID: Chris Smith wrote: > I've heard Simon (Peyton-Jones) twice now mention the desire to be able > to embed a monadic subexpression into a monad. That would be > http://article.gmane.org/gmane.comp.lang.haskell.prime/2267 and in the > recent OSCON video. I still think that this syntax extension has profound impact and is a bad idea. Simon's and Neill's use case was the dreaded name-supply monad where the order of effects really doesn't matter up to alpha-conversion. The objection to that use case is that monads are not the right abstraction for that, they're too general. Also, a workaround is to lift functions f :: a -> b -> m c g :: d -> m b to f' :: m a -> m b -> m c g' :: m d -> m b and thus flip the need for argument sugar f $(g x) y VS f' (g' (r$ x)) (r$ y) With r = return, the latter is Haskell98. See also http://thread.gmane.org/gmane.comp.lang.haskell.prime/2263/focus=2267 > Also, I got so frustrated that I ended up abandoning some code > recently because STM is, in the end, so darn hard to use as a > result of this issue. I'd love to see this solved, and I'm quite > eager to do it. This sounds suspicious, since the order of effects is of course important in the STM monad. Can you post an example of code you intend to abandon due to ugliness? I'd be astonished if there's no better way to write it. Regards, apfelmus From jules at jellybean.co.uk Fri Aug 3 04:06:41 2007 From: jules at jellybean.co.uk (Jules Bean) Date: Fri Aug 3 03:59:02 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> Message-ID: <46B2E211.6080400@jellybean.co.uk> Neil Mitchell wrote: > Hi Chris, > >> I've heard Simon (Peyton-Jones) twice now mention the desire to be able >> to embed a monadic subexpression into a monad. > > I think this is a fantastic idea, please do so! > >> $( expr ) -- conflicts with template haskell >> ( <- expr ) -- makes sense, and I think it's unambiguous >> >> Other ideas: >> >> ``expr`` -- back-ticks make sense for UNIX shell scripters >> (| expr |) -- I don't think anything uses this yet > > This final (| one |) looks way too much like template haskell, it has > the feel of template haskell, even if it isn't yet in the syntax. Your > (<- proposal) feels a bit like an operator section - I'm not sure if > that is a good thing or a bad thing, but for some reason feels > slightly clunky and high-syntax overhead, perhaps because of the > inevitable space between the <- and expr, and that ()<- are all fairly > high semantic value currently in Haskell, while this extension should > blend in, rather than stand out. I'm not sure I agree with Neil's misgivings. Certainly <- already has a high semantic value, but this is a very closely related notion, so I see that as consistent. As for the (), well as far as I know they only have two meanings: grouping and tupling. This seems like a special case of grouping to me. E.g.: do a <- m b <- n l a x b y becomes l (<- m) x (<- n) y ...with, I suppose, left-to-right evaluation order. This looks 'almost like substitution' which is the goal. Jules From simonpj at microsoft.com Fri Aug 3 04:13:18 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Fri Aug 3 04:05:35 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: Message-ID: | > I've heard Simon (Peyton-Jones) twice now mention the desire to be able | > to embed a monadic subexpression into a monad. That would be | > http://article.gmane.org/gmane.comp.lang.haskell.prime/2267 and in the | > recent OSCON video. | | I still think that this syntax extension has profound impact and is a | bad idea. Simon's and Neill's use case was the dreaded name-supply monad | where the order of effects really doesn't matter up to alpha-conversion. | The objection to that use case is that monads are not the right | abstraction for that, they're too general Just for the record, I am not arguing that this is the Right Thing; I am quite agnostic about it. But the status quo doesn't seem that great either, and I'm all for experimentation. Same goes for view patterns and record wildcards, for example. Simon From ithika at gmail.com Fri Aug 3 04:28:10 2007 From: ithika at gmail.com (Dougal Stanton) Date: Fri Aug 3 04:20:29 2007 Subject: [Haskell-cafe] When is waitForProcess not necessary? In-Reply-To: References: Message-ID: <2d3641330708030128s51d644adpc167eb282c1fa22e@mail.gmail.com> On 03/08/07, Dave Bayer wrote: > I'm actually calling > Markdown.pl on tiny files (source code of lengths a human would read), and > it is certainly sluggish enough to be a fair test.) I had to do this recently, so you might be interested in my approach: The idea here is to run arbitrary text (blog posts) through Markdown and Smartypants before sending them out to the wider world. The code should be pretty self-contained and easy to follow. It does use waitForProcess but I've done my best to keep it clean. (It could still do with being refactored though; there are still bits or repeated code.) The part you want is about 80% of the way down and looks like this: educate = \s -> markdown s >>= smartypants markdown = convert "Markdown" smartypants = convert "SmartyPants" convertWith conv str = do (hin, hout, herr, proc) <- runInteractiveProcess conv [] Nothing Nothing forkIO $ hPutStr hin str >> hClose hin str' <- hGetContents hout return (str', proc) convert conv input = do bracket (convertWith conv input) (\(_,pc) -> do ret <- waitForProcess pc return (ret==ExitSuccess)) (return . fst) Cheers, D. From jules at jellybean.co.uk Fri Aug 3 04:38:09 2007 From: jules at jellybean.co.uk (Jules Bean) Date: Fri Aug 3 04:30:26 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: <46B2E211.6080400@jellybean.co.uk> References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> <46B2E211.6080400@jellybean.co.uk> Message-ID: <46B2E971.5040307@jellybean.co.uk> Jules Bean wrote: > do > a <- m > b <- n > l a x b y > > becomes > > l (<- m) x (<- n) y > > ...with, I suppose, left-to-right evaluation order. This looks 'almost > like substitution' which is the goal. > Having read the thread SPJ pointed to, I should point out that using a mixture of Applicative and Monad notation, this can currently be written as: l <$> m <*> (return x) <*> n =<< (return y) ...where the thing that feels weirdest is having to remember to use =<< instead of <*> for the final 'application'. Jules From bulat.ziganshin at gmail.com Fri Aug 3 06:37:25 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Fri Aug 3 06:34:44 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: Message-ID: <1539063779.20070803143725@gmail.com> Hello apfelmus, Friday, August 3, 2007, 12:05:22 PM, you wrote: > I still think that this syntax extension has profound impact and is a > bad idea. can you please rewrite *p++=*q++ in haskell? -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From claus.reinke at talk21.com Fri Aug 3 06:57:52 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Fri Aug 3 06:50:12 2007 Subject: [Haskell-cafe] monad subexpressions References: Message-ID: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> > I've heard Simon (Peyton-Jones) twice now mention the desire to be able > to embed a monadic subexpression into a monad. That would be > http://article.gmane.org/gmane.comp.lang.haskell.prime/2267 >.. > Thoughts? what is the problem you're trying to solve, and is it worth the complication in syntax? in previous threads, the answer to the second questions seemed to be 'no', because there are easy workarounds (liftMn/return, or combinator-based lifting) and the extension would have non-local effects. what is particularly nasty about this extension is that it might be easy to add, but will interfere with just about everything else: it looks like an operator, and for tiny examples, it seems to have a local effect only, but it is really a piece of static syntax distributed widely over parts of a dynamic expression; the special quoting cannot be understood locally, as it is -namelessly- bound to the _next_ enclosing 'do', thereby complicating local program transformations, by tools or users. why is the syntax even bound to do (adding 'do's or switching from 'do' to '>>=' will change everything), and not to monadic operators (with lifting in place, there'd be more isolated monadic calls, without need for 'do')? wouldn't it be sufficient to lift the parameter out of the next enclosing call (and isn't that what the no-syntax alternatives already provide)? and what is the precise specification/what happens with more complex examples? more helpful than an immediate implementation, imho, would be a wiki page formalising the proposed extension and discussing the alternatives with pros and cons. perhaps there are lifting operations that are missing (eg, liftMn lifts non-monadic functions, but how to lift monadic functions with non-monadic parameters?), or perhaps the combinators that enable lifting of complete calls (rather than functions) could be simplified; this issue trips up enough people that it is worth investigating what the real show-stoppers are, or why the workarounds are not more widely used/known. but in the end, i'd expect the no-syntax route to be just as convenient, and less problematic in this case. claus From lutz at iks-jena.de Fri Aug 3 07:26:27 2007 From: lutz at iks-jena.de (Lutz Donnerhacke) Date: Fri Aug 3 07:18:44 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <1539063779.20070803143725@gmail.com> Message-ID: * Bulat Ziganshin wrote: > Hello apfelmus, >> I still think that this syntax extension has profound impact and is a >> bad idea. > > can you please rewrite *p++=*q++ in haskell? p = q From rahn at ira.uka.de Fri Aug 3 07:32:57 2007 From: rahn at ira.uka.de (Mirko Rahn) Date: Fri Aug 3 07:25:24 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <1539063779.20070803143725@gmail.com> References: <1539063779.20070803143725@gmail.com> Message-ID: <46B31269.7010805@ira.uka.de> > rewrite *p++=*q++ in haskell? I always reject such codes when produced by my students. It is just unreadable. I even do not understand what you are trying to achieve. However, gcc seems it to compile to something like *p = *(p+1) ; *q = *(q+1) But for what is the '=' good for? So rewriting it in Haskell (of any size) is a good idea to actually understand the code. Please, could you do it. /BR -- -- Mirko Rahn -- Tel +49-721 608 7504 -- --- http://liinwww.ira.uka.de/~rahn/ --- From rahn at ira.uka.de Fri Aug 3 07:47:47 2007 From: rahn at ira.uka.de (Mirko Rahn) Date: Fri Aug 3 07:40:12 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> Message-ID: <46B315E3.2020701@ira.uka.de> >>> rewrite *p++=*q++ in haskell? >> *p = *(p+1) ; *q = *(q+1) > If that's true then GCC has gone insane, because they are completely different. Of course you are right, I just observed at the wrong place..., sorry for that. > Though, as any C programmer knows, you really should be using > memcpy() I like to hear that you would reject it either. /BR -- -- Mirko Rahn -- Tel +49-721 608 7504 -- --- http://liinwww.ira.uka.de/~rahn/ --- From bulat.ziganshin at gmail.com Fri Aug 3 07:58:04 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Fri Aug 3 07:53:57 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <46B31269.7010805@ira.uka.de> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> Message-ID: <155949898.20070803155804@gmail.com> Hello Mirko, Friday, August 3, 2007, 3:32:57 PM, you wrote: >> rewrite *p++=*q++ in haskell? > I always reject such codes when produced by my students. It is just > unreadable. it's one of C idioms. probably, you don't have enough C experience to understand it :) > So rewriting it in Haskell (of any size) is a good idea to actually > understand the code. Please, could you do it. result is that currently C code rewritten in Haskell becomes much larger and less readable. if you think that readIORef is more readable than *, and x<-readioref v; writeioref v (x+1) is more readable than ++ - it's up to you :) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From miguelimo38 at yandex.ru Fri Aug 3 08:11:37 2007 From: miguelimo38 at yandex.ru (Miguel Mitrofanov) Date: Fri Aug 3 08:05:23 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <46B31269.7010805@ira.uka.de> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> Message-ID: <10610560506.20070803161137@yandex.ru> >> rewrite *p++=*q++ in haskell? MR> I always reject such codes when produced by my students. It is just MR> unreadable. I even do not understand what you are trying to achieve. MR> However, gcc seems it to compile to something like MR> *p = *(p+1) ; *q = *(q+1) MR> But for what is the '=' good for? MR> So rewriting it in Haskell (of any size) is a good idea to actually MR> understand the code. Please, could you do it. MR> /BR From miguelimo38 at yandex.ru Fri Aug 3 08:13:34 2007 From: miguelimo38 at yandex.ru (Miguel Mitrofanov) Date: Fri Aug 3 08:07:15 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <46B31269.7010805@ira.uka.de> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> Message-ID: <1063654624.20070803161334@yandex.ru> >> rewrite *p++=*q++ in haskell? MR> I always reject such codes when produced by my students. I don't think it's a good idea to reject working code. MR> I even do not understand what you are trying to achieve. Well, that just means that your students are a bit smarter than you. And I'd like to ensure you, they know this and are considering you as a person who is afraid of smart people. From rahn at ira.uka.de Fri Aug 3 08:41:05 2007 From: rahn at ira.uka.de (Mirko Rahn) Date: Fri Aug 3 08:33:32 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <155949898.20070803155804@gmail.com> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> Message-ID: <46B32261.1070807@ira.uka.de> >>> rewrite *p++=*q++ in haskell? > it's one of C idioms. probably, you don't have enough C experience to > understand it :) Maybe, but how can *you* understand it, when the standard is vague about it? It could be A: *p=*q; p+=1; q+=1; B: *p=*q; q+=1; p+=1; C: tp=p; tq=q; p+=1; q+=1; *tp=*tq; ...and so on. Which is the "right" version? > result is that currently C code rewritten in Haskell becomes much > larger and less readable. Larger should not be that issue and readability depends on the reader as your C example shows. Some Haskellers would very quickly recognize some common idioms, where others need some help... /BR -- -- Mirko Rahn -- Tel +49-721 608 7504 -- --- http://liinwww.ira.uka.de/~rahn/ --- From ndmitchell at gmail.com Fri Aug 3 08:49:13 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Fri Aug 3 08:41:28 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <46B32261.1070807@ira.uka.de> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> Message-ID: <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> Hi Perhaps we need to cool this thread down a little bit, and refocus. I personally choose never to use ++ as anything but a statement, since my brain works that way. Other people find different things natural, so can pick what they choose. The one thing you can guarantee is that discussing it isn't going to result in anyone changing their opinion! The thread started out on monad subexpressions, with request for helpful thoughts as to what could be done with them, and how we can treat them syntactically. Does anyone have any further thoughts on the syntax? We started with 4 suggestions, and as far as I can tell, are left with only one (<- ...). This is the time for people to have new and clever thoughts, and possibly shape the future of (what I think) will be a very commonly used Haskell syntax. For the record, my comments on (<- ...) where not objections, but merely "thoughts out loud", and I could certainly see myself using that syntax in a day to day basis. Thanks Neil On 8/3/07, Mirko Rahn wrote: > > >>> rewrite *p++=*q++ in haskell? > > > it's one of C idioms. probably, you don't have enough C experience to > > understand it :) > > Maybe, but how can *you* understand it, when the standard is vague about it? > > It could be > > A: *p=*q; p+=1; q+=1; > B: *p=*q; q+=1; p+=1; > C: tp=p; tq=q; p+=1; q+=1; *tp=*tq; > > ...and so on. Which is the "right" version? > > > result is that currently C code rewritten in Haskell becomes much > > larger and less readable. > > Larger should not be that issue and readability depends on the reader as > your C example shows. Some Haskellers would very quickly recognize some > common idioms, where others need some help... > > /BR > > -- > -- Mirko Rahn -- Tel +49-721 608 7504 -- > --- http://liinwww.ira.uka.de/~rahn/ --- > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From ndmitchell at gmail.com Fri Aug 3 09:06:31 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Fri Aug 3 08:58:45 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> Message-ID: <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> Hi Thinking on the semantic issue for the moment: Can you use (<-) outside of a do block? b >> f (<- a) What are the semantics of do b >> f (<- a) where does the evaluation of a get lifted to? Given: if (<- a) then f (<- b) else g (<- c) Do b and c both get monadic bindings regardless of a? if (<- a) then do f (<- b) else g (<- c) Does this change to make b bound inside the then, but c bound outside? Does this then violate the rule that do x == x Can you combine let and do? do let x = (<- a) f x Our "best guess" is that all monadic bindings get floated to the previous line of the innermost do block, in left-to-right order. Monadic expressions in let statements are allowed. Outside a do block, monadic subexpressions are banned. Despite all these complications, it's still a great idea, and would be lovely to have! Thanks Neil and Tom On 8/3/07, Neil Mitchell wrote: > Hi > > Perhaps we need to cool this thread down a little bit, and refocus. I > personally choose never to use ++ as anything but a statement, since > my brain works that way. Other people find different things natural, > so can pick what they choose. The one thing you can guarantee is that > discussing it isn't going to result in anyone changing their opinion! > > The thread started out on monad subexpressions, with request for > helpful thoughts as to what could be done with them, and how we can > treat them syntactically. Does anyone have any further thoughts on the > syntax? We started with 4 suggestions, and as far as I can tell, are > left with only one (<- ...). This is the time for people to have new > and clever thoughts, and possibly shape the future of (what I think) > will be a very commonly used Haskell syntax. > > For the record, my comments on (<- ...) where not objections, but > merely "thoughts out loud", and I could certainly see myself using > that syntax in a day to day basis. > > Thanks > > Neil > > > > On 8/3/07, Mirko Rahn wrote: > > > > >>> rewrite *p++=*q++ in haskell? > > > > > it's one of C idioms. probably, you don't have enough C experience to > > > understand it :) > > > > Maybe, but how can *you* understand it, when the standard is vague about it? > > > > It could be > > > > A: *p=*q; p+=1; q+=1; > > B: *p=*q; q+=1; p+=1; > > C: tp=p; tq=q; p+=1; q+=1; *tp=*tq; > > > > ...and so on. Which is the "right" version? > > > > > result is that currently C code rewritten in Haskell becomes much > > > larger and less readable. > > > > Larger should not be that issue and readability depends on the reader as > > your C example shows. Some Haskellers would very quickly recognize some > > common idioms, where others need some help... > > > > /BR > > > > -- > > -- Mirko Rahn -- Tel +49-721 608 7504 -- > > --- http://liinwww.ira.uka.de/~rahn/ --- > > _______________________________________________ > > Haskell-Cafe mailing list > > Haskell-Cafe@haskell.org > > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > From claus.reinke at talk21.com Fri Aug 3 09:12:26 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Fri Aug 3 09:04:45 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <1539063779.20070803143725@gmail.com> Message-ID: <00f401c7d5cf$f120be70$14217ad5@cr3lt> > can you please rewrite *p++=*q++ in haskell? assuming these operations i :: V a -> IO (V a) -- incr var addr, return old addr r :: V a -> IO a -- read var w :: V a -> a -> IO () -- write var value and this unfolded translation do { qv <- r q; w p qv; i p; i q } assuming further these liftings ap1 :: (a->m b) -> (m a->m b) ap2 :: (a->b->m c) -> (m a->m b->m c) then we can define (=:) :: IO (V a) -> IO a -> IO () mv =: ma = (ap2 w) mv ma and get this inlined version i p =: (r `ap1` i q) but one might still prefer do { w p =<< r q; i p; i q } but whatever line-noise one prefers, this still seems a call for better combinators in the standard libs, rather than a call for more syntax. claus From bos at serpentine.com Fri Aug 3 09:38:15 2007 From: bos at serpentine.com (Bryan O'Sullivan) Date: Fri Aug 3 09:31:34 2007 Subject: [Haskell-cafe] When is waitForProcess not necessary? In-Reply-To: <2d3641330708030128s51d644adpc167eb282c1fa22e@mail.gmail.com> References: <2d3641330708030128s51d644adpc167eb282c1fa22e@mail.gmail.com> Message-ID: <46B32FC7.4050700@serpentine.com> Dougal Stanton wrote: > I had to do this recently, so you might be interested in my approach: > > > > The idea here is to run arbitrary text (blog posts) through Markdown > and Smartypants before sending them out to the wider world. Pardon me while I veer off-topic, but you could also use Pandoc to do this. No forking required. http://sophos.berkeley.edu/macfarlane/pandoc/ References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> Message-ID: <01916127.20070803172433@gmail.com> Hello Mirko, Friday, August 3, 2007, 4:41:05 PM, you wrote: >> result is that currently C code rewritten in Haskell becomes much >> larger and less readable. > Larger should not be that issue and readability depends on the reader as > your C example shows. Some Haskellers would very quickly recognize some > common idioms, where others need some help... probably Turing machine is your favorite PL - it has simple and concise semantics :) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From bulat.ziganshin at gmail.com Fri Aug 3 09:36:40 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Fri Aug 3 09:32:39 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <00f401c7d5cf$f120be70$14217ad5@cr3lt> References: <1539063779.20070803143725@gmail.com> <00f401c7d5cf$f120be70$14217ad5@cr3lt> Message-ID: <785460922.20070803173640@gmail.com> Hello Claus, Friday, August 3, 2007, 5:12:26 PM, you wrote: >> can you please rewrite *p++=*q++ in haskell? > do { w p =<< r q; i p; i q } how about *Object.File.Line.CurPtr++ = *AnotherObject.File.Line.CurPtr++ ? ;) > but whatever line-noise one prefers, this still seems a call for > better combinators in the standard libs, rather than a call for > more syntax. the problem with Haskell is that we need to split C expression into several statements and explicitly specify execution order even when we know that it doesn't matter. ideally, it should be possible to define ++x = modifyIORef x (+1) >> readIORef x *x = readIORef x and know that ghc will automatically generate temporary variables for results of monadic operations, understand the code and optimize it the sole reason why it's required for me is writing imperative software. while some purists may believe that haskell doesn't need imperative code, it's part of my program/libs and i want to have simple and concise representation for it -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From ithika at gmail.com Fri Aug 3 10:18:32 2007 From: ithika at gmail.com (Dougal Stanton) Date: Fri Aug 3 10:10:52 2007 Subject: [Haskell-cafe] When is waitForProcess not necessary? In-Reply-To: <46B32FC7.4050700@serpentine.com> References: <2d3641330708030128s51d644adpc167eb282c1fa22e@mail.gmail.com> <46B32FC7.4050700@serpentine.com> Message-ID: <2d3641330708030718j6d12730bp225e4793276b525b@mail.gmail.com> On 03/08/07, Bryan O'Sullivan wrote: > Pardon me while I veer off-topic, but you could also use Pandoc to do > this. No forking required. > http://sophos.berkeley.edu/macfarlane/pandoc/ I'll add that to the list of "things that must be done". That list seems, necessarily, to be longer than any list "things I have done". Last time I looked at PanDoc the docs gave the impression it was not very complete. It looks a lot better now. The idea of LaTeX embedded in Markdown sounds awesome... D. From dpiponi at gmail.com Fri Aug 3 10:37:45 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Fri Aug 3 10:29:59 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: <46B2E211.6080400@jellybean.co.uk> References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> <46B2E211.6080400@jellybean.co.uk> Message-ID: <625b74080708030737v55ff4fe0n3e3ee124f483427c@mail.gmail.com> On 8/3/07, Jules Bean wrote: > do > a <- m > b <- n > l a x b y > > becomes > > l (<- m) x (<- n) y Couldn't this be best done with McBride and Patterson's Applicative idiom notation? So the above would become [[l m (pure x) n (pure y)]] (or something like that) It would have the advantage of being usable with any Applicative, not just Monads. -- Dan From jules at jellybean.co.uk Fri Aug 3 10:39:16 2007 From: jules at jellybean.co.uk (Jules Bean) Date: Fri Aug 3 10:31:34 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: <625b74080708030737v55ff4fe0n3e3ee124f483427c@mail.gmail.com> References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> <46B2E211.6080400@jellybean.co.uk> <625b74080708030737v55ff4fe0n3e3ee124f483427c@mail.gmail.com> Message-ID: <46B33E14.7010006@jellybean.co.uk> Dan Piponi wrote: > On 8/3/07, Jules Bean wrote: >> do >> a <- m >> b <- n >> l a x b y >> >> becomes >> >> l (<- m) x (<- n) y > > Couldn't this be best done with McBride and Patterson's Applicative > idiom notation? > > So the above would become > > [[l m (pure x) n (pure y)]] (or something like that) > > It would have the advantage of being usable with any Applicative, not > just Monads. Well that's exactly the kind of discussion I was trying to generate. And I did give an applicative version when I replied to myself (although not admittedly full scale idiom brackets) Jules From dpiponi at gmail.com Fri Aug 3 10:46:03 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Fri Aug 3 10:38:19 2007 Subject: [Haskell-cafe] Perfect example In-Reply-To: <200708022002.14755.jon@ffconsultancy.com> References: <200708022002.14755.jon@ffconsultancy.com> Message-ID: <625b74080708030746n112ba14boee79fb1463c5531a@mail.gmail.com> On 8/2/07, Jon Harrop wrote: > Any suggestions for a perfect example that uniquely demonstrates the benefits > of the Haskell language compared to other languages? For short and sweet, power series is a nice example. Try http://www.polyomino.f2s.com/david/haskell/hs/PowerSeries.hs.txt or http://www.cs.dartmouth.edu/~doug/powser.html. Makes nice use of laziness to allow power series to consume earlier members of the series to produce later ones. Power series 'reversion' has traditionally been a tricky thing to code up but it's almost trivial in Haskell. And power series for many transcendental functions can be implemented directly from defining differential equations. -- Dan From bayer at math.columbia.edu Fri Aug 3 10:51:43 2007 From: bayer at math.columbia.edu (Dave Bayer) Date: Fri Aug 3 10:44:13 2007 Subject: [Haskell-cafe] Re: When is waitForProcess not necessary? References: <2d3641330708030128s51d644adpc167eb282c1fa22e@mail.gmail.com> <46B32FC7.4050700@serpentine.com> Message-ID: Bryan O'Sullivan serpentine.com> writes: > Pardon me while I veer off-topic, but you could also use Pandoc to do > this. No forking required. > http://sophos.berkeley.edu/macfarlane/pandoc/ What I'm doing is neither Haskell nor Markdown specific; I allow any HTML markup filter that plays nice with the direct HTML I also write (a restriction I could easily drop), and I cooperate with language-specific library doc generators such as Haddock. For all the fuss one reads about Haskell-not-as-fast-as-C, it's amusing how sluggish Markdown.pl is. Someone should write a small BSD'd Haskell version as example code for programming in Haskell. I may, although I can't see myself writing anything called "SmartyPants". I admire pandoc and I allow its use as an alternative to Markdown.pl, as an external command. I don't want to link it into my code because * It is GPL'd and I'm writing BSD'd code * It is a library that does not come with GHC. * It is twice the length of my code so far. The Hackage/Cabal universe takes the perspective that one is a committed Haskell user, and one wants the same diversity of tools enjoyed, say, in the Perl universe. When one uses Haskell to write a tool whose use is standalone and not Haskell-specific, there's a very good chance that someone will come along and try to build it for a new platform, installing and using GHC for the first time in order to do so. The barrier to entry is easily doubled if one has to also figure out how to obtain libraries that do not come automatically with GHC. Plenty of us have the moxie to install a package like GHC for a single use, because we've heard that "hackers" can do such things easily, but we don't really want to join each treehouse. I've installed versions of, say, Perl, Python, Ruby, even if there was a possibly lame installation already present. Still, their package systems generally left me fuming. I know my audience; we mathematicians can be smart and incredibly stupid at the same time. From simonpj at microsoft.com Fri Aug 3 11:14:01 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Fri Aug 3 11:06:17 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: <625b74080708030737v55ff4fe0n3e3ee124f483427c@mail.gmail.com> References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> <46B2E211.6080400@jellybean.co.uk> <625b74080708030737v55ff4fe0n3e3ee124f483427c@mail.gmail.com> Message-ID: | Couldn't this be best done with McBride and Patterson's Applicative | idiom notation? | | So the above would become | | [[l m (pure x) n (pure y)]] (or something like that) | | It would have the advantage of being usable with any Applicative, not | just Monads. Does anyone have a pointer to a stand-alone description of "full-scale idiom notation". S From jules at jellybean.co.uk Fri Aug 3 11:24:56 2007 From: jules at jellybean.co.uk (Jules Bean) Date: Fri Aug 3 11:17:12 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> <46B2E211.6080400@jellybean.co.uk> <625b74080708030737v55ff4fe0n3e3ee124f483427c@mail.gmail.com> Message-ID: <46B348C8.2010901@jellybean.co.uk> Simon Peyton-Jones wrote: > Does anyone have a pointer to a stand-alone description of "full-scale idiom notation". http://www.haskell.org/haskellwiki/Idiom_brackets I think I've seen something more detailed but I don't know if it was in one of Conor's papers, or if it was personal conversation/ seminar... Jules From cdsmith at twu.net Fri Aug 3 11:26:28 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 11:18:42 2007 Subject: [Haskell-cafe] Re: Re: monad subexpressions References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> Message-ID: Neil Mitchell wrote: > We started with 4 suggestions, and as far as I can tell, are > left with only one (<- ...). > For the record, my comments on (<- ...) where not objections, but > merely "thoughts out loud", and I could certainly see myself using > that syntax in a day to day basis. Right, I definitely didn't read your post as objecting to the syntax. I do have concerns about it. In particular, the section-like syntax suggests to me (quite misleadingly) that it is somewhat self-contained. I find myself half expecting to be able to rewrite (mapM f xs) as (map (<- f) xs), or something like that. In other words, the syntax lies to me. At the moment, though, I can't think of anything better. -- Chris Smith From claus.reinke at talk21.com Fri Aug 3 11:29:32 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Fri Aug 3 11:21:51 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt> <785460922.20070803173640@gmail.com> Message-ID: <015501c7d5e3$1847ce40$14217ad5@cr3lt> >>> can you please rewrite *p++=*q++ in haskell? >> do { w p =<< r q; i p; i q } > > how about *Object.File.Line.CurPtr++ = *AnotherObject.File.Line.CurPtr++ ? ;) what's the difference?-) let p = Object.File.Line.CurPtr let q = AnotherObject.File.Line.CurPtr do { w p =<< r q; i p; i q } the other line-noise version i gave does't even need the lets to avoid duplicating long names: i Object.File.Line.CurPtr =: (r `ap1` i AnotherObject.File.Line.CurPtr) but this is rapidly approaching the level at which my brain calls for a separation of concerns. there are oneliners that make code more obvious, and there are oneliners that make code harder to read. and definitions of hard/obvious differ.. > the problem with Haskell is that we need to split C expression into > several statements and explicitly specify execution order even when we > know that it doesn't matter. ideally, it should be possible to define > > ++x = modifyIORef x (+1) >> readIORef x > *x = readIORef x apart from the prefix symbols (i used one-letter prefix names), you can (as i'm sure you know). and the point of my little exercise was to show that instead of doing the splitting by hand at each usage site, we can write lifting combinators that do the splitting behind the scenes. what gives haskell aspirations to be a fine imperative language is that its abstraction mechanisms work as well for imperative code as for functional code. claus From duncan.coutts at worc.ox.ac.uk Fri Aug 3 11:55:28 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Fri Aug 3 11:46:35 2007 Subject: [Haskell-cafe] Re: When is waitForProcess not necessary? In-Reply-To: References: <2d3641330708030128s51d644adpc167eb282c1fa22e@mail.gmail.com> <46B32FC7.4050700@serpentine.com> Message-ID: <1186156528.5989.215.camel@localhost> On Fri, 2007-08-03 at 14:51 +0000, Dave Bayer wrote: > The Hackage/Cabal universe takes the perspective that one is a committed > Haskell user, and one wants the same diversity of tools enjoyed, say, in > the Perl universe. When one uses Haskell to write a tool whose use is > standalone and not Haskell-specific, there's a very good chance that > someone will come along and try to build it for a new platform, installing > and using GHC for the first time in order to do so. The barrier to entry is > easily doubled if one has to also figure out how to obtain libraries that > do not come automatically with GHC. Plenty of us have the moxie to install > a package like GHC for a single use, because we've heard that "hackers" can > do such things easily, but we don't really want to join each treehouse. The plan/goal is for ghc and hopefully other implementations to come with cabal-install so that when you try and build your random cabal package it'll be able to download, build and install all the deps (without necessarily requiring root). So in the end you should not have to figure out all the deps yourself, it's just that at the moment we're kind of in an intermediate phase. Duncan From cdsmith at twu.net Fri Aug 3 12:09:49 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 12:02:07 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: Message-ID: apfelmus wrote: > I still think that this syntax extension has profound impact and is a > bad idea. Simon's and Neill's use case was the dreaded name-supply monad > where the order of effects really doesn't matter up to alpha-conversion. > The objection to that use case is that monads are not the right > abstraction for that, they're too general. I'm primarily interested in the two cases where one simply has no choice about the use of monads: and those are IO and STM. No, this is not purely functional programming then; but it has some very compelling advantages to Haskell's implementation of these, that I'm afraid are currently quite hidden behind the difficult syntax. Using something besides a monad is simply not an option. A lot of what I'm thinking about Haskell now comes from my experience in trying to teach it to new programmers (which in turn comes from it being lonenly to be the only person I talk to that knows Haskell). I'm quite convinced, right now, that one huge problem with adoption of Haskell has to do with this right here. If there's a way to get nice syntax without modifying the compiler, that is certainly an advantage; but I do see it as rather small compared to the goal of producing something that it rather simple to understand and use. I can explain desugaring rules for this idea in a short paragraph. The alternatives all seem to involve operators and functions that I've not used in about six months or more of moderate playing around with Haskell. Type class hacking is way over the top; other ideas seem reasonable to me, but I'm concerned they won't seem very reasonable to anyone with much less experience using Haskell than I've got. The other objection, though, and I'm quoting from a post in a past thread on this, is something like, "The more tiresome monads are, the more incentive you have to avoid them." Unfortunately, I'm afraid this cheapens work people are doing in making the necessary imperative parts of Haskell more useful and interesting. Making monads distasteful is not a reasonable goal. > > Also, I got so frustrated that I ended up abandoning some code > > recently because STM is, in the end, so darn hard to use as a > > result of this issue. I'd love to see this solved, and I'm quite > > eager to do it. > > This sounds suspicious, since the order of effects is of course > important in the STM monad. Can you post an example of code you intend > to abandon due to ugliness? I'd be astonished if there's no better way > to write it. I'll dig for it later if you like. The essence of the matter was a bunch of functions that looked something like this: foo = do b' <- readTVar b c' <- readTVar c d' <- readTvar d return (b' + c' / d') In other words, a string of readTVar statements, followed by one computation on the results. Each variable name has to be duplicated before it can be used, and the function is four lines long instead of one. It's true that order of effects *can* be important in monads like IO and STM. It's also true, though, that probably 50% of the time with IO, and 95% with STM, the order does not actually matter. Taking a hard-line approach on this and forcing a linear code structure is equivalent to ignoring what experience has taught in dozens of other programming languages. Can you think of a single widely used programming language that forces programmers to write linear one-line-per-operation code like this? IMO, Haskell gets away with this because STM and IO stuff isn't very common; and STM and IO will remain uncommon (and will instead be replaced by unsafe code written in Python or Ruby) as long as this is the case. I find it hard to speculate that Haskell programmers will understand the alternatives, but won't understand something like "monadic subexpressions are evaluated in the order of their closing parentheses". -- Chris Smith From claus.reinke at talk21.com Fri Aug 3 12:12:13 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Fri Aug 3 12:04:34 2007 Subject: [Haskell-cafe] monad subexpressions References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> Message-ID: <016d01c7d5e9$0eec4550$14217ad5@cr3lt> to illustrate why some of us are concerned about this extension, a few examples might help. consider: f (g (<- mx)) does this stand for (a) mx >>= \x-> f (g x) (b) f (mx >>= \x-> (g x)) (c) none of the above, because there's no do (d) something else entirely if (a/b), does the decision depend on the type of g (if g is pure, then (a), if g is monadic itself, then (b))? if (d), what? if (a/b), then this is no longer preprocessing, but depends on the types, which means that the type system must work in the presence of this extension, rather than its pre-processed form. if you want to avoid that, you're left with (c), but is that any better? if (c), then the following are no longer equivalent 1. return ... 2. do return ... in particular, do return .. is no longer a unit of the monad (in (a/b), even return .. isn't). so if you write f (do g (<- mx)) you mean (b), while if you write do f (g (<- mx)) you mean (a), and if you write f (g (<- mx)) you mean either an error, if there is no surrounding 'do', or something else, if there is a surrounding 'do'. and woe to those who think they can insert some 'do' notation whereever they like - they need to check the subexpressions for (<-) first! now, consider nesting monadic subexpressions: f (<- g (<- mx)) surely means the same as f =<< (g =<< mx), namely mx >>= \x-> g x >>= \gx-> f gx right? wrong! we forgot the 'do'. without a 'do'-context, this means nothing in (c). so if you have do .. fx <- f (<- g (<- mx)) .. fx <- f (<- g (<- mx)) .. and there are no free variables, then you can do the usual sharing to improve readability, right? let fgmx = f (<- g (<- mx)) in do .. fx <- fgmx .. fx <- fgmx .. wrong again! this is syntax, not expression, so the latter variant changes the scope the (<-)s refer to (some outer 'do', if one exists). you could have written do let fgmx = f (<- g (<- mx)) .. fx <- fgmx .. fx <- fgmx .. perhaps, and at this stage you might no longer be surprised that do and let no longer commute. or were you? if you weren't, here's a quick question: we've already seen the left- and right-identity laws in danger, so what about associativity? do { do { a; b}; c } is still the same as do { a; do { b; c } } yes? no? perhaps? sometimes? how long did it take you? could someone please convince me that i'm painting far too gloomy a picture here?-) claus From simonpj at microsoft.com Fri Aug 3 12:29:15 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Fri Aug 3 12:21:29 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: <016d01c7d5e9$0eec4550$14217ad5@cr3lt> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> Message-ID: | f (g (<- mx)) | | does this stand for | | (a) mx >>= \x-> f (g x) | (b) f (mx >>= \x-> (g x)) | (c) none of the above, because there's no do | (d) something else entirely For me the answer is definitely (c). Furthermore there must be no lambda between the "monadic splice" and the "do". Given that, I think the meaning of a monadic splice is straightforward, and all your excellent questions have easy answers. The question remains of whether or not it's valuable. Simon From cdsmith at twu.net Fri Aug 3 12:56:01 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 12:48:49 2007 Subject: [Haskell-cafe] Re: Re: monad subexpressions References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> Message-ID: Neil Mitchell wrote: > Thinking on the semantic issue for the moment: > > Can you use (<-) outside of a do block? Good question, but my answer is a strong no! Syntactic sugar for monads has always been tied to do blocks; promoting it outside of contexts where "do" announces that you'll be using syntactic sugar seems like a very bad idea. > do b >> f (<- a) > > where does the evaluation of a get lifted to? I think it's rather clear that a gets moved before b. The example is confusing because the code is bad; not because of any new problems with this proposal. > Given: > > if (<- a) then f (<- b) else g (<- c) > > Do b and c both get monadic bindings regardless of a? This is tougher, but I'd say yes. In this case, you've chosen not to give "then" and "else" clauses their own do block, so this would evaluate both. Certainly if/then could be made a special case... but it would be exactly that. i.e., if I did this: cond b th el = if b then th else el do cond (<- a) (f (<- b)) (g (<- c)) Then you'd lose. And the fact that you'd still lose there makes me less than thrilled to mislead people by special-casing if/then/else. When something is dangerous, it should be labelled as such as loudly talked about; but covered up in the hopes that no one will dig deep enough to hurt themselves. > if (<- a) then do f (<- b) else g (<- c) > > Does this change to make b bound inside the then, but c bound outside? > Does this then violate the rule that do x == x Then yes, it would. > Can you combine let and do? > > do let x = (<- a) > f x Right. In effect, as a matter of fact, the notation x <- a would become equivalent to let x = (<- a) > Our "best guess" is that all monadic bindings get floated to the > previous line of the innermost do block, in left-to-right order. > Monadic expressions in let statements are allowed. Outside a do block, > monadic subexpressions are banned. Sure. SPJ mentioned that you wouldn't promote (<- x) past a lambda. I'm not convinced (it seems to fall into the same category as the if statement), but it's worth considering. -- Chris Smith From george.moschovitis at gmail.com Fri Aug 3 12:57:27 2007 From: george.moschovitis at gmail.com (George Moschovitis) Date: Fri Aug 3 12:49:40 2007 Subject: [Haskell-cafe] Haskell FCGI server. Message-ID: Dear devs, is it possible to create a FCGI server that listens to a specific port using the Haskell FCGI library? The front end web server would then communicate with this back end FCGI server through this port. A small example would be really appreciated. thanks, George. -- http://nitroproject.org http://phidz.com http://blog.gmosx.com http://cull.gr http://www.joy.gr http://www.me.gr -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070803/cf41908f/attachment.htm From ndmitchell at gmail.com Fri Aug 3 13:04:31 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Fri Aug 3 12:56:45 2007 Subject: [Haskell-cafe] Re: Re: monad subexpressions In-Reply-To: References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> Message-ID: <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> Hi > > Can you combine let and do? > > > > do let x = (<- a) > > f x > > Right. In effect, as a matter of fact, the notation > > x <- a > > would become equivalent to > > let x = (<- a) Hmm, interesting. Consider: let x = 12 let x = (<- x) Currently, in let x = ... the x is in scope on the right hand side. Now it isn't. Changing the order of evaluation with syntactic sugar seems fine, changing the lexical scoping seems nasty. Perhaps this is a reason to disallow monadic expressions in a let. > > Our "best guess" is that all monadic bindings get floated to the > > previous line of the innermost do block, in left-to-right order. > > Monadic expressions in let statements are allowed. Outside a do block, > > monadic subexpressions are banned. > > Sure. SPJ mentioned that you wouldn't promote (<- x) past a lambda. > I'm not convinced (it seems to fall into the same category as the if > statement), but it's worth considering. I'm not convinced either, a nice concrete example would let people ponder this a bit more. What is nice to note is that all your answers to my questions matched perfectly with what I thought should happen. Thanks Neil From darrelll at amgen.com Fri Aug 3 13:11:37 2007 From: darrelll at amgen.com (Lewis-Sandy, Darrell) Date: Fri Aug 3 13:03:54 2007 Subject: [Haskell-cafe] Question about arrows Message-ID: <567ACB2E39C83543B746F1AD7F5E5E040BFEE8B0@wa-mb2-sea.amgen.com> Is there a class property of the Control.Arrow class that represents the evaluatation of an arrow: eval :: (Arrow a)=>a b c->b->c I am writing some higher order code that I would like to work with either functions or partial functions (implemented as balanced binary search trees) and don't want to write separate instances for each concrete arrow type. For example, consider the example below: divideAndConquer::( Arrow a, Bifunctor m)=>(m c y->y)->a b c->(x->m b x)->x->y divideAndConquer combine solve divide = combine.(bimap (eval solve) (divideAndConquer combine solve divide)).divide that implements datatype generic divide and conquer. divide encodes how to decompose a problem of type x into subproblems, solve encodes how to solve indivisible sub-problems, and combine encodes how to put the sub-solutions together. The branching strategy is encoded in the bifunctor, and the use of eval faciliatates either evaluating a function or looking up solutions in a table. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070803/d6b27d8c/attachment.htm From trevion at gmail.com Fri Aug 3 13:32:07 2007 From: trevion at gmail.com (J. Garrett Morris) Date: Fri Aug 3 13:24:20 2007 Subject: [Haskell-cafe] Question about arrows In-Reply-To: <567ACB2E39C83543B746F1AD7F5E5E040BFEE8B0@wa-mb2-sea.amgen.com> References: <567ACB2E39C83543B746F1AD7F5E5E040BFEE8B0@wa-mb2-sea.amgen.com> Message-ID: <6cf91caa0708031032mc33bf69jbb3d84059ea36451@mail.gmail.com> On 8/3/07, Lewis-Sandy, Darrell wrote: > > Is there a class property of the Control.Arrow class that represents the > evaluatation of an arrow: > > eval :: (Arrow a)=>a b c->b->c > There isn't because that type signature isn't valid in general. Consider the Kleisli arrows, for instance: how would you write eval :: Kleisli (State Int) Int Int -> Int -> Int? You need to get the initial state from somewhere... similar problems would exist for Kleisli IO Int Int. /g -- The man who'd introduced them didn't much like either of them, though he acted as if he did, anxious as he was to preserve good relations at all times. One never knew, after all, now did one now did one now did one. From cdsmith at twu.net Fri Aug 3 13:39:11 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 13:31:32 2007 Subject: [Haskell-cafe] RE: monad subexpressions References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> Message-ID: Simon Peyton-Jones wrote: > Furthermore there must be no lambda between the "monadic splice" and the "do". I'm curious about this. One could sugar: do tax <- getTax return $ map (\price -> price * (1 + tax)) bill into: do return $ map (\price -> price * (1 + (<- getTax))) someNums Do you not think this is desirable? Is there a negative side-effect that I'm not noticing? I sort of see this in the same boat as Neil's example with if/then/else. The meaning may not be precisely what you'd expect... but mind-reading is hard, and it's more consistent to just say "find the innermost containing do block" than make up new rules for each piece of syntax. Granted, a special case of "it's an error" is far more appealing than the corresponding special case for if; but I don't yet see a reason for this exception to the rule either. -- Chris Smith From lgreg.meredith at biosimilarity.com Fri Aug 3 14:11:59 2007 From: lgreg.meredith at biosimilarity.com (Greg Meredith) Date: Fri Aug 3 14:04:16 2007 Subject: RE [Haskell-cafe] Monad Description For Imperative Message-ID: <5de3f5ca0708031111j2e16ed8bjf5d07436333b1743@mail.gmail.com> Haskellians, i am delighted to see vigorous exchange that actually resulted in change of positions. i confess i was going to give up, but glad others stepped into the breach. This is yet another indication of what an unusual community this is. Best wishes, --greg Date: Fri, 3 Aug 2007 13:43:32 +1200 From: ok Subject: Re: RE [Haskell-cafe] Monad Description For Imperative To: haskell-cafe Cafe Message-ID: <8575BD1C-2113-4D48-A3D4-BDFF41238BB9@cs.otago.ac.nz> Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed I asked "How is IO a functor"? On 3 Aug 2007, at 11:50 am, Dan Piponi wrote: > IO is a fully paid up Monad in the categorical sense. The category is > the category whose objects are types and whose arrows are functions > between those types. IO is a functor. The object a maps to IO a. An > arrow f::a->b maps to (>>= return . f)::IO a -> IO b and that can be > used to make IO an instance of Functor. The natural transforms eta and > mu are called return and join. Please go over this again, but slowly this time. You have convinced me, but I'd like to understand the details a little better. I see that any type constructor TC :: * -> * is halfway to being a functor on this category of types. It acts on the objects in the obvious way, so the next step is to see about the arrows. If f :: a -> b then we want TC f :: TC a -> TC b such that TC (f . g) = TC f . TC g and TC (id::a->a) = id :: TC a -> TC a Now this is precisely the Haskell Functor class, so TC is the object part and fmap is the arrow part. You say that (>>= return . f) can be used to make [a Monad] an instance of Functor. Try it... by golly it's true. I see: fmap f = (>>= return . f). So why *aren't* Monads already set up using the type class machinery to always *be* Functors in Haskell? Isn't it bound to confuse people if monads are functors but Monads are not Functors? This is especially puzzling because Maybe, [], and IO already *are* Functors, but the way this is done makes it look accidental, not like the fundamental property of Monads it apparently is. (By the way, I note that the on-line documentation for Control.Monad glosses >>= as "Sequentially composes two actions...".) -- L.G. Meredith Managing Partner Biosimilarity LLC 505 N 72nd St Seattle, WA 98103 +1 206.650.3740 http://biosimilarity.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070803/8ce629ce/attachment-0001.htm From sebastian.sylvan at gmail.com Fri Aug 3 14:14:48 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Fri Aug 3 14:07:02 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: Message-ID: <3d96ac180708031114i2f1ab07awc9e98897648aa491@mail.gmail.com> On 03/08/07, apfelmus wrote: > Chris Smith wrote: > > Also, I got so frustrated that I ended up abandoning some code > > recently because STM is, in the end, so darn hard to use as a > > result of this issue. I'd love to see this solved, and I'm quite > > eager to do it. > > This sounds suspicious, since the order of effects is of course > important in the STM monad. Can you post an example of code you intend > to abandon due to ugliness? I'd be astonished if there's no better way > to write it. Just because order *technically* matters doesn't mean it *actually* matters in a given circumstance: mytransaction = do { x0 <- readTVar xvar0 x1 <- readTVar xvar1 : xn <- readTVar xvarn return $ foo x0 x1 .. xn } Versus mytransaction = return $ foo $(readTVar xvar0) $(readTVar xvar1) .. $(readTVar xvarn) Now I'm not to happy about the long names for reading variables either, short overloaded names like "get" and "put" would look much nicer in this example, and in other places too. And certainly, sometimes you do want to name things for convenience. But in *lots* of cases you just want to e.g. read N variables, in an arbitrary order, and then do something with them. Yes the order matters to the *compiler*, but it doesn't always matter to the *programmer*, so to have a more convenient way to express those cases would be very nice, IMO. And there may even be cases where the order does matter but you'd be happy with a left-to-right ordering. This has been a pet-peeve of mine for ages. Imperative programming in Haskell is neat, but I really don't want to write what amounts to almost assembly programming levels of explicitness for simple tasks. I'd also like to reiterate my request for a notation that doesn't require brackets around the *action* but will also work by applying it to a function which when fully applied to its argument returns an action (i.e.: $foo x y + $bar z w, rather than $(foo x y) + $(bar z w)). Function application is normally very low-noise in Haskell (good), and it would be nice if we can keep it low-noise in this notation too. Maybe $ isn't a good operator though.. How about #? Maybe using angle brackets would work.. I'd still like to have them work for functions returning actions though ( x y + z w ). Wonder what that would do to ordering comparisons, lexically speaking.... -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From cdsmith at twu.net Fri Aug 3 14:36:30 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 14:28:49 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> Message-ID: Claus Reinke wrote: > to illustrate why some of us are concerned about this extension, > a few examples might help. Claus, I've been saving your message in order to respond to it when I have the time to look over it in detail. I don't think there will be forthcoming answers from me, though. Ultimately, it may just have to come down to implementing the extension, making it available as an extension to GHC and perhaps other Haskell compilers, and then learning from people's experience. If there is a really good syntax that avoids the need for language changes, that would be great. If there's one that's clearly good enough and pops up before I finish this, then I may even abort the work. As it stands, though, I'm just not sure how to evaluate ideas without language changes against an alternative that doesn't exist. This is especially true when we're talking about non-quantifiable ideas like convenience, readability, and intuitiveness. As such, I'm happy to pursue the language change route, so that we'll have a real implementation and a fully developed idea, instead of a theory to discuss. I suspect it will then be more productive to talk about the options, such as whether the language change is really needed or beneficial. Neil and I just discussed some of the semantic issues you raise here in another subthread. Some of them are not quite as intuitive as I'd like, but the meaning is at least well-defined. As for this thread, yes I agree with Simon that it's necessary to choose your "option c" and tie any new syntax rather tightly to the 'do' keyword; anything else involves becoming a mind-reader. > if (c), then the following are no longer equivalent > > 1. return ... > 2. do return ... Yes, that is true. > if you weren't, here's > a quick question: we've already seen the left- and right-identity > laws in danger, so what about associativity? > > do { do { a; b}; c } > > is still the same as > > do { a; do { b; c } } > > yes? no? perhaps? sometimes? how long did it take you? I'm not entirely sure I understand the point here. The monad laws are defined in terms of >>= and return. They have never had anything to do with do, let, or <-. All of the monad laws still hold. -- Chris Smith From cdsmith at twu.net Fri Aug 3 14:39:55 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 14:32:15 2007 Subject: [Haskell-cafe] Re: Re: monad subexpressions References: <3d96ac180708031114i2f1ab07awc9e98897648aa491@mail.gmail.com> Message-ID: Sebastian Sylvan wrote: > I'd also like to reiterate my request for a notation that doesn't > require brackets around the *action* but will also work by applying it > to a function which when fully applied to its argument returns an > action (i.e.: $foo x y + $bar z w, rather than $(foo x y) + $(bar z > w)). Function application is normally very low-noise in Haskell > (good), and it would be nice if we can keep it low-noise in this > notation too. I'm trying to understand your suggestion. Can you tell me how you'd sugar the following? getA :: Friggle MyA getB :: Friggle MyB foo :: Int -> MyB -> Friggle MyC do a <- getA b <- getB a foo 42 b -- Chris Smith From dpiponi at gmail.com Fri Aug 3 14:40:40 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Fri Aug 3 14:32:53 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> <46B2E211.6080400@jellybean.co.uk> <625b74080708030737v55ff4fe0n3e3ee124f483427c@mail.gmail.com> Message-ID: <625b74080708031140s10d6ea9cv5629784a8936734d@mail.gmail.com> On 8/3/07, Simon Peyton-Jones wrote: > | Couldn't this be best done with McBride and Patterson's Applicative > | idiom notation? > Does anyone have a pointer to a stand-alone description of "full-scale idiom notation". > S The full paper is here: http://www.cs.nott.ac.uk/~ctm/Idiom.pdf Is that what you want? It would be sweet to have the generality of Applicatives. I find the examples of vectorised arithmetic and expression evaluators in that paper quite compelling, besides the use of Applicatives as an alternative way to talk to monads. -- Dan From claus.reinke at talk21.com Fri Aug 3 14:47:20 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Fri Aug 3 14:39:43 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <3d96ac180708031114i2f1ab07awc9e98897648aa491@mail.gmail.com> Message-ID: <01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> > mytransaction = do { > x0 <- readTVar xvar0 > x1 <- readTVar xvar1 > : > xn <- readTVar xvarn > return $ foo x0 x1 .. xn > } > > Versus > > mytransaction = return $ foo $(readTVar xvar0) $(readTVar xvar1) .. > $(readTVar xvarn) ah, a concrete example. but isn't that the typical use case for ap? mytransaction = foo `liftM` r xvar0 `ap` r xvar1 .. where r = readTVar claus From ndmitchell at gmail.com Fri Aug 3 14:52:02 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Fri Aug 3 14:44:15 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> Message-ID: <404396ef0708031152t2e9c270ejb79ddeca5365dfe2@mail.gmail.com> Hi > > do { do { a; b}; c } > > > > is still the same as > > > > do { a; do { b; c } } > > > > yes? no? perhaps? sometimes? how long did it take you? > > I'm not entirely sure I understand the point here. The monad laws are > defined in terms of >>= and return. They have never had anything to do > with do, let, or <-. All of the monad laws still hold. The Monad laws have never been defined in terms of do notation, but they have always held with do notation since it was simply basic sugar for >> and >>=. Now do notation is no longer as simple, and the laws do not hold on do, only on the desugared version. We have lost the ability to manipulate do quite as easily, and gained a more compact expression of monadic actions. I think the trade off is worth it, but others may not. Thanks Neil From droundy at darcs.net Fri Aug 3 15:13:18 2007 From: droundy at darcs.net (David Roundy) Date: Fri Aug 3 15:05:35 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <46B32261.1070807@ira.uka.de> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> Message-ID: <20070803191318.GJ20161@darcs.net> On Fri, Aug 03, 2007 at 02:41:05PM +0200, Mirko Rahn wrote: > >>>rewrite *p++=*q++ in haskell? > > >it's one of C idioms. probably, you don't have enough C experience to > >understand it :) > > Maybe, but how can *you* understand it, when the standard is vague about it? > > It could be > > A: *p=*q; p+=1; q+=1; > B: *p=*q; q+=1; p+=1; > C: tp=p; tq=q; p+=1; q+=1; *tp=*tq; > > ...and so on. Which is the "right" version? Isn't that the point? It's buggy code if *q == p or *p == q, or a few other cases perhaps, but if those are not the case, then all of those are "right," and the compiler has the choice to implement whichever it deems most efficient. In the cases where this is actually used, all three of those are correct, the code is understandable, compact and unambiguous. -- David Roundy Department of Physics Oregon State University From dav.vire+haskell at gmail.com Fri Aug 3 15:26:22 2007 From: dav.vire+haskell at gmail.com (david48) Date: Fri Aug 3 15:18:35 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> Message-ID: <4c88418c0708031226w7fc9e264gd9a1647b57568fea@mail.gmail.com> On 8/3/07, Neil Mitchell wrote: This is how I understand it: > Can you use (<-) outside of a do block? > b >> f (<- a) b >> do { ta <-a; f ta } or b >> a >>= \ta -> f ta > What are the semantics of > do b >> f (<- a) do b >> a >>= \ta -> f ta > Given: > > if (<- a) then f (<- b) else g (<- c) a >>= \ta -> if (ta) then ( b >>= \tb -> f tb ) else ( c >>= \tc -> f tc ) > do let x = (<- a) > f x No idea if that could be possible. or maybe : do a >>= \ta -> let x = ta in f x _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From dav.vire+haskell at gmail.com Fri Aug 3 15:48:05 2007 From: dav.vire+haskell at gmail.com (david48) Date: Fri Aug 3 15:40:18 2007 Subject: [Haskell-cafe] Re: Re: monad subexpressions In-Reply-To: <4c88418c0708031245o7712911aob8e7231084c2de4b@mail.gmail.com> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> <4c88418c0708031245o7712911aob8e7231084c2de4b@mail.gmail.com> Message-ID: <4c88418c0708031248j98b5268g9aa5abea344864a3@mail.gmail.com> Sorry for the double post, I posted with the wrong email address and haskell-cafe rejected it. On 8/3/07, Neil Mitchell wrote: > > Right. In effect, as a matter of fact, the notation > > > > x <- a > > > > would become equivalent to > > > > let x = (<- a) > > Hmm, interesting. Consider: > > let x = 12 > let x = (<- x) Wouldn't that be forbidden ? I'd expect the x in ( <- x ) have to be of type m a. If you meant : x <- return 12 let x = ( <- x ) Then I imagine it would turn into x <- return 12 x >>= \tx -> let x = tx in .... Isn't that correct ? From cdsmith at twu.net Fri Aug 3 15:55:21 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 15:47:40 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> <4c88418c0708031245o7712911aob8e7231084c2de4b@mail.gmail.com> <4c88418c0708031248j98b5268g9aa5abea344864a3@mail.gmail.com> Message-ID: david48 wrote: > On 8/3/07, Neil Mitchell wrote: > > > > Hmm, interesting. Consider: > > > > let x = 12 > > let x = (<- x) > > Wouldn't that be forbidden ? > > I'd expect the x in ( <- x ) have to be of type m a. > Yes, unless of course you did: instance (Monad m, Num n) => Num (m n) or some such nonsense. :) > If you meant : > > x <- return 12 > let x = ( <- x ) This would be equally wrong. Perhaps you meant: do let x = return 12 let x = (<- x) ... Then this would become: do let x = return 12 t1 <- x let x = t1 ... Which is, in turn: let x = return 12 in x >>= (\t1 -> let x = t1 in ...) -- Chris Smith From cdsmith at twu.net Fri Aug 3 16:01:14 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 15:53:30 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> Message-ID: Neil Mitchell wrote: > > Right. In effect, as a matter of fact, the notation > > > > x <- a > > > > would become equivalent to > > > > let x = (<- a) > > Hmm, interesting. Consider: > > let x = 12 > let x = (<- x) Okay, so the desugaring process wouldn't terminate in that case! One could either: (a) try to retain the equivalence in theory, but make it illegal to use x in a monadic subexpression when defining x; (b) we could abandon my claim that they are equivalent. > I'm not convinced either, a nice concrete example would let people > ponder this a bit more. I tried to provide something in my response to Simon. Here it is again: One could sugar: do tax <- getTax return $ map (\price -> price * (1 + tax)) bill into: do return $ map (\price -> price * (1 + (<- getTax))) someNums > What is nice to note is that all your answers > to my questions matched perfectly with what I thought should happen. That is nice. I'm still very uncomfortable with the <- syntax (a complete flip for me since this morning!); and a little uneasy about the use of case, if, lambdas, etc. Time to keep thinking, I guess. I'd like to take Simon's suggestion and do a wiki page about this; but it should probably be on the Haskell prime wiki, no? I'm not entirely clear on how to get an account there. I could add it to HaskellWiki, but I think that would be the wrong place for it. -- Chris Smith From zednenem at psualum.com Fri Aug 3 16:07:46 2007 From: zednenem at psualum.com (David Menendez) Date: Fri Aug 3 15:59:59 2007 Subject: FW: RE [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: References: <625b74080708011357o5c85a0e9m71cd832e7d55a59b@mail.gmail.com> Message-ID: <49a77b7a0708031307o4127ee40qd428229c53a2d804@mail.gmail.com> On 8/1/07, Jeff Polakow wrote: > >But what about an actual object of type 'IO > > Int', say? > > > I usually describe the type resulting from applying a monad a computation. Same here. If "m" is a monad, then "m a" is a computation. (Of course, computations are first-class values, like functions.) I've occasionally called functions of type "a -> m b" monadic functions, but I suspect that's poor style. I wonder how much of the confusion surrounding monads comes from the fact that using them in Haskell involves higher-order functions, type constructors, and type constructor classes. From bulat.ziganshin at gmail.com Fri Aug 3 16:09:09 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Fri Aug 3 16:10:08 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: <016d01c7d5e9$0eec4550$14217ad5@cr3lt> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> Message-ID: <348929336.20070804000909@gmail.com> Hello Claus, Friday, August 3, 2007, 8:12:13 PM, you wrote: > f (g (<- mx)) > does this stand for > (a) mx >>= \x-> f (g x) this variant. just like any imperative language (are you used any?). idea of FORmula TRANslator is old and widely used enough to prevent such questions -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From bulat.ziganshin at gmail.com Fri Aug 3 16:06:54 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Fri Aug 3 16:10:13 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: Message-ID: <1092013784.20070804000654@gmail.com> Hello Chris, Friday, August 3, 2007, 8:09:49 PM, you wrote: > foo = do b' <- readTVar b > c' <- readTVar c > d' <- readTvar d > return (b' + c' / d') > It's true that order of effects *can* be important in monads like IO and > STM. It's also true, though, that probably 50% of the time with IO, and 90%, in my programs at least > 95% with STM, the order does not actually matter. Taking a hard-line > approach on this and forcing a linear code structure is equivalent to > ignoring what experience has taught in dozens of other programming > languages. Can you think of a single widely used programming language > that forces programmers to write linear one-line-per-operation code like > this? assembler :) it's what our opponents propose - let's Haskell be like assembler with its simple and concise execution model :) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From josef.svenningsson at gmail.com Fri Aug 3 16:22:37 2007 From: josef.svenningsson at gmail.com (Josef Svenningsson) Date: Fri Aug 3 16:14:51 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions In-Reply-To: References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> Message-ID: <8dde104f0708031322w3ddfed8ej931cd912ddae3b7f@mail.gmail.com> On 8/3/07, Chris Smith wrote: > Neil Mitchell wrote: > > I'm not convinced either, a nice concrete example would let people > > ponder this a bit more. > > I tried to provide something in my response to Simon. Here it is again: > > One could sugar: > > do tax <- getTax > return $ map (\price -> price * (1 + tax)) bill > > into: > > do return $ map (\price -> price * (1 + (<- getTax))) someNums > I think what Simon is worried about here is that the syntax in the latter expression suggests that the effects of getTax will be performed every time the lambda is applied. After all getTax appears inside the lambda. But in fact is the side effects will only be performed once. I agree with Simon that (<- getTax) shouldn't be promoted outside a lambda. Fwiw, I'm all in favor for some new piece of syntax for this problem. Cheers, Josef From apfelmus at quantentunnel.de Fri Aug 3 16:22:53 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Fri Aug 3 16:15:25 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> Message-ID: Chris Smith wrote: > I'm primarily interested in the two cases where one simply has no > choice about the use of monads: and those are IO and STM. > No, this is not purely functional programming then; but it has > some very compelling advantages to Haskell's implementation of > these, that I'm afraid are currently quite hidden behind the > difficult syntax. Using something besides a monad is simply not > an option. > > "The more tiresome monads are, the more incentive you have to > avoid them." Unfortunately, I'm afraid this cheapens work people > are doing in making the necessary imperative parts of Haskell > more useful and interesting. Making monads distasteful is not a > reasonable goal. > > Can you think of a single widely used programming language > that forces programmers to write linear one-line-per-operation code > like this? IMO, Haskell gets away with this because STM and IO stuff > isn't very common; and STM and IO will remain uncommon (and will > instead be replaced by unsafe code written in Python or Ruby) as > long as this is the case. I mean it in the following way: the power of Haskell is that a large core of pure functions does the actual algorithmic work and is surrounded by a small layer of imperative code. It's not possible to avoid the small layer of imperative code, of course. But the more you treat imperative code as somewhat pure, the greater the danger that the purely functional logic will be buried inside a mess of imperative code. In other words, the goal is exactly to make IO and STM uncommon, otherwise you loose the power the purely functional approach offers. What I want to say is: if you feel the urge to use the monad splicing syntax, then I think that there's a big chance that the code you write is in essence pure and can also be made completely pure. That's why I'd like to see the code that made you give up. It may require much more pondering to find a pure abstraction to the programming problem at hand. But once found, it bests any ad-hoc code. For example, take the HGL (Haskell Graphics Library) which actually shows the boundary between pure and monad. The main abstraction is the type Graphic that represents a graphic to be drawn on the screen. It's implemented with a monad Draw a with in turns does IO to draw itself on the screen. But the abstraction is to treat this as a purely functional value with operations like emptyGraphic :: Graphic polygon :: [Point] -> Graphic overGraphic :: Graphic -> Graphic -> Graphic to create and compose graphics. To draw a graphic, you have to use IO. But his is no reason not to offer a pure abstraction even if the internals are littered with IO. HGL still exports the Draw monad type Graphic = Draw () and I consider this a sin. It only appears as monad in the three functions selectBrush :: Brush -> Draw Brush selectPen :: Pen -> Draw Pen selectFont :: Font -> Draw Font which exist to enable the user to hand-optimize a bit since brush, font and pen creation is expensive on Win32. But arguably, these optimizations can be performed automatically under the hood. An interesting example of how a purely functional data structure makes life much easier is described in N. Ramsey and J. Dias. An Applicative Control-Flow Graph Based on Huet's Zipper http://www.eecs.harvard.edu/~nr/pubs/zipcfg-abstract.html We are using ML to build a compiler that does low-level optimization. To support optimizations in classic imperative style, we built a control-flow graph using mutable pointers and other mutable state in the nodes. This decision proved unfortunate: the mutable flow graph was big and complex, and it led to many bugs. We have replaced it by a smaller, simpler, applicative flow graph based on Huet's (1997) zipper. The new flow graph is a success; this paper presents its design and shows how it leads to a gratifyingly simple implementation of the dataflow framework developed by Lerner, Grove, and Chambers (2002). That being said, it is of course desirable to be able to describe genuinely imperative behavior like resource (de-)allocation elegantly in Haskell. Not everything can be pure :) (or rather :( ). But I'm not sure whether the linearization imposed is really an issue then. > Ultimately, it may just have to come down to implementing the > extension, making it available as an extension to GHC and perhaps > other Haskell compilers. > > As it stands, though, I'm just not sure how to evaluate ideas > without language changes against an alternative that doesn't exist. Hm, it seems slightly unfair to me to leave the burden of searching for an alternative to somebody else. > I can explain desugaring rules for this idea in a short paragraph. > The alternatives all seem to involve operators and functions that I've > not used in about six months or more of moderate playing around with > Haskell. In fact, applicative functors are a very useful and powerful abstraction and to some extend, they exactly solve the problem of programming with monads in an applicative style. I would be sad if you'd ignore them in case they solve your STM-code problem without compiler extension. Regards, apfelmus From westondan at imageworks.com Fri Aug 3 16:25:43 2007 From: westondan at imageworks.com (Dan Weston) Date: Fri Aug 3 16:17:56 2007 Subject: [Haskell-cafe] monad subexpressions In-Reply-To: <46B2E971.5040307@jellybean.co.uk> References: <404396ef0708021756k74171c5elbb69f7c9ff157e6e@mail.gmail.com> <46B2E211.6080400@jellybean.co.uk> <46B2E971.5040307@jellybean.co.uk> Message-ID: <46B38F47.80201@imageworks.com> Jules Bean wrote: > do > a <- m > b <- n > l a x b y > > becomes > > l (<- m) x (<- n) y > > ...with, I suppose, left-to-right evaluation order. This looks 'almost > like substitution' which is the goal. Almost? So then (flip f) (<- m) (<- n) does *not* equal f (<- n) (<- m) ? There goes any hope of my understanding future Haskell code. (<- n) sure looks like an operator section to me, and more importantly a first class Haskell object. What human parsing this would not see a mere function application? And I guess this makes the following complete nonsense: do let a = (<- m) let b = (<- n) l a x b y What about do let (b,a) = ((<- n),(<- m)) -- many lines of code l a x b y Who can say that b was evaluated before a? I hope the language syntax does not evolve beyond my merely mortal ability to desugar it? Dan Weston From claus.reinke at talk21.com Fri Aug 3 16:30:14 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Fri Aug 3 16:22:32 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: Message-ID: <026701c7d60d$1a399a10$14217ad5@cr3lt> > I'll dig for it later if you like. The essence of the matter was a > bunch of functions that looked something like this: > > foo = do b' <- readTVar b > c' <- readTVar c > d' <- readTvar d > return (b' + c' / d') > > In other words, a string of readTVar statements, followed by one > computation on the results. Each variable name has to be duplicated > before it can be used, and the function is four lines long instead of > one. if that happens frequently, an instance of the numeric classes seems called for, automating both the lifting and the readTVar, but if there are only a couple of cases, you could lift the operations for the module, or even per definition: foo1 b c d = readTVar b + readTVar c / readTVar d where (+) = liftM2 (Prelude.+) (/) = liftM2 (Prelude./) claus From cdsmith at twu.net Fri Aug 3 16:38:15 2007 From: cdsmith at twu.net (Chris Smith) Date: Fri Aug 3 16:30:42 2007 Subject: [Haskell-cafe] Re: Re: monad subexpressions References: <1092013784.20070804000654@gmail.com> Message-ID: Bulat Ziganshin wrote: > assembler :) it's what our opponents propose - let's Haskell be like > assembler with its simple and concise execution model :) I feel bad that portions of this thread have gotten a bit ugly. I don't have any opponents, so far as I know. I am just trying to discuss the best way to solve this problem. -- Chris Smith From ndmitchell at gmail.com Fri Aug 3 16:42:41 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Fri Aug 3 16:34:55 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions In-Reply-To: References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> Message-ID: <404396ef0708031342x7af7ab6fq77e377152f828841@mail.gmail.com> Hi > > let x = 12 > > let x = (<- x) > > Okay, so the desugaring process wouldn't terminate in that case! One > could either: (a) try to retain the equivalence in theory, but make it > illegal to use x in a monadic subexpression when defining x; (b) we > could abandon my claim that they are equivalent. This example isn't intended to be about termination of the desugaring, or about types etc - the only point is to note the change in the lexical scoping rules that (<-) gives. I'll try and state my concern more clearly: let x = a In this expression, x is available for use within a, since let is recursive. This allows us to write: let xs = "paws" : xs With the end result that xs is bound to ["paws","paws","paws","paws"... Now consider: let x = (<- a) With the proposed desugaring we obtain: temp <- a let x = temp Now x is NOT in scope within the expression a! We have changed the static lexical scoping, and only within the brackets. This behaviour is (in my opinion) horrid. A quick poll of people in my office lead us all to believe that this issue means you should not be allowed (<-) within a do's let statement. This leads us to a second problem, floating these monadic expressions outside any binding: do case x of [] -> return 1 (y:ys) -> f (<- g y) Here, the proposed desugaring does not work, since y is not in scope where we move the element to. Perhaps this leads to the conclusion that monadic subexpressions should not be allowed inside any binding group, including let, case or lambda. Thanks Neil From dav.vire+haskell at gmail.com Fri Aug 3 16:53:18 2007 From: dav.vire+haskell at gmail.com (david48) Date: Fri Aug 3 16:45:30 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions In-Reply-To: <404396ef0708031342x7af7ab6fq77e377152f828841@mail.gmail.com> References: <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> <404396ef0708031342x7af7ab6fq77e377152f828841@mail.gmail.com> Message-ID: <4c88418c0708031353h675e29e4v58d390003351dacd@mail.gmail.com> On 8/3/07, Neil Mitchell wrote: > temp <- a > let x = temp if you write : let x = (<-a):x is it possible that is desugars into : temp <-a let x = temp:x that would'nt work ? I realize I may be asking dumb questions but being dumb never harmed anyone so :) Also : > do case x of > [] -> return 1 > (y:ys) -> f (<- g y) Is it not possible that is desugars to do case x of [] -> return 1 (y:ys) -> g y >>= \temp -> f temp > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From ndmitchell at gmail.com Fri Aug 3 17:00:01 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Fri Aug 3 16:52:14 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions In-Reply-To: <4c88418c0708031353h675e29e4v58d390003351dacd@mail.gmail.com> References: <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> <404396ef0708031342x7af7ab6fq77e377152f828841@mail.gmail.com> <4c88418c0708031353h675e29e4v58d390003351dacd@mail.gmail.com> Message-ID: <404396ef0708031400x16ac5a17o9cac23b8760e0cd6@mail.gmail.com> Hi > if you write : > > let x = (<-a):x > > is it possible that is desugars into : > > temp <-a > let x = temp:x > > that would'nt work ? That would work, since 'a' doesn't refer to 'x'. I can't think of a real example where it becomes an issue, but the scope within 'a' has changed. > Also : > > > do case x of > > [] -> return 1 > > (y:ys) -> f (<- g y) > > Is it not possible that is desugars to > > do case x of > [] -> return 1 > (y:ys) -> g y >>= \temp -> f temp See the rule about always binding to the previous line of a do block. This case then violates that. Thanks Neil From dav.vire+haskell at gmail.com Fri Aug 3 17:10:10 2007 From: dav.vire+haskell at gmail.com (david48) Date: Fri Aug 3 17:02:23 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions In-Reply-To: <404396ef0708031400x16ac5a17o9cac23b8760e0cd6@mail.gmail.com> References: <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> <404396ef0708031342x7af7ab6fq77e377152f828841@mail.gmail.com> <4c88418c0708031353h675e29e4v58d390003351dacd@mail.gmail.com> <404396ef0708031400x16ac5a17o9cac23b8760e0cd6@mail.gmail.com> Message-ID: <4c88418c0708031410g28a860ddv141f7ed026e785d7@mail.gmail.com> On 8/3/07, Neil Mitchell wrote: > > Is it not possible that is desugars to > > do case x of > > [] -> return 1 > > (y:ys) -> g y >>= \temp -> f temp > See the rule about always binding to the previous line of a do block. > This case then violates that. I assumed that the example was equivalent to : do case x of [] -> return 1 (y:ys) -> do f (<- g y) Shouldn't the rule work then ? From sebastian.sylvan at gmail.com Fri Aug 3 17:11:58 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Fri Aug 3 17:04:12 2007 Subject: [Haskell-cafe] Re: Re: monad subexpressions In-Reply-To: References: <3d96ac180708031114i2f1ab07awc9e98897648aa491@mail.gmail.com> Message-ID: <3d96ac180708031411x30d75912p6f3b970e032bda91@mail.gmail.com> On 03/08/07, Chris Smith wrote: > Sebastian Sylvan wrote: > > I'd also like to reiterate my request for a notation that doesn't > > require brackets around the *action* but will also work by applying it > > to a function which when fully applied to its argument returns an > > action (i.e.: $foo x y + $bar z w, rather than $(foo x y) + $(bar z > > w)). Function application is normally very low-noise in Haskell > > (good), and it would be nice if we can keep it low-noise in this > > notation too. > > I'm trying to understand your suggestion. Can you tell me how you'd > sugar the following? > > getA :: Friggle MyA > getB :: Friggle MyB > foo :: Int -> MyB -> Friggle MyC > > do a <- getA > b <- getB a > foo 42 b > Something like: foo 42 (#getB #getA)? Is there an ambiguity that I'm to dense to see here? :-) -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From ndmitchell at gmail.com Fri Aug 3 17:15:36 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Fri Aug 3 17:07:48 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions In-Reply-To: <4c88418c0708031410g28a860ddv141f7ed026e785d7@mail.gmail.com> References: <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> <404396ef0708031342x7af7ab6fq77e377152f828841@mail.gmail.com> <4c88418c0708031353h675e29e4v58d390003351dacd@mail.gmail.com> <404396ef0708031400x16ac5a17o9cac23b8760e0cd6@mail.gmail.com> <4c88418c0708031410g28a860ddv141f7ed026e785d7@mail.gmail.com> Message-ID: <404396ef0708031415v4ac14d6bj14bdf48ba2e6cf40@mail.gmail.com> Hi > > > do case x of > > > [] -> return 1 > > > (y:ys) -> g y >>= \temp -> f temp > > > See the rule about always binding to the previous line of a do block. > > This case then violates that. > > I assumed that the example was equivalent to : > > do case x of > [] -> return 1 > (y:ys) -> do f (<- g y) > > Shouldn't the rule work then ? If the do was inserted, then yes, this would work. Without it, it doesn't. Perhaps this makes a restriction to not inside case/let/lambda not that severe, since usually an additional do could be inserted. Thanks Neil From sebastian.sylvan at gmail.com Fri Aug 3 17:16:11 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Fri Aug 3 17:08:24 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> References: <3d96ac180708031114i2f1ab07awc9e98897648aa491@mail.gmail.com> <01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> Message-ID: <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> On 03/08/07, Claus Reinke wrote: > > mytransaction = do { > > x0 <- readTVar xvar0 > > x1 <- readTVar xvar1 > > : > > xn <- readTVar xvarn > > return $ foo x0 x1 .. xn > > } > > > > Versus > > > > mytransaction = return $ foo $(readTVar xvar0) $(readTVar xvar1) .. > > $(readTVar xvarn) > > ah, a concrete example. but isn't that the typical use case for ap? > > mytransaction = foo `liftM` r xvar0 `ap` r xvar1 .. > where r = readTVar I really find it difficult to articulate why this isn't acceptable, because it seems so obvious to me! It's short yes, but I really don't think it's very clear... I have a hard time believing that anyone finds that natural. After lots and lots of mind-bending forays into various branches of mathematics, then yes maybe you can get used to it, but it's hardly as natural as saying "add this one symbol to your values to extract monadic values left-to-right". -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From alex at alexjacobson.com Fri Aug 3 18:02:06 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Fri Aug 3 17:54:30 2007 Subject: [Haskell-cafe] Re: HDBC or HSQL In-Reply-To: <1449382301.20070801115957@gmail.com> References: <470880360707300831s44170261lb5d2002d1f56e70b@mail.gmail.com> <46B00D4F.6090206@alexjacobson.com> <1449382301.20070801115957@gmail.com> Message-ID: <46B3A5DE.6030704@alexjacobson.com> Will be pushing out the refactored happs repos in the next 2 weeks. The gist is: * HAppS.IxSet provides efficient query operations on haskell sets. * HAppS.State provides ACID, replicated, and soon sharded access to your application state. * HAppS.Network will provide server side HTTP functionality from which to access your replicated state. -Alex- Bulat Ziganshin wrote: > Hello Alex, > > Wednesday, August 1, 2007, 8:34:23 AM, you wrote: > >> I am asking because I am trying to make HAppS a reasonable replacement >> for all contexts in which you would otherwise use an external relational >> database except those in which an external SQL database is a specific >> requirement. > > where i can read about such usage? > > From alex at alexjacobson.com Fri Aug 3 18:04:10 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Fri Aug 3 17:56:28 2007 Subject: [Haskell-cafe] Re: HDBC or HSQL In-Reply-To: <470880360708011106h30e646dai3b79ce8f673f5ac1@mail.gmail.com> References: <470880360707300831s44170261lb5d2002d1f56e70b@mail.gmail.com> <46B00D4F.6090206@alexjacobson.com> <470880360708011106h30e646dai3b79ce8f673f5ac1@mail.gmail.com> Message-ID: <46B3A65A.8090703@alexjacobson.com> Have you looked at the HAppS.DBMS.IxSet? It gives you a type safe way to query indexed collections. -Alex- Isto Aho wrote: > Hi, > > I'd like to store small matrices into a db. Number of rows and columns > may vary in a way not > known in advance. One might use a relation (matrixId, col, row, value) > or something like that > but if it is possible to put a matrix in one command into db, some > queries will be easier. > E.g., one relation can store several matrices and it would be easy to > query, how many > matrices are stored currently. With that above four tuple you can find > out the number of unique > matrixId's, too, but it is not as easy as with matrices. > > Anyhow, now I'm not sure if I should stick with HSQL any more... Earlier > comments on this > thread made me think that maybe it would be a better idea to try to > learn enough HDBC. > > This would be used in a server application. Is HAppS applicable here? > > e.g. after some tweaking the following works with HSQL: > > addRows = do > dbh <- connect server database user_id passwd > intoDB dbh ([555,111, 50, 1000]::[Int]) > ([21.0,22.0,23.0,24.0]::[Double]) > intoDB dbh ([556,111, 50, 1000]::[Int]) > ([21.0,22.0,23.0,24.0]::[Double]) > intoDB dbh ([]::[Int]) ([]::[Double]) > where > intoDB dbh i_lst d_lst = > catchSql (do > let cmd = "INSERT INTO trial (intList, dList) > VALUES (" ++ > toSqlValue i_lst ++ "," ++ toSqlValue > d_lst ++ ")" > execute dbh cmd > ) > (\e -> putStrLn $ "Problem: " ++ show e) > > > Similarly, queries can handle matrices and I like that it is now > possible to select those columns or rows from the stored matrix that > are needed. E.g. > > retrieveRecords2 :: Connection -> IO [[Double]] > retrieveRecords2 c = do > -- query c "select dList[1:2] from trial" >>= collectRows getRow > query c "select dList from trial" >>= collectRows getRow > where > getRow :: Statement -> IO [Double] > getRow stmt = do > lst <- getFieldValue stmt "dList" > return lst > readTable2 = do > dbh <- connect server database user_id passwd > values <- retrieveRecords2 dbh > putStrLn $ "dLists are : " ++ (show values) > > > br, > Isto > > > 2007/8/1, Alex Jacobson >: > > Out of curiosity, can I ask what you are actually trying to do? > > I am asking because I am trying to make HAppS a reasonable replacement > for all contexts in which you would otherwise use an external relational > database except those in which an external SQL database is a specific > requirement. > > -Alex- > From bayer at math.columbia.edu Fri Aug 3 18:05:13 2007 From: bayer at math.columbia.edu (Dave Bayer) Date: Fri Aug 3 17:57:48 2007 Subject: [Haskell-cafe] Re: When is waitForProcess not necessary? References: Message-ID: So I stared at the documentation in Control-Concurrent, learned about finally and MVar variables, and crossed the genes from the suggestions here to come up with runCommand :: String -> String -> IO (String,Bool) runCommand cmd input = do (inp,out,err,pid) <- runInteractiveCommand cmd let get h = do mvar <- newEmptyMVar let put xs = seq (length xs) (putMVar mvar xs) forkIO $ finally (hGetContents h >>= put) (put []) takeMVar mvar if null input then return () else hPutStr inp input output <- get out errmsg <- get err exit <- waitForProcess pid case exit of ExitSuccess -> return (output,True) ExitFailure _ -> do hPutStrLn stderr errmsg return (errmsg,False) which seems to work well; I haven't beat on it. I like the return type for my needs, e.g. I can write (out,ok) <- runCommand mark doc if ok then write out src else hPutStr stderr out So why don't the MVar examples in this thread bracket somehow, e.g. with finally as Control-Concurrent suggests: Note that we use finally from the Control.Exception module to make sure that the MVar is written to even if the thread dies or is killed for some reason. It seems to me that this could happen, with waitForProcess doing fine, yet the MVar never getting written. (I haven't written a test example to exercise this.) From dan.doel at gmail.com Fri Aug 3 19:04:52 2007 From: dan.doel at gmail.com (Dan Doel) Date: Fri Aug 3 18:52:38 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> References: <01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> Message-ID: <200708031904.52941.dan.doel@gmail.com> On Friday 03 August 2007, Sebastian Sylvan wrote: > On 03/08/07, Claus Reinke wrote: > > ah, a concrete example. but isn't that the typical use case for ap? > > > > mytransaction = foo `liftM` r xvar0 `ap` r xvar1 .. > > where r = readTVar > > I really find it difficult to articulate why this isn't acceptable, > because it seems so obvious to me! It's short yes, but I really don't > think it's very clear... > I have a hard time believing that anyone finds that natural. After > lots and lots of mind-bending forays into various branches of > mathematics, then yes maybe you can get used to it, but it's hardly as > natural as saying "add this one symbol to your values to extract > monadic values left-to-right". Note that if this is the example we're using, idiom brackets solve things: mytransaction = [[ foo (r xvar0) (r xvar1) ...]] where r = readTVar and are, possibly, less fraught with peril, considering all the discussions about where the desugaring should place the implicit binding, and what happens if there isn't an enclosing do and so on (as idiom brackets desugar to the "foo `liftM` r xvar0 `ap` r xvar1 ..." mentioned above, and the entire expression is delimited, there are no such questions to be pondered, I think). Also, note, if you use the operators in Control.Applicative, then: return $ foo $(bar1) $(bar2) $(bar3) ... can be: return foo <*> bar1 <*> bar2 <*> bar3 ... or: foo <$> bar1 <*> bar2 <*> bar3 I don't (personally) see how that's any more cryptic than placing brackets around around the monadic values themselves. In either case, there's some magic going on that the user may or may not understand. In the applicative case, it's using a different kind of (Monadic/Applicative) function application via an operator. In the monad brackets case, it's doing a macro expansion. I, personally find the former clearer, but perhaps that's because I understand Applicative fairly well, but only have a vague idea of what, specifically, the macro will be doing so far. To get outside the scope of idiom brackets/applicative, you'd need a use case like: if $(mexpr) then branch1 else branch2 or (lest that be to easy): case $(mexpr) of p1 -> branch1 p2 -> branch2 ... In other words, something where you're not simply applying a pure function to a bunch of monadic arguments. I can't say I've run into such patterns much myself, but I've been told they're common in xmonad, and may be elsewhere. In general, I guess you'd need the monad brackets when you'd need to interact with other syntax (since it isn't first-class). Record update would probably be another example. But applications of pure functions to monadic values doesn't seem like a particularly compelling motivator, in my opinion. -- Dan From claus.reinke at talk21.com Fri Aug 3 20:07:27 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Fri Aug 3 19:59:45 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <3d96ac180708031114i2f1ab07awc9e98897648aa491@mail.gmail.com><01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> Message-ID: <036201c7d62b$72380440$14217ad5@cr3lt> >> mytransaction = foo `liftM` r xvar0 `ap` r xvar1 .. >> where r = readTVar > > I really find it difficult to articulate why this isn't acceptable, > because it seems so obvious to me! It's short yes, but I really don't > think it's very clear... if it is any consolation, i don't use that style myself (yet?-). but it is a useful stepping stone on a path that seems to go somewhat like this: - explicit do-notation with flattened parameters - explicitly defined lifted operations - liftMn, for on-the-spot lifting - liftM/ap (avoiding need for infinitely many liftMn) - idioms http://www.cs.nott.ac.uk/~ctm/Idiom.pdf - idiom brackets - .. ?-) > I have a hard time believing that anyone finds that natural. After > lots and lots of mind-bending forays into various branches of > mathematics, then yes maybe you can get used to it, but it's hardly as > natural as saying "add this one symbol to your values to extract > monadic values left-to-right". what makes this unnatural to me is that it is built-in syntax, which not only interacts badly with haskell's general abstraction facilities, but is outside the programmers' control. once we've figured out what we want, programatically, then putting a nice syntax on top of it, that is syntactic sugar, but binding fairly complex syntax transformations to an innocent-looking syntax is not. perhaps a good start would be syntactic sugar for idiom brackets, to rescue them from the complexities of type-level programming? at least, that would be a local transformation with well-explored semantics, similar to do-notation on top of >>=/return. if that doesn't work out, one might take another look at (<-). claus From brandon at heave.ugcs.caltech.edu Fri Aug 3 20:48:18 2007 From: brandon at heave.ugcs.caltech.edu (Brandon Michael Moore) Date: Fri Aug 3 20:40:30 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <200708031904.52941.dan.doel@gmail.com> References: <01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> <200708031904.52941.dan.doel@gmail.com> Message-ID: <20070804004818.GA2860@heave.ugcs.caltech.edu> > Also, note, if you use the operators in Control.Applicative, then: > > return $ foo $(bar1) $(bar2) $(bar3) ... > > can be: > > return foo <*> bar1 <*> bar2 <*> bar3 ... > > or: > > foo <$> bar1 <*> bar2 <*> bar3 > > I don't (personally) see how that's any more cryptic than placing brackets > around around the monadic values themselves. > ... Seconded. The main difference with brackes is that the application to pure values looks the same as normal application. > > To get outside the scope of idiom brackets/applicative, you'd need a use case > like: > > if $(mexpr) then branch1 else branch2 > > or (lest that be to easy): > > case $(mexpr) of > p1 -> branch1 > p2 -> branch2 > ... > > In other words, something where you're not simply applying a pure function to > a bunch of monadic arguments. I can't say I've run into such patterns much > myself, but I've been told they're common in xmonad, and may be elsewhere. General purpose brackets are overkill here. I would really like a simple monadic case. What's so bad about caseM mexpr of p1 -> branch1 p2 -> branch2 vvvv (mexpr >>= \e -> case e of p1 -> branch1 p2 -> branch2) It's simple sugar for working with monadic code, much like do notation. (indeed, it seems to plug a gap - we have do for sequencing, liftM and so on for application, but no sugar for case discrimination) It's a much simpler sort of thing than this fancy sugar for intermixing code in various monads people have been talking about (so far it seems assumed that one is just Identity...) Brandon From stefanor at cox.net Fri Aug 3 20:51:55 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 3 20:44:12 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <20070804004818.GA2860@heave.ugcs.caltech.edu> References: <01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> <200708031904.52941.dan.doel@gmail.com> <20070804004818.GA2860@heave.ugcs.caltech.edu> Message-ID: <20070804005155.GA5306@localhost.localdomain> On Fri, Aug 03, 2007 at 05:48:18PM -0700, Brandon Michael Moore wrote: > General purpose brackets are overkill here. I would really like a simple > monadic case. What's so bad about > > caseM mexpr of > p1 -> branch1 > p2 -> branch2 > > vvvv > > (mexpr >>= \e -> case e of > p1 -> branch1 > p2 -> branch2) > > It's simple sugar for working with monadic code, much like do notation. > (indeed, it seems to plug a gap - we have do for sequencing, liftM and > so on for application, but no sugar for case discrimination) > > It's a much simpler sort of thing than this fancy sugar for intermixing > code in various monads people have been talking about (so far it seems > assumed that one is just Identity...) I think the CaseLambda proposal on the Haskell' wiki solves this one nicely. mexpr >>= case of p1 -> branch1 p2 -> branch2 You still have to use >>=, but you don't have to name the scrutinee (and names are expensive cognitively). Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070803/c6bddc1c/attachment.bin From aslatter at gmail.com Fri Aug 3 21:13:44 2007 From: aslatter at gmail.com (Antoine Latter) Date: Fri Aug 3 21:05:56 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions In-Reply-To: References: <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> <4c88418c0708031245o7712911aob8e7231084c2de4b@mail.gmail.com> <4c88418c0708031248j98b5268g9aa5abea344864a3@mail.gmail.com> Message-ID: <694519c50708031813m76788f6bjf0fb3bc53a21ddd5@mail.gmail.com> On 8/3/07, Chris Smith wrote: > Yes, unless of course you did: > > instance (Monad m, Num n) => Num (m n) > > or some such nonsense. :) I decided to take this as a dare - at first I thought it would be easy to declare (Monad m, Num n) => m n to be an instance of Num (just lift or return the operators as necessary), but I ran into trouble once I realized I needed two things I wasn't going to get: An instance of Eq (m n), and an instance of Show (m n) for all monads m. Eq would need a function of the form: (==) :: Monad m => m a -> m a -> Bool and Show would need a function of type m a -> String There's no way I'm getting a function of those types using return and join to operate on the monad. So, there went that idea. -Antoine From twanvl at gmail.com Fri Aug 3 21:41:31 2007 From: twanvl at gmail.com (Twan van Laarhoven) Date: Fri Aug 3 21:33:39 2007 Subject: [Haskell-cafe] Re: Re: Re: monad subexpressions In-Reply-To: <694519c50708031813m76788f6bjf0fb3bc53a21ddd5@mail.gmail.com> References: <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> <404396ef0708030549m4ca4765bt4463dd9a6d559e84@mail.gmail.com> <404396ef0708030606j56ec3dacw52b5d3134bc62267@mail.gmail.com> <404396ef0708031004l6966fd3ev32dc04c333c0a6c0@mail.gmail.com> <4c88418c0708031245o7712911aob8e7231084c2de4b@mail.gmail.com> <4c88418c0708031248j98b5268g9aa5abea344864a3@mail.gmail.com> <694519c50708031813m76788f6bjf0fb3bc53a21ddd5@mail.gmail.com> Message-ID: <46B3D94B.6000400@gmail.com> Antoine Latter wrote: > On 8/3/07, Chris Smith wrote: > >>Yes, unless of course you did: >> >> instance (Monad m, Num n) => Num (m n) >> >>or some such nonsense. :) > > > I decided to take this as a dare - at first I thought it would be easy > to declare (Monad m, Num n) => m n to be an instance of Num (just lift > or return the operators as necessary), but I ran into trouble once I > realized I needed two things I wasn't going to get: > > An instance of Eq (m n), and an instance of Show (m n) for all monads > m. Eq would need a function of the form: > > (==) :: Monad m => m a -> m a -> Bool > > and Show would need a function of type m a -> String What about Eq1 and Show1 classes? In the same vein as Typeable1: > class Eq1 f where > eq1 :: Eq a => f a -> f a -> Bool > neq1 :: Eq a => f a -> f a -> Bool > class Show1 f where > show1 :: Show a => f a -> String > showsPrec1 :: Show a => Int -> f a -> ShowS Now you can declare the Num instance: > instance (Monad m, Eq1 m, Show1 m, Num n) => Num (m n) where > (+) = liftM2 (+) > (-) = liftM2 (-) > (*) = liftM2 (*) > abs = liftM abs > signum = liftM signum > negate = ligtM negate > fromInteger = return . fromInteger And just to show that such instances can exist: > instance Eq1 [] where > eq1 = (==) > neq1 = (/=) > instance Show1 [] where > show1 = show > showsPrec1 = showsPrec Note: All of this is untested code. Twan From bulat.ziganshin at gmail.com Sat Aug 4 00:35:49 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 4 00:36:18 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> Message-ID: <1955583864.20070804083549@gmail.com> Hello apfelmus, Saturday, August 4, 2007, 12:22:53 AM, you wrote: > avoid the small layer of imperative code, of course. But the more you > treat imperative code as somewhat pure, the greater the danger that the > purely functional logic will be buried inside a mess of imperative code. > In other words, the goal is exactly to make IO and STM uncommon, > otherwise you loose the power the purely functional approach offers. it's point of view of theoretical purist. i consider Haskell as language for real world apps and need to write imperative code appears independently of our wishes. in paricular, it's required to write very efficient code, to interact with existing imperative APIs, to make programs which has explicit memory control (as opposite to lazy evaluation with GC) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From bulat.ziganshin at gmail.com Sat Aug 4 01:26:46 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 4 01:22:55 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <015501c7d5e3$1847ce40$14217ad5@cr3lt> References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt> <785460922.20070803173640@gmail.com> <015501c7d5e3$1847ce40$14217ad5@cr3lt> Message-ID: <1662608023.20070804092646@gmail.com> Hello Claus, Friday, August 3, 2007, 7:29:32 PM, you wrote: >> how about *Object.File.Line.CurPtr++ = *AnotherObject.File.Line.CurPtr++ ? ;) > what's the difference?-) > let p = Object.File.Line.CurPtr > let q = AnotherObject.File.Line.CurPtr > do { w p =<< r q; i p; i q } back to the assembler future? :) so-called high-level languages started with the idea that you don't need to give explicit names to intermediate results >> the problem with Haskell is that we need to split C expression into >> several statements and explicitly specify execution order even when we >> know that it doesn't matter. ideally, it should be possible to define >> >> ++x = modifyIORef x (+1) >> readIORef x >> *x = readIORef x > apart from the prefix symbols (i used one-letter prefix names), you > can (as i'm sure you know). and the point of my little exercise was to > show that instead of doing the splitting by hand at each usage site, > we can write lifting combinators that do the splitting behind the scenes. > what gives haskell aspirations to be a fine imperative language is that > its abstraction mechanisms work as well for imperative code as for > functional code. can you give translation you mean? i don't have anything against combinators, they just need to be easy to use, don't forcing me to think where i should put one, as i don't think with lazy code and C imperative code. and they shouldn't clatter the code, too. just try to write complex expression using C and these combinators -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From bryan.burgers at gmail.com Sat Aug 4 02:01:57 2007 From: bryan.burgers at gmail.com (Bryan Burgers) Date: Sat Aug 4 01:54:08 2007 Subject: [Haskell-cafe] Question about arrows In-Reply-To: <567ACB2E39C83543B746F1AD7F5E5E040BFEE8B0@wa-mb2-sea.amgen.com> References: <567ACB2E39C83543B746F1AD7F5E5E040BFEE8B0@wa-mb2-sea.amgen.com> Message-ID: On 8/3/07, Lewis-Sandy, Darrell wrote: > > Is there a class property of the Control.Arrow class that represents the > evaluatation of an arrow: > > eval :: (Arrow a)=>a b c->b->c > You could always use the ArrowEval class. Granted, it doesn't exist, so you'd have to write it, but it should serve your purposes. class ArrowEval a where eval :: a b c -> b -> c instance ArrowEval (->) where eval = ... instance ArrowEval YourPartial where eval = ... (That's off the cuff, so I probably didn't get the syntax correct.) Does that fit your problem? But like Mr. Morris said, eval isn't valid for every arrow, so you can only define instances of ArrowEval where it is valid. Bryan From apfelmus at quantentunnel.de Sat Aug 4 04:18:33 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Sat Aug 4 04:10:57 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> References: <3d96ac180708031114i2f1ab07awc9e98897648aa491@mail.gmail.com> <01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> Message-ID: Sebastian Sylvan wrote: > Claus Reinke wrote: >>> mytransaction = do { >>> x0 <- readTVar xvar0 >>> x1 <- readTVar xvar1 >>> : >>> xn <- readTVar xvarn >>> return $ foo x0 x1 .. xn >>> } >> >> ah, a concrete example. but isn't that the typical use case for ap? >> >> mytransaction = foo `liftM` r xvar0 `ap` r xvar1 .. >> where r = readTVar > > I really find it difficult to articulate why this isn't acceptable, > because it seems so obvious to me! It's short yes, but I really don't > think it's very clear... > I have a hard time believing that anyone finds that natural. I think it's entirely natural :) Applicative functors (Control.Applicative) are the pattern behind this. The notation may seem a little weird first, but in the end, `ap` is a kind of explicit function application and similar to $. With the notation from Control.Applicative, the line return foo `ap` r xvar0 `ap` r xvar1 `ap` ... reads pure foo <*> r xvar0 <*> r xvar1 <*> ... or foo <$> r xvar0 <*> r xvar1 <*> ... In other words, instead of using juxtaposition to apply an argument to a function, we use <*>. The type of `ap` is ap :: m (a -> b) -> m a -> m b so that it can be thought of as a generalized function application where the function is "under" a monad. The difference to $ is that <*> is left associative and allows for currying. I.e. <*> is like $ used in the following way ((foo $ x0) $ x1) $ x2 Note that you can even incorporate the TVar by defining your own generalized function application: apT :: STM (a -> b) -> TVar a -> STM b apT f x = f `ap` readTVar x Then, mytransaction reads mytransaction = return foo `apT` xvar0 `apT` xvar1 `apT` ... Regards, apfelmus From bulat.ziganshin at gmail.com Sat Aug 4 04:38:04 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 4 04:34:08 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <3d96ac180708031114i2f1ab07awc9e98897648aa491@mail.gmail.com> <01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> Message-ID: <351474761.20070804123804@gmail.com> Hello apfelmus, Saturday, August 4, 2007, 12:18:33 PM, you wrote: > Then, mytransaction reads > mytransaction = return foo `apT` xvar0 `apT` xvar1 `apT` ... how about a+b*(c+d)? -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From claus.reinke at talk21.com Sat Aug 4 07:06:11 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Sat Aug 4 06:58:28 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt> <1662608023.20070804092646@gmail.com> Message-ID: <009401c7d687$78608930$901d8351@cr3lt> > can you give translation you mean? i don't have anything against > combinators, they just need to be easy to use, don't forcing me to > think where i should put one, as i don't think with lazy code and C > imperative code. and they shouldn't clatter the code, too. just try to > write complex expression using C and these combinators perhaps we're misunderstanding each other? if i define a monadic assignment operator lifted over monadic lhs/rhs, i can already have side-effecting lhs/rhs, including post-increments and content lookup. that's what that example demonstrated, translating everything you asked for. one can do the same with other operations, such as lifting numeric operations over monadic operands (though the current class hierarchy may require some ugly dummy class instances for that; also, non-overloaded Bool always requires some workaround). what is it that you think is missing? claus From bulat.ziganshin at gmail.com Sat Aug 4 07:47:11 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 4 07:43:15 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <009401c7d687$78608930$901d8351@cr3lt> References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt> <1662608023.20070804092646@gmail.com> <009401c7d687$78608930$901d8351@cr3lt> Message-ID: <175831851.20070804154711@gmail.com> Hello Claus, Saturday, August 4, 2007, 3:06:11 PM, you wrote: >> can you give translation you mean? i don't have anything against >> combinators, they just need to be easy to use, don't forcing me to >> think where i should put one, as i don't think with lazy code and C >> imperative code. and they shouldn't clatter the code, too. just try to >> write complex expression using C and these combinators > perhaps we're misunderstanding each other? if i define a monadic > assignment operator lifted over monadic lhs/rhs, i can already have > side-effecting lhs/rhs, including post-increments and content lookup. > that's what that example demonstrated, translating everything you > asked for. one can do the same with other operations, such as > lifting numeric operations over monadic operands (though the > current class hierarchy may require some ugly dummy class > instances for that; also, non-overloaded Bool always requires > some workaround). what is it that you think is missing? i know that it may be trsanslated to everything including pure assembler. what i'm missing in current Haskell is USEFUL SYNTAX for these expressions. adding tons of liftM and ap can't make me happy -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From andrewcoppin at btinternet.com Sat Aug 4 07:53:23 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 4 07:45:11 2007 Subject: [Haskell-cafe] How odd... Message-ID: <46B468B3.7000704@btinternet.com> > 0^2 0 > (0 :+ 0)^2 0 :+ 0 > 0**2 0 > (0 :+ 0)**2 NaN :+ NaN (Is this a bug?) From claus.reinke at talk21.com Sat Aug 4 10:57:13 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Sat Aug 4 10:49:32 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt><1662608023.20070804092646@gmail.com><009401c7d687$78608930$901d8351@cr3lt> <175831851.20070804154711@gmail.com> Message-ID: <00e101c7d6a7$beee76d0$901d8351@cr3lt> > i know that it may be trsanslated to everything including pure > assembler. what i'm missing in current Haskell is USEFUL SYNTAX for > these expressions. adding tons of liftM and ap can't make me happy but the point is that you have a standard set of operations when working at that level, including conditionals, assignments, pointer increments, read/write, etc. you only need to define lifted variants of each of those operations *once*, in a library. when you use those lifted variants, you can (actually: you have to) use them with monadic parameters, and no need for liftM/ap. liftM/ap are useful, but need to appear in application code only when you do not know in advance what set of operations you'll need, as you can then lift any operation on the fly. so, there could be a library defining lhs ==: rhs = putMVar <$> lhs <*> rhs and in your application code, you could write newEmptyMVar ==: putStrLn "hi there" (not that this would be useful;-) claus From paul at cogito.org.uk Sat Aug 4 11:01:40 2007 From: paul at cogito.org.uk (Paul Johnson) Date: Sat Aug 4 10:54:03 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B468B3.7000704@btinternet.com> References: <46B468B3.7000704@btinternet.com> Message-ID: <46B494D4.5000709@cogito.org.uk> Andrew Coppin wrote: > > 0**2 > 0 > > > (0 :+ 0)**2 > NaN :+ NaN > > (Is this a bug?) According to the Standard Prelude, # x ** y = exp (log x * y) So 0 ** 2 is equivalent to exp (log 0 * 2) > log 0 -Infinity > log 0 * 2 -Infinity > exp (log 0 * 2) 0.0 On to the complex number case. From the standard for Complex: # log z = log (magnitude z) :+ phase z # phase (0 :+ 0) = 0 This is a special case for the phase of zero. # (x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x') > log (0 :+ 0) (-Infinity) :+ 0.0 > log (0 :+ 0) * 2 (-Infinity) :+ NaN Which is the source of the problem. The imaginary part involves multiplying (-Infinity) by the imaginary part of 2 (i.e. 0), which is NaN. So no, its not a bug, its according to the standard. Whether the standard ought to be modified for multiplication by numbers of the form (x :+ 0) is another question. Arguably the correct value in the last case should have been (-Infinity) :+ 0.0 on the grounds that (x :+ y) * 2 should be equal to (x * 2 :+ y * 2). In most cases this holds, but if one of the complex multiplicands contains an infinity then you get a NaN instead. While working through this I also came across the following case which technically is a bug: > 0 ** 0 1.0 > exp (log 0 * 0) NaN I suspect that GHCi is using a built-in exponentiation operator that doesn't quite conform to the standard in this case. Paul. From bulat.ziganshin at gmail.com Sat Aug 4 11:19:14 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 4 11:15:20 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <00e101c7d6a7$beee76d0$901d8351@cr3lt> References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt><1662608023.20070804092646@gmail.com><009401c7d687$78608930$901d8351@cr3lt> <175831851.20070804154711@gmail.com> <00e101c7d6a7$beee76d0$901d8351@cr3lt> Message-ID: <1278932794.20070804191914@gmail.com> Hello Claus, Saturday, August 4, 2007, 6:57:13 PM, you wrote: > so, there could be a library defining > lhs ==: rhs = putMVar <$> lhs <*> rhs > and in your application code, you could write > newEmptyMVar ==: putStrLn "hi there" > (not that this would be useful;-) it's great! how fools are invented fortran! anyone using macroassembler can define macros for any shape of expression and use them as they need. for example, instead of writing a=b*c+d it's much easier to define macro abcd macro a,b,op1,c,op2,d mov r1, b op1 r1, c op2 r1, d mov a, r1 endm and use it. want to assign a=b/(c+d)? nothing can be easier! just define one more macro! -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From scm at iis.sinica.edu.tw Sat Aug 4 11:25:21 2007 From: scm at iis.sinica.edu.tw (Shin-Cheng Mu) Date: Sat Aug 4 11:17:49 2007 Subject: [Haskell-cafe] Developing Programs and Proofs Spontaneously using GADT Message-ID: <544F41C1-FFAC-47C5-B3B9-2DD3291FC570@iis.sinica.edu.tw> I am curious about the possibility of developing Haskell programs spontaneously with proofs about their properties and have the type checker verify the proofs for us, in a way one would do in a dependently typed language. In the exercise below, I tried to redo part of the merge-sort example in Altenkirch, McBride, and McKinna's introduction to Epigram [1]: deal the input list into a binary tree, and fold the tree by the function merging two sorted lists into one. The property I am going to show is merely that the length of the input list is preserved. Given that dependent types and GADTs are such popular topics, I believe the same must have been done before, and there may be better ways to do it. If so, please give me some comments or references. Any comments are welcomed. > {-# OPTIONS_GHC -fglasgow-exts #-} To begin with, we define the usual type-level representation of natural numbers and lists indexed by their lengths. > data Z = Z deriving Show > data S a = S a deriving Show > data List a n where > Nil :: List a Z > Cons :: a -> List a n -> List a (S n) 1. Append To warm up, let us see the familiar "append" example. Unfortunately, unlike Omega, Haskell does not provide type functions. I am not sure which is the best way to emulate type functions. One possibility is to introduce the following GADT: > data Plus m n k where --- m + n = k > PlusZ :: Plus Z n n > PlusS :: Plus m n k -> Plus (S m) n (S k) such that Plus m n k represents a proof that m + n = k. Not having type functions, one of the possible ways to do append is to have the function, given two lists of lengths m and n, return a list of length k and a proof that m + n = k. Thus, the type of append would be: append :: List a m -> List a n -> exists k. (List a k, Plus m n k) In Haskell, the existential quantifier is mimicked by forall. We define: > data DepSum a p = forall i . DepSum (a i) (p i) The term "dependent sum" is borrowed from the Omega tutorial of Sheard, Hook, and Linger [2] (why is it called a sum, not a product?). The function append can thus be defined as: > append :: List a m -> List a n -> DepSum (List a) (Plus m n) > append Nil ys = DepSum ys PlusZ > append (Cons x xs) ys = > case (append xs ys) of > DepSum zs p -> DepSum (Cons x zs) (PlusS p) Another possibility is to provide append a proof that m + n = k. The type and definition of of append would be: < append :: Plus m n k -> List a m -> List a n -> List a k < append PlusZ Nil ys = ys < append (PlusS pf) (Cons x xs) ys = Cons x (append pf xs ys) I thought the second append would be more difficult to use: to append two lists, I have to provide a proof about their lengths! It turns out that this append actually composes easier with other parts of the program. We will come to this later. 2. Some Lemmas Here are some lemmas represented as functions on terms. The function, for example, converts a proof of m + (1+n) = k to a proof of (1+m) + n = k. > incAssocL :: Plus m (S n) k -> Plus (S m) n k > incAssocL PlusZ = PlusS PlusZ > incAssocL (PlusS p) = PlusS (incAssocL p) > incAssocR :: Plus (S m) n k -> Plus m (S n) k > incAssocR (PlusS p) = plusMono p > plusMono :: Plus m n k -> Plus m (S n) (S k) > plusMono PlusZ = PlusZ > plusMono (PlusS p) = PlusS (plusMono p) For example, the following function revcat performs list reversal by an accumulating parameter. The invariant we maintain is m + n = k. To prove that the invariant holds, we have to use incAssocL. > revcat :: List a m -> List a n -> DepSum (List a) (Plus m n) > revcat Nil ys = DepSum ys PlusZ > revcat (Cons x xs) ys = > case revcat xs (Cons x ys) of > DepSum zs p -> DepSum zs (incAssocL p) 3. Merge Apart from the proof manipulations, the function merge is not very different from what one would expect: > merge :: Ord a => List a m -> List a n -> DepSum (List a) (Plus m n) > merge Nil ys = DepSum ys PlusZ > merge (Cons x xs) Nil = append (Cons x xs) Nil > merge (Cons x xs) (Cons y ys) > | x <= y = case merge xs (Cons y ys) of > DepSum zs p -> DepSum (Cons x zs) (PlusS p) > | otherwise = case merge (Cons x xs) ys of > DepSum zs p -> DepSum (Cons y zs) (plusMono p) The lemma plusMono is used to convert a proof of m + n = k to a proof of m + (1+n) = 1+k. 4. Sized Trees We also index binary trees by their sizes: > data Tree a n where > Nul :: Tree a Z > Tip :: a -> Tree a (S Z) > Bin :: Tree a n1 -> Tree a n -> > (Plus p n n1, Plus n1 n k) -> Tree a k The two trees given to the constructor Bin have sizes n1 and n respectively. The resulting tree, of size k, comes with a proof that n1 + n = k. Furthermore, we want to maintain an invariant that n1 either equals n, or is bigger than n by one. This is represented by the proof Plus p n n1. In the definition of insertT later, p is either PlusZ or PlusS PlusZ. 5. Lists to Trees The function insertT inserts an element into a tree: > insertT :: a -> Tree a n -> Tree a (S n) > insertT x Nul = Tip x > insertT x (Tip y) = Bin (Tip x) (Tip y) (PlusZ, PlusS PlusZ) > insertT x (Bin t u (PlusZ, p)) = > Bin (insertT x t) u (PlusS PlusZ, PlusS p) > insertT x (Bin t u (PlusS PlusZ, p)) = > Bin t (insertT x u) (PlusZ, PlusS (incAssocR p)) Note that whenever we construct a tree using Bin, the first proof, corresponding to the difference in size of the two subtrees, is either PlusZ or PlusS PlusZ. The counterpart of foldr on indexed list is defined by: > foldrd :: (forall k . (a -> b k -> b (S k))) -> b Z > -> List a n -> b n > foldrd f e Nil = e > foldrd f e (Cons x xs) = f x (foldrd f e xs) The result is also an indexed type (b n). The function deal :: List a n -> Tree a n, building a tree out of a list, can be defined as a fold: > deal :: List a n -> Tree a n > deal = foldrd insertT Nul 6. Trees to Lists, and Merge Sort The next step is to fold through the tree by the function merge. The first two clauses are simple: > mergeT :: Ord a => Tree a n -> List a n > mergeT Nul = Nil > mergeT (Tip x) = Cons x Nil For the third clause, one would wish that we could write something as simple as: mergeT (Bin t u (_,p1)) = case merge (mergeT t) (mergeT u) of DepSum xs p -> xs However, this does not type check. Assume that t has size n1, and u has size n. The DepSum returned by merge consists of a list of size i, and a proof p of type Plus m n i, for some i. The proof p1, on the other hand, is of type P m n k for some k. Haskell does not know that Plus m n is actually a function and cannot conclude that i=k. To explicitly state the equality, we assume that there is a function plusFn which, given a proof of m + n = i and a proof of m + n = k, yields a function converting an i in any context to a k. That is: plusFn :: Plus m n i -> Plus m n k -> (forall f . f i -> f k) The last clause of mergeT can be written as: > mergeT (Bin t u (_,p1)) = > case merge (mergeT t) (mergeT u) of > DepSum xs p -> plusFn p p1 xs How do I define plusFn? I would like to employ the techniques related to equality types [3,4,5], but currently I have not yet figured out how. I've merely produced a version of plusFn specialised to List a: > plusFn :: Plus m n h -> Plus m n k -> List a h -> List a k > plusFn PlusZ PlusZ xs = xs > plusFn (PlusS p1) (PlusS p2) (Cons x xs) = > Cons x (plusFn p1 p2 xs) Needless to say this is not satisfactory. Now that we have both deal and mergeT, merge sort is simply their composition: > msort :: Ord a => List a n -> List a n > msort = mergeT . deal The function mergeT can be defined using a fold on trees as well. Such a fold might probably look like this: > foldTd :: (forall m n k . Plus m n k -> b m -> b n -> b k) > -> (a -> b (S Z)) -> b Z > -> Tree a n -> b n > foldTd f g e Nul = e > foldTd f g e (Tip x) = g x > foldTd f g e (Bin t u (_,p)) = > f p (foldTd f g e t) (foldTd f g e u) mergeT :: Ord a => Tree a n -> List a n mergeT = foldTd merge' (\x -> Cons x Nil) Nil where merge' p1 xs ys = case merge xs ys of DepSum xs p -> plusFn p p1 xs I am not sure whether this is a "reasonable" type for foldTd. 7. Passing in the Proof as an Argument Previously I thought the second definition of append would be more difficult to use, because we will have to construct a proof about the lengths before calling append. In the context above, however, it may actually be more appropriate to use this style of definitions. An alternative definition of merge taking a proof as an argument can be defined by: < merge :: Ord a => Plus m n k -> List a m -> < List a n -> List a k < merge PlusZ Nil ys = ys < merge pf (Cons x xs) Nil = append pf (Cons x xs) Nil < merge (PlusS p) (Cons x xs) (Cons y ys) < | x <= y = Cons x (merge p xs (Cons y ys)) < | otherwise = Cons y (merge (incAssocL p) (Cons x xs) ys) A definition of mergeT using this definition of merge follows immediately because we can simply use the proof coming with the tree: < mergeT :: Ord a => Tree a n -> List a n < mergeT Nul = Nil < mergeT (Tip x) = Cons x Nil < mergeT (Bin t u (_,p1)) = < merge p1 (mergeT t) (mergeT u) I don't know which approach can be called more "natural". References [1] Thorsten Altenkirch, Conor McBride, and James McKinna. Why Dependent Types Matter. http://www.e-pig.org/downloads/ydtm.pdf [2] Tim Sheard, James Hook, and Nathan Linger. GADTs + Extensible Kinds = Dependent Programming. http://web.cecs.pdx.edu/~sheard/papers/GADT+ExtKinds.ps [3] James Cheney, Ralf Hinze. A lightweight implementation of generics and dynamics. [4] Stephanie Weirich, Type-safe cast: (functional pearl), ICFP 2000. [5] Arthur I. Baars , S. Doaitse Swierstra, Typing dynamic typing, ACM SIGPLAN Notices, v.37 n.9, p.157-166, September 2002 Appendix. Auxiliary Functions > instance Show a => Show (List a n) where > showsPrec _ Nil = ("[]"++) > showsPrec _ (Cons x xs) = shows x . (':':) . shows xs > instance Show (Plus m n k) where > showsPrec _ PlusZ = ("pZ"++) > showsPrec p (PlusS pf) = showParen (p>=10) (("pS " ++) . > showsPrec 10 pf) > instance Show a => Show (Tree a n) where > showsPrec _ Nul = ("Nul"++) > showsPrec p (Tip x) = showParen (p >= 10) (("Tip " ++) . shows x) > showsPrec p (Bin t u pf) = > showParen (p>=10) > (("Bin "++) . showsPrec 10 t . (' ':) . showsPrec 10 u . > (' ':) . showsPrec 10 pf) From allbery at ece.cmu.edu Sat Aug 4 11:27:16 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sat Aug 4 11:19:29 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <1278932794.20070804191914@gmail.com> References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt><1662608023.20070804092646@gmail.com><009401c7d687$78608930$901d8351@cr3lt> <175831851.20070804154711@gmail.com> <00e101c7d6a7$beee76d0$901d8351@cr3lt> <1278932794.20070804191914@gmail.com> Message-ID: On Aug 4, 2007, at 11:19 , Bulat Ziganshin wrote: > and use it. want to assign a=b/(c+d)? nothing can be easier! just > define one more macro! And? Everything above machine code is just "macros" at various levels of abstraction, including all our favorite higher-level abstractions. -- 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 andrewcoppin at btinternet.com Sat Aug 4 11:38:08 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 4 11:29:54 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B494D4.5000709@cogito.org.uk> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> Message-ID: <46B49D60.402@btinternet.com> Paul Johnson wrote: > Andrew Coppin wrote: >> > 0**2 >> 0 >> >> > (0 :+ 0)**2 >> NaN :+ NaN >> >> (Is this a bug?) > According to the Standard Prelude, > # x ** y = exp (log x * y) I had a feeling this would be the cause. > > log 0 > -Infinity Oh. So... since when does Haskell know about infinity? BTW, I recently had some code like this: foo x | x < 0 = ... | x == 0 = ... | x > 0 = ... I was most perplexed when I got a "non-exhaustive patterns" exception... It turns out there was a NaN in there. I forget about that. > > exp (log 0 * 2) > 0.0 Well that's interesting. I did wonder why it *doesn't* break in the real case... > On to the complex number case. From the standard for Complex: > > # log z = log (magnitude z) :+ phase z > > # phase (0 :+ 0) = 0 > This is a special case for the phase of zero. > > # (x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x') > > > log (0 :+ 0) > (-Infinity) :+ 0.0 > > > log (0 :+ 0) * 2 > (-Infinity) :+ NaN > > Which is the source of the problem. The imaginary part involves > multiplying (-Infinity) by the > imaginary part of 2 (i.e. 0), which is NaN. Um... why would infinity * 0 be NaN? That doesn't make sense... > So no, its not a bug, its according to the standard. So I'm the only person who was expecting zero squared to be zero? (IMHO the standard should try to implement mathematical operations in a mathematically sensible way...) > While working through this I also came across the following case which > technically is a bug: > > > 0 ** 0 > 1.0 > > > exp (log 0 * 0) > NaN > > I suspect that GHCi is using a built-in exponentiation operator that > doesn't quite conform to the standard in this case. Now that really *is* odd... From mfn-haskell-cafe at cs.york.ac.uk Sat Aug 4 11:38:40 2007 From: mfn-haskell-cafe at cs.york.ac.uk (Matthew Naylor) Date: Sat Aug 4 11:34:38 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <00e101c7d6a7$beee76d0$901d8351@cr3lt> References: <175831851.20070804154711@gmail.com> <00e101c7d6a7$beee76d0$901d8351@cr3lt> Message-ID: <20070804153840.GA30929@venice.cs.york.ac.uk> Hi Claus, > but the point is that you have a standard set of operations > when working at that level, including conditionals, assignments, > pointer increments, read/write, etc. you only need to define > lifted variants of each of those operations *once*, in a library. I think that defining lifted versions of every function is dangerous, especially in a widely-used library. Monadic code will start to look pure, and before long someone will be using let expressions and where blocks to share monadic computations rather than using do blocks to share the *results* of monadic computations. Matt. From lennart at augustsson.net Sat Aug 4 11:47:16 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Sat Aug 4 11:39:26 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B49D60.402@btinternet.com> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> Message-ID: Haskell doesn't know much about infinity, but Haskell implementations are allowed to use IEEE floating point which has infinity. And to get things right, there needs to be a few changes to the library to do the right thing for certain numbers, this is not news. In fact I filed a bug report a while back about it. -- Lennart On 8/4/07, Andrew Coppin wrote: > > Paul Johnson wrote: > > Andrew Coppin wrote: > >> > 0**2 > >> 0 > >> > >> > (0 :+ 0)**2 > >> NaN :+ NaN > >> > >> (Is this a bug?) > > According to the Standard Prelude, > > # x ** y = exp (log x * y) > > I had a feeling this would be the cause. > > > > log 0 > > -Infinity > > Oh. So... since when does Haskell know about infinity? > > BTW, I recently had some code like this: > > foo x > | x < 0 = ... > | x == 0 = ... > | x > 0 = ... > > I was most perplexed when I got a "non-exhaustive patterns" exception... > It turns out there was a NaN in there. I forget about that. > > > > exp (log 0 * 2) > > 0.0 > > Well that's interesting. I did wonder why it *doesn't* break in the real > case... > > > On to the complex number case. From the standard for Complex: > > > > # log z = log (magnitude z) :+ phase z > > > > # phase (0 :+ 0) = 0 > > This is a special case for the phase of zero. > > > > # (x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x') > > > > > log (0 :+ 0) > > (-Infinity) :+ 0.0 > > > > > log (0 :+ 0) * 2 > > (-Infinity) :+ NaN > > > > Which is the source of the problem. The imaginary part involves > > multiplying (-Infinity) by the > > imaginary part of 2 (i.e. 0), which is NaN. > > Um... why would infinity * 0 be NaN? That doesn't make sense... > > > So no, its not a bug, its according to the standard. > > So I'm the only person who was expecting zero squared to be zero? (IMHO > the standard should try to implement mathematical operations in a > mathematically sensible way...) > > > While working through this I also came across the following case which > > technically is a bug: > > > > > 0 ** 0 > > 1.0 > > > > > exp (log 0 * 0) > > NaN > > > > I suspect that GHCi is using a built-in exponentiation operator that > > doesn't quite conform to the standard in this case. > > Now that really *is* odd... > > _______________________________________________ > 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/haskell-cafe/attachments/20070804/a614e418/attachment.htm From bulat.ziganshin at gmail.com Sat Aug 4 11:48:32 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 4 11:45:00 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt><1662608023.20070804092646@gmail.com><009401c7d687$78608930$901d8351@cr3lt> <175831851.20070804154711@gmail.com> <00e101c7d6a7$beee76d0$901d8351@cr3lt> <1278932794.20070804191914@gmail.com> Message-ID: <1267644489.20070804194832@gmail.com> Hello Brandon, Saturday, August 4, 2007, 7:27:16 PM, you wrote: > On Aug 4, 2007, at 11:19 , Bulat Ziganshin wrote: >> and use it. want to assign a=b/(c+d)? nothing can be easier! just >> define one more macro! > And? Everything above machine code is just "macros" at various > levels of abstraction, including all our favorite higher-level > abstractions. and what you prefer? assembler or high-level language? -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From claus.reinke at talk21.com Sat Aug 4 11:55:18 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Sat Aug 4 11:48:02 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt><1662608023.20070804092646@gmail.com><009401c7d687$78608930$901d8351@cr3lt><175831851.20070804154711@gmail.com><00e101c7d6a7$beee76d0$901d8351@cr3lt> <1278932794.20070804191914@gmail.com> Message-ID: <01df01c7d6af$dbf780c0$901d8351@cr3lt> >> so, there could be a library defining > >> lhs ==: rhs = putMVar <$> lhs <*> rhs ouch! since putMVar is already impure, there's a join missing: lhs ==: rhs = putMVar <$> lhs <*> rhs >> and in your application code, you could write > >> newEmptyMVar ==: putStrLn "hi there" > .. rant deleted .. > and use it. want to assign a=b/(c+d)? nothing can be easier! just > define one more macro! Dear Bulat in your enthusiam, please do not forget to read what is written! the lifted operations combine as the unlifted ones do. so there's one definition each for =, /, +, not one definition for each of their combinations. claus From bulat.ziganshin at gmail.com Sat Aug 4 12:01:35 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 4 11:57:40 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <01df01c7d6af$dbf780c0$901d8351@cr3lt> References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt><1662608023.20070804092646@gmail.com><009401c7d687$78608930$901d8351@cr3lt><175831851.20070804154711@gmail.com><00e101c7d6a7$beee76d0$901d8351@cr3lt> <1278932794.20070804191914@gmail.com> <01df01c7d6af$dbf780c0$901d8351@cr3lt> Message-ID: <1979757155.20070804200135@gmail.com> Hello Claus, Saturday, August 4, 2007, 7:55:18 PM, you wrote: >>> so, there could be a library defining >> >>> lhs ==: rhs = putMVar <$> lhs <*> rhs > the lifted operations combine as the unlifted ones do. so there's > one definition each for =, /, +, not one definition for each of > their combinations. it's called doublethinking :) when you count operations, you count only primitive ones. when you say about easiness of programming, you propose to define special operation for each access pattern. it's obvious for you that using only standard operations, it's hard to read and write code, and using special operations, you will need to define special one for each usage pattern -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From jbapple+haskell-cafe at gmail.com Sat Aug 4 12:11:37 2007 From: jbapple+haskell-cafe at gmail.com (Jim Apple) Date: Sat Aug 4 12:03:48 2007 Subject: [Haskell-cafe] Developing Programs and Proofs Spontaneously using GADT In-Reply-To: <544F41C1-FFAC-47C5-B3B9-2DD3291FC570@iis.sinica.edu.tw> References: <544F41C1-FFAC-47C5-B3B9-2DD3291FC570@iis.sinica.edu.tw> Message-ID: On 8/4/07, Shin-Cheng Mu wrote: > Unfortunately, unlike Omega, Haskell does not provide type > functions. Something similar is coming: http://haskell.org/haskellwiki/GHC/Indexed_types#Instance_declarations_2 > Haskell does not know that Plus m n is actually > a function and cannot conclude that i=k. > > To explicitly state the equality, we assume that there is > a function plusFn which, given a proof of m + n = i and > a proof of m + n = k, yields a function converting an i > in any context to a k. That is: > > plusFn :: Plus m n i -> Plus m n k > -> (forall f . f i -> f k) > [snip] > How do I define plusFn? I would like to employ the techniques > related to equality types [3,4,5], but currently I have not > yet figured out how. plusFn :: Plus m n h -> Plus m n k -> f h -> f k plusFn PlusZ PlusZ x = x plusFn (PlusS p1) (PlusS p2) x = case plusFn p1 p2 Equal of Equal -> x data Equal a b where Equal :: Equal a a Jim From claus.reinke at talk21.com Sat Aug 4 12:11:32 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Sat Aug 4 12:03:51 2007 Subject: [Haskell-cafe] Re: monad subexpressions References: <175831851.20070804154711@gmail.com><00e101c7d6a7$beee76d0$901d8351@cr3lt> <20070804153840.GA30929@venice.cs.york.ac.uk> Message-ID: <01e201c7d6b2$20cbac10$901d8351@cr3lt> > I think that defining lifted versions of every function is dangerous, > especially in a widely-used library. Monadic code will start to look > pure, and before long someone will be using let expressions and where > blocks to share monadic computations rather than using do blocks to > share the *results* of monadic computations. yes. we actually had that fun with Conal Elliott's functional reactive programming libraries, where all expressions were lifted to a reader monad for time (expressions not mentioning time were constant, those mentioning time were dependent on the overall progress of time). the limitations of overloading (Bool, mostly) and the variations of sharing possible in expressions overloaded this way led to quite a bit of research as well as implementation and language extensions. it is a borderline case: it results in an embedded domain-specific language that looks a lot like haskell, but isn't haskell. as long as one keeps the difference in mind, it is useful, though. having such overloaded operations in an edsl for low-level imperative programming in haskell might be worthwhile, and since some people have been asking for it, i wanted to point out that it is possible. for general use, i agree that explicit control (using idioms perhaps) is safer. although there are functional languages that are based on the everything is monadic-io slogan (scheme, lisp, mls,..). the monad subexpressions under discussion are somewhere in between those extremes, with some syntactic differences, some control, and their own complications. claus From andrewcoppin at btinternet.com Sat Aug 4 12:16:48 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 4 12:08:32 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> Message-ID: <46B4A670.6050803@btinternet.com> Lennart Augustsson wrote: > Haskell doesn't know much about infinity, but Haskell implementations > are allowed to use IEEE floating point which has infinity. > And to get things right, there needs to be a few changes to the > library to do the right thing for certain numbers, this is not news. > In fact I filed a bug report a while back about it. It's news to me that the IEEE floating point standard defines infinity. (NaN I knew about...) From allbery at ece.cmu.edu Sat Aug 4 12:44:46 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sat Aug 4 12:36:58 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <1267644489.20070804194832@gmail.com> References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt><1662608023.20070804092646@gmail.com><009401c7d687$78608930$901d8351@cr3lt> <175831851.20070804154711@gmail.com> <00e101c7d6a7$beee76d0$901d8351@cr3lt> <1278932794.20070804191914@gmail.com> <1267644489.20070804194832@gmail.com> Message-ID: On Aug 4, 2007, at 11:48 , Bulat Ziganshin wrote: > Hello Brandon, > > Saturday, August 4, 2007, 7:27:16 PM, you wrote: > >> On Aug 4, 2007, at 11:19 , Bulat Ziganshin wrote: > >>> and use it. want to assign a=b/(c+d)? nothing can be easier! just >>> define one more macro! > >> And? Everything above machine code is just "macros" at various >> levels of abstraction, including all our favorite higher-level >> abstractions. > > and what you prefer? assembler or high-level language? That would be why I'm using a language which lets me compose things in complex ways. And just once, abstracting it away into a library, which you seem to be missing. -- 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 apfelmus at quantentunnel.de Sat Aug 4 12:53:36 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Sat Aug 4 12:45:58 2007 Subject: [Haskell-cafe] Re: Developing Programs and Proofs Spontaneously using GADT In-Reply-To: <544F41C1-FFAC-47C5-B3B9-2DD3291FC570@iis.sinica.edu.tw> References: <544F41C1-FFAC-47C5-B3B9-2DD3291FC570@iis.sinica.edu.tw> Message-ID: Shin-Cheng Mu wrote: > I am curious about the possibility of developing Haskell programs > spontaneously with proofs about their properties and have the > type checker verify the proofs for us, in a way one would do in > a dependently typed language. > > In the exercise below, I tried to redo part of the merge-sort > example in Altenkirch, McBride, and McKinna's introduction to > Epigram [1]: deal the input list into a binary tree, and fold > the tree by the function merging two sorted lists into one. > The property I am going to show is merely that the length of > the input list is preserved. Cool! :) > Given that dependent types and GADTs are such popular topics, > I believe the same must have been done before, and there may be > better ways to do it. If so, please give me some comments or > references. Any comments are welcomed. > >> {-# OPTIONS_GHC -fglasgow-exts #-} > > To begin with, we define the usual type-level representation > of natural numbers and lists indexed by their lengths. > >> data Z = Z deriving Show >> data S a = S a deriving Show > >> data List a n where >> Nil :: List a Z >> Cons :: a -> List a n -> List a (S n) > > 1. Append > > To warm up, let us see the familiar "append" example. > Unfortunately, unlike Omega, Haskell does not provide type > functions. I am not sure which is the best way to > emulate type functions. One possibility is to introduce > the following GADT: > >> data Plus m n k where --- m + n = k >> PlusZ :: Plus Z n n >> PlusS :: Plus m n k -> Plus (S m) n (S k) > > such that Plus m n k represents a proof that m + n = k. Wouldn't type families (~ associated type synonyms) do exactly that once they become available? type family Plus :: * -> * -> * type instance Plus Z n = n type instance Plus (S m) n = S (Plus m n) append :: (Plus m n ~ k) => List a m -> List a n -> List a k append Nil ys = ys append (Cons x xs) ys = Cons x (append xs ys) But I'd guess that there are some constraints on the type family instance declarations to keep things decidable. Viewed with the dictionary translation for type classes in mind, this is probably exactly the alternative type of append you propose: append :: Plus m n k -> List a m -> List a n -> List a k > However, this does not type check. Assume that t has size > n1, and u has size n. The DepSum returned by merge consists > of a list of size i, and a proof p of type Plus m n i, for > some i. The proof p1, on the other hand, is of type P m n k > for some k. Haskell does not know that Plus m n is actually > a function and cannot conclude that i=k. > > To explicitly state the equality, we assume that there is > a function plusFn which, given a proof of m + n = i and > a proof of m + n = k, yields a function converting an i > in any context to a k. That is: > > plusFn :: Plus m n i -> Plus m n k > -> (forall f . f i -> f k) > > How do I define plusFn? I would like to employ the techniques > related to equality types [3,4,5], but currently I have not > yet figured out how. I've merely produced a version of > plusFn specialised to List a: > >> plusFn :: Plus m n h -> Plus m n k -> List a h -> List a k >> plusFn PlusZ PlusZ xs = xs >> plusFn (PlusS p1) (PlusS p2) (Cons x xs) = >> Cons x (plusFn p1 p2 xs) > > Needless to say this is not satisfactory. I remember that the newtype Equal a b = Proof (forall f . f a -> f b) type equality has been used to define/implement GADTs Ralf Hinze. Fun with phantom types. http://www.informatik.uni-bonn.de/~ralf/publications/With.pdf so a general plusFn ought to be possible. I think that the following induction should work (untested!): equalZ :: Equal Z Z equalS :: Equal m n -> Equal (S n) (S m) plusFn :: Plus m n i -> Plus m n k -> Equal i k plusFn PlusZ PlusZ = equalZ plusFn (PlusS x) (PlusS y) = equalS (plusFn x y) with the "trivial" equality proofs for natural numbers equalZ = Proof id newtype Succ f a = InSucc { outSucc :: f (S a) } equalS (Proof eq) = Proof (outSucc . eq . InSucc) The newtype is just for making the type checker recognize that f (S a) is indeed of the form g a for some type constructor g . Regards, apfelmus From paul at cogito.org.uk Sat Aug 4 13:06:41 2007 From: paul at cogito.org.uk (Paul Johnson) Date: Sat Aug 4 12:58:53 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B4A670.6050803@btinternet.com> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> <46B4A670.6050803@btinternet.com> Message-ID: <46B4B221.4040704@cogito.org.uk> Andrew Coppin wrote: > It's news to me that the IEEE floating point standard defines > infinity. (NaN I knew about...) See http://en.wikipedia.org/wiki/IEEE_754 Paul. From paul at cogito.org.uk Sat Aug 4 13:07:47 2007 From: paul at cogito.org.uk (Paul Johnson) Date: Sat Aug 4 13:00:00 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B49D60.402@btinternet.com> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> Message-ID: <46B4B263.7060106@cogito.org.uk> Andrew Coppin wrote: > Paul Johnson wrote: >> > log 0 >> -Infinity > Oh. So... since when does Haskell know about infinity? I should have mentioned that the underlying platform in my case is an Intel P4. Haskell does not specify a floating point implementation; the assumption is that it uses whatever the platform provides because anything else would be horribly inefficient. The P4 implements IEEE floating point, which as Andrew pointed out includes Infinity, -Infinity and NaN as special cases of floating point values. It also seems to distinguish between 0.0 and (-0.0), although they are still equal. For instance: > (-0.0) -0.0 > 1.0 / 0.0 Infinity > 1.0 / (-0.0) -Infinity (Aside: should Infinity etc. be included in the Haskell standard? Or possibly in a Data.Numeric.IEEE extension? They look like constructors, and it would be nice to be able to pattern match on them.) So if you tried these experiments on a non-IEEE platform then you would get different results. You might get exceptions or just wierd big numbers. ISTR someone posted results from a Sun Sparc along these lines some time ago. > foo x > | x < 0 = ... > | x == 0 = ... > | x > 0 = ... > I was most perplexed when I got a "non-exhaustive patterns" > exception... It turns out there was a NaN in there. I forget about that. Nasty. I'll have to bear that one in mind myself. You can detect infinities by equality, but not NaN. > let inf = (1.0 / 0.0) > let nan = inf * 0.0 > inf == inf True >nan == nan False >> > exp (log 0 * 2) >> 0.0 > Well that's interesting. I did wonder why it *doesn't* break in the > real case... I haven't perused the IEEE standard, but I expect it defines something like this: Infinity * 0 = NaN Infinity * _ = Infinity exp Infinity = Infinity exp (-Infinity) = 0 > Um... why would infinity * 0 be NaN? That doesn't make sense... Infinity times anything is Infinity. Zero times anything is zero. So what should Infinity * zero be? There isn't one right answer. In this case the "morally correct" answer is zero, but in other contexts it might be Infinity or even some finite number other than zero. Consider 0.0 / 0.0, which also evaluates to NaN. What should its value be? If you take the limit of (x / x) as x -> 0 then the right answer is 0. On the other hand if you take the limit of (0 / x) as x -> 0 then the right answer is infinity. Worse yet, if you take the limit of (2x / x) as x-> 0 then the right answer is 2. You can pick any finite or infinite value you like. So the only possible answer is NaN. > >> So no, its not a bug, its according to the standard. > > So I'm the only person who was expecting zero squared to be zero? > (IMHO the standard should try to implement mathematical operations in > a mathematically sensible way...) It does *try*. I'm not sure if IEEE arithmetic was actually defined back in 98. It certainly wasn't widely implemented. There might well be a case for revisiting the standard to allow for IEEE values, but you can't mandate them because not all platforms support IEEE arithmetic. >> While working through this I also came across the following case >> which technically is a bug: >> >> > 0 ** 0 >> 1.0 >> >> > exp (log 0 * 0) >> NaN >> >> I suspect that GHCi is using a built-in exponentiation operator that >> doesn't quite conform to the standard in this case. > > Now that really *is* odd... When I said "built in" I meant "built in to the hardware". This is probably another special case defined in the IEEE standard, which is not the same as the Haskell 98 definition. The reason why the IEEE standard was defined in the first place was that floating point software portability was being seriously limited by these corner cases. You would get some numerical code working on a Sun, and then find it broke on a PC because one of them defined (0.0 / 0.0) as 1 and the other defined it as 0. Worse yet, you might find it worked on Intel chips but not IBM or AMD. Programmers also had to code explicit checks for division by zero and implement their own versions of Infinity and NaN in cases where they might appear, which cluttered up the code and slowed down execution. One way out of this morass would be to define Haskell floating point arithmetic as IEEE standard, and document non-conformance for certain platforms. In the long term that is probably the way forwards (do any currently sold chips *not* implement IEEE?). It would also let us include Infinity and NaN as constructors. However it would lead to significant problems when compiling code that used these values on non-IEEE platforms. What do you do then? Paul. From paul at cogito.org.uk Sat Aug 4 13:16:45 2007 From: paul at cogito.org.uk (Paul Johnson) Date: Sat Aug 4 13:08:57 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B4B221.4040704@cogito.org.uk> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> <46B4A670.6050803@btinternet.com> <46B4B221.4040704@cogito.org.uk> Message-ID: <46B4B47D.2030109@cogito.org.uk> Also see http://hal.archives-ouvertes.fr/hal-00128124 before you start on any serious numerical software. Paul. From lennart at augustsson.net Sat Aug 4 13:21:50 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Sat Aug 4 13:14:01 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B4B263.7060106@cogito.org.uk> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> <46B4B263.7060106@cogito.org.uk> Message-ID: The Haskell type class RealFloat has a reasonable number of operations to test for NaN, denormalized numbers, etc. You can also ask if the implementation uses IEEE. -- Lennart On 8/4/07, Paul Johnson wrote: > > Andrew Coppin wrote: > > Paul Johnson wrote: > >> > log 0 > >> -Infinity > > Oh. So... since when does Haskell know about infinity? > I should have mentioned that the underlying platform in my case is an > Intel P4. Haskell does not specify a floating point implementation; the > assumption is that it uses whatever the platform provides because > anything else would be horribly inefficient. The P4 implements IEEE > floating point, which as Andrew pointed out includes Infinity, -Infinity > and NaN as special cases of floating point values. It also seems to > distinguish between 0.0 and (-0.0), although they are still equal. For > instance: > > > (-0.0) > -0.0 > > > 1.0 / 0.0 > Infinity > > > 1.0 / (-0.0) > -Infinity > > (Aside: should Infinity etc. be included in the Haskell standard? Or > possibly in a Data.Numeric.IEEE extension? They look like constructors, > and it would be nice to be able to pattern match on them.) > > So if you tried these experiments on a non-IEEE platform then you would > get different results. You might get exceptions or just wierd big > numbers. ISTR someone posted results from a Sun Sparc along these lines > some time ago. > > foo x > > | x < 0 = ... > > | x == 0 = ... > > | x > 0 = ... > > I was most perplexed when I got a "non-exhaustive patterns" > > exception... It turns out there was a NaN in there. I forget about that. > Nasty. I'll have to bear that one in mind myself. > > You can detect infinities by equality, but not NaN. > > > let inf = (1.0 / 0.0) > > let nan = inf * 0.0 > > inf == inf > True > >nan == nan > False > > >> > exp (log 0 * 2) > >> 0.0 > > Well that's interesting. I did wonder why it *doesn't* break in the > > real case... > I haven't perused the IEEE standard, but I expect it defines something > like this: > > Infinity * 0 = NaN > Infinity * _ = Infinity > exp Infinity = Infinity > exp (-Infinity) = 0 > > Um... why would infinity * 0 be NaN? That doesn't make sense... > Infinity times anything is Infinity. Zero times anything is zero. So > what should Infinity * zero be? There isn't one right answer. In this > case the "morally correct" answer is zero, but in other contexts it > might be Infinity or even some finite number other than zero. > > Consider 0.0 / 0.0, which also evaluates to NaN. What should its value > be? If you take the limit of (x / x) as x -> 0 then the right answer is > 0. On the other hand if you take the limit of (0 / x) as x -> 0 then > the right answer is infinity. Worse yet, if you take the limit of (2x / > x) as x-> 0 then the right answer is 2. You can pick any finite or > infinite value you like. So the only possible answer is NaN. > > > >> So no, its not a bug, its according to the standard. > > > > So I'm the only person who was expecting zero squared to be zero? > > (IMHO the standard should try to implement mathematical operations in > > a mathematically sensible way...) > It does *try*. I'm not sure if IEEE arithmetic was actually defined > back in 98. It certainly wasn't widely implemented. There might well > be a case for revisiting the standard to allow for IEEE values, but you > can't mandate them because not all platforms support IEEE arithmetic. > >> While working through this I also came across the following case > >> which technically is a bug: > >> > >> > 0 ** 0 > >> 1.0 > >> > >> > exp (log 0 * 0) > >> NaN > >> > >> I suspect that GHCi is using a built-in exponentiation operator that > >> doesn't quite conform to the standard in this case. > > > > Now that really *is* odd... > When I said "built in" I meant "built in to the hardware". This is > probably another special case defined in the IEEE standard, which is not > the same as the Haskell 98 definition. > > The reason why the IEEE standard was defined in the first place was that > floating point software portability was being seriously limited by these > corner cases. You would get some numerical code working on a Sun, and > then find it broke on a PC because one of them defined (0.0 / 0.0) as 1 > and the other defined it as 0. Worse yet, you might find it worked on > Intel chips but not IBM or AMD. Programmers also had to code explicit > checks for division by zero and implement their own versions of Infinity > and NaN in cases where they might appear, which cluttered up the code > and slowed down execution. > > One way out of this morass would be to define Haskell floating point > arithmetic as IEEE standard, and document non-conformance for certain > platforms. In the long term that is probably the way forwards (do any > currently sold chips *not* implement IEEE?). It would also let us > include Infinity and NaN as constructors. However it would lead to > significant problems when compiling code that used these values on > non-IEEE platforms. What do you do then? > > Paul. > > _______________________________________________ > 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/haskell-cafe/attachments/20070804/60599f20/attachment-0001.htm From andrewcoppin at btinternet.com Sat Aug 4 13:26:15 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 4 13:18:03 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B4B1AC.5060203@cogito.org.uk> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> <46B4B1AC.5060203@cogito.org.uk> Message-ID: <46B4B6B7.4090005@btinternet.com> > >> Um... why would infinity * 0 be NaN? That doesn't make sense... > Infinity times anything is Infinity. Zero times anything is zero. So > what should Infinity * zero be? There isn't one right answer. In > this case the "morally correct" answer is zero, but in other contexts > it might be Infinity or even some finite number other than zero. I don't follow. Infinity times any positive quantity gives positive infinity. Infinity times any negative quantity gives negative infinity. Infinity times zero gives zero. What's the problem? > Consider 0.0 / 0.0, which also evaluates to NaN. Division by zero is *definitely* undefined. (The equation 0 * k = v has no solutions.) From lennart at augustsson.net Sat Aug 4 13:44:58 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Sat Aug 4 13:37:09 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B4B6B7.4090005@btinternet.com> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> <46B4B1AC.5060203@cogito.org.uk> <46B4B6B7.4090005@btinternet.com> Message-ID: Infinity is a very slippery concept, you can't compute with it like that. You can compute various limits, though. So, e.g., for a > 0 lim x*a -> Inf x->Inf and lim x*0 -> 0 x->Inf But lim x*(1/x) -> 1 x->Inf And that last one would be "Inf*0" in the limit. In fact, you can make Inf*0 any number you like. So NaN is the sensible. -- Lennart On 8/4/07, Andrew Coppin wrote: > > > > > >> Um... why would infinity * 0 be NaN? That doesn't make sense... > > Infinity times anything is Infinity. Zero times anything is zero. So > > what should Infinity * zero be? There isn't one right answer. In > > this case the "morally correct" answer is zero, but in other contexts > > it might be Infinity or even some finite number other than zero. > > I don't follow. > > Infinity times any positive quantity gives positive infinity. > Infinity times any negative quantity gives negative infinity. > Infinity times zero gives zero. > > What's the problem? > > > Consider 0.0 / 0.0, which also evaluates to NaN. > > Division by zero is *definitely* undefined. (The equation 0 * k = v has > no solutions.) > > _______________________________________________ > 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/haskell-cafe/attachments/20070804/500b544b/attachment.htm From igloo at earth.li Sat Aug 4 14:41:39 2007 From: igloo at earth.li (Ian Lynagh) Date: Sat Aug 4 14:33:50 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B49D60.402@btinternet.com> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> Message-ID: <20070804184139.GA2298@matrix.chaos.earth.li> On Sat, Aug 04, 2007 at 04:38:08PM +0100, Andrew Coppin wrote: > > BTW, I recently had some code like this: > > foo x > | x < 0 = ... > | x == 0 = ... > | x > 0 = ... > > I was most perplexed when I got a "non-exhaustive patterns" exception... > It turns out there was a NaN in there. I forget about that. If you use guards then you can get non-exhaustive pattern warnings anyway, e.g.: myNot x | x == True = False | x == False = True gives Warning: Pattern match(es) are non-exhaustive In the definition of `myNot': Patterns not matched: _ as it is (in general) undecidable whether all patterns are covered. > >While working through this I also came across the following case which > >technically is a bug: > > > >> 0 ** 0 > >1.0 > > > >> exp (log 0 * 0) > >NaN > > > >I suspect that GHCi is using a built-in exponentiation operator that > >doesn't quite conform to the standard in this case. Hmm, according to the report the Floating class has a default method x ** y = exp (log x * y) but the Double instance is just instance Floating Double where ... so could define something different. 6.4.3 says 0**y is undefined. Thanks Ian From ndmitchell at gmail.com Sat Aug 4 14:53:14 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Sat Aug 4 14:45:23 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <20070804184139.GA2298@matrix.chaos.earth.li> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> <20070804184139.GA2298@matrix.chaos.earth.li> Message-ID: <404396ef0708041153r51d36f70gf02fc3c8f70bd6a4@mail.gmail.com> Hi If you just use Catch (http://www-users.cs.york.ac.uk/~ndm/catch/): > > foo x > > | x < 0 = ... > > | x == 0 = ... > > | x > 0 = ... This gives an error. Something identical to this code is in Data.FiniteMap, and indeed, when using floats and NaN's (or just silly Ord classes) you can cause Data.FiniteMap to pattern match error. See section 6.3 of the draft paper on the Catch website for details. > myNot x > | x == True = False > | x == False = True This is determined to be exhaustive. > as it is (in general) undecidable whether all patterns are covered. In general, yes. But its possible to do a lot better than GHC's current warnings (I'm not saying its worth changing, though) Thanks Neil From bulat.ziganshin at gmail.com Sat Aug 4 14:51:12 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 4 14:47:13 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt><1662608023.20070804092646@gmail.com><009401c7d687$78608930$901d8351@cr3lt> <175831851.20070804154711@gmail.com> <00e101c7d6a7$beee76d0$901d8351@cr3lt> <1278932794.20070804191914@gmail.com> <1267644489.20070804194832@gmail.com> Message-ID: <1212495777.20070804225112@gmail.com> Hello Brandon, Saturday, August 4, 2007, 8:44:46 PM, you wrote: > That would be why I'm using a language which lets me compose things > in complex ways. And just once, abstracting it away into a library, > which you seem to be missing. and you hate 'do' syntax sugar? -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From trebla at vex.net Sat Aug 4 14:59:39 2007 From: trebla at vex.net (Albert Y. C. Lai) Date: Sat Aug 4 14:51:51 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B468B3.7000704@btinternet.com> References: <46B468B3.7000704@btinternet.com> Message-ID: <46B4CC9B.6090003@vex.net> Andrew Coppin wrote: > > 0^2 > 0 > > > (0 :+ 0)^2 > 0 :+ 0 > > > 0**2 > 0 > > > (0 :+ 0)**2 > NaN :+ NaN There is nothing wrong AFAIK. (How much do I know? BSc in math, went through classes on real analysis and complex analysis.) There is no reason to expect complex ** to agree with real **. Real x**y is first defined for natural y (agreeing with x^y), then extend to integer y (agreeing with x^^y), then extend to rational y (taking nth root when y = m/n), then extend to real y by continuity wherever possible. You can still expect real 0**2 = 0^2 = 0. Complex x**y involves picking a phase angle of x. "Phase angle" is an ill notion for 0. Complex 0**y is better left undefined. You said > So I'm the only person who was expecting zero squared to be zero? Are you trying to be sensational, or are you going hyperbole? If you want zero squared, you're welcome to use 0^2. Complex 0**2 does not have to be related to zero squared. You said > (IMHO the standard should try to implement mathematical > operations in a mathematically sensible way...) But AFAIK it is already a mathematically sensible way - it is what I learned from my math classes. Perhaps you mean highschoolly sensible. I understand that highschool math is a bit simple-minded, e.g., you can greatly confuse someone by 1 = ((-1)**2)**0.5 = ((-1)**0.5)**2) = i**2 = -1 "So I'm the only one expecting x square-root squared to be x?" Thank God complex ** is supposed to be different from real **. From dpiponi at gmail.com Sat Aug 4 15:47:14 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Sat Aug 4 15:39:24 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B4CC9B.6090003@vex.net> References: <46B468B3.7000704@btinternet.com> <46B4CC9B.6090003@vex.net> Message-ID: <625b74080708041247p541e4b4etd931f5d827a91f6c@mail.gmail.com> On 8/4/07, Albert Y. C. Lai wrote: > There is no reason to expect complex ** to agree with real **. There's every reason. It is standard mathematical practice to embed the integers in the rationals in the reals in the complex numbers and it is nice to have as many functions as possible respect that embedding. In particular, it's nice to get a kind of commutativity when we start casting between different numeric types. There's an old paper on this subject by Reynolds (http://lambda-the-ultimate.org/node/2078) though I'm more familiar with the treatment in Pierce's "Basic Category for Computer Scientists". If you look through a variety of complex analysis books you'll find a number of different approaches to handling 0^x for complex x. Many agree that this is defined for Re(x)>0. Some say it is defined for integer x>0. Some say it's not defined at all, and then in the following paragraphs talk about x^2 where x takes values in the entire complex plane. So it seems to me that it is entirely reasonable to hope that (0:+0)**2=0:+0. > Complex x**y involves picking a phase angle of x. "Phase angle" is an > ill notion for 0. Complex 0**y is better left undefined. There is no right answer here, it's a matter of taste. Among mathematicians there doesn't seem to be a uniform consensus. But I think that in computing a commutativity principle is nice to have, so I think we should have x**fromInteger y = x^y, where defined, so that, in some sense, (^) is embedded in (**). -- Dan From derek.a.elkins at gmail.com Sat Aug 4 16:20:43 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Sat Aug 4 16:12:58 2007 Subject: [Haskell-cafe] Developing Programs and Proofs Spontaneously using GADT In-Reply-To: <544F41C1-FFAC-47C5-B3B9-2DD3291FC570@iis.sinica.edu.tw> References: <544F41C1-FFAC-47C5-B3B9-2DD3291FC570@iis.sinica.edu.tw> Message-ID: <1186258843.6796.37.camel@derek-laptop> On Sat, 2007-08-04 at 23:25 +0800, Shin-Cheng Mu wrote: > [...] > In Haskell, the existential quantifier is mimicked by forall. > We define: > > > data DepSum a p = forall i . DepSum (a i) (p i) > > The term "dependent sum" is borrowed from the Omega tutorial > of Sheard, Hook, and Linger [2] (why is it called a sum, > not a product?). There is already a dependent product. One compelling reason for this naming comes from category theory and how they relate to each other (the dependent sum is a left adjoint, the dependent product is a right adjoint [not directly to each other].) They are related in the same way products and sums are related, or universal quantification and existential quantification are. So, looking at the product case (A,B)=AxB (and ()=1) and the sum case Either A B = A+B we can see how they generalize to be the above. Let's say we have a pair of the same type. We can clearly represent it as AxA, but another alternative is 1+1->A. We can write the isomorphism in Haskell: pToF :: (a,a) -> (Either () () -> a) pToF (x,_) (Left ()) = x pToF (_,y) (Right ()) = y fToP :: (Either () () -> a) -> (a,a) fToP f = (f (Left ()), f (Right ())) Similarly for sums, A+A can be written (1+1)xA. Again, the Haskell: sToP :: Either a a -> (Either () (),a) sToP (Left x) = (Left (), x) sToP (Right x) = (Right (), x) pToS :: (Either () (), a) -> Either a a pToS (Left (), x) = Left x pToS (Right (), x) = Right x Incidentally, this is how sums are usually encoded, i.e. a pair of a tag and a value. (Also incidentally, these are almost exactly the isomorphisms defining adjunctions related to the ones that define product and sum, i.e. the above definitions immediately fall out of the category theory.) So how to represent AxB or A+B with this encoding? You can't. However, in a dependently typed language we can write (in some dependently typed pseudo-Haskell) [for concreteness, let's set A=Int, B=String]: f :: Either () () -> Type f (Left ()) = Int f (Right ()) = String Now we use the same definitions as above only with the types, pToF :: (Int,String) -> (s :: Either () () -> f s) fToP :: (s :: Either () () -> f s) -> (Int,String) sToP :: Either Int String -> s :: Either () (). f s pToS :: (s :: Either () (). f s) -> Either Int String This leads to the dependent product being a function space when there is no dependency, and similarly the dependent sum being a (normal) product. From stephen.forrest at gmail.com Sat Aug 4 16:35:54 2007 From: stephen.forrest at gmail.com (Stephen Forrest) Date: Sat Aug 4 16:28:03 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <625b74080708041247p541e4b4etd931f5d827a91f6c@mail.gmail.com> References: <46B468B3.7000704@btinternet.com> <46B4CC9B.6090003@vex.net> <625b74080708041247p541e4b4etd931f5d827a91f6c@mail.gmail.com> Message-ID: <2ea1ace50708041335t5ba11d22o19bcf8561eaeee55@mail.gmail.com> On 8/4/07, Dan Piponi wrote: > > On 8/4/07, Albert Y. C. Lai wrote: > > There is no reason to expect complex ** to agree with real **. > > There's every reason. It is standard mathematical practice to embed > the integers in the rationals in the reals in the complex numbers and > it is nice to have as many functions as possible respect that > embedding. A example I have seen before that illustrates some the difficulties with preserving such behaviour is (-1)^(1/3). Of course, taking the nth root is multi-valued, so if you're to return a single value, you must choose a convention. Many implementations I have seen choose the solution with lowest argument (i.e. the first solution encounted by a counterclockwise sweep through the plane starting at (1,0).) With this interpretation, (-1)^(1/3) = 0.5 + sqrt(3)/2 * i. If you go with the real solution (-1) you might need to do so carefully in order to preserve other useful properties of ^, like continuity. Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070804/f7eadf87/attachment.htm From drl at cs.cmu.edu Sat Aug 4 16:59:29 2007 From: drl at cs.cmu.edu (Dan Licata) Date: Sat Aug 4 16:51:41 2007 Subject: [Haskell-cafe] Developing Programs and Proofs Spontaneously using GADT In-Reply-To: <1186258843.6796.37.camel@derek-laptop> References: <544F41C1-FFAC-47C5-B3B9-2DD3291FC570@iis.sinica.edu.tw> <1186258843.6796.37.camel@derek-laptop> Message-ID: <20070804205929.GA29902@cs.cmu.edu> Another way of understanding the terminology is this: A "dependent product" type (usually written \Pi x:A.B) can be thought of as a big product of the types (B[a1/x], ..., B[aN/x]) for the inhabitants a1...aN of the type A. To introduce a dependent product, you have to provide each component of the tuple. To eliminate a dependent product, you can project out one component. A "dependent sum" type (usually written \Sigma x:A.B) can be thought of as a big sum of the types B[a1/x] + ... + B[aN/x], where again a1 .. aN are all the inhabitants of A. To introduce a dependent sum, you pick a particular branch of the sum (by choosing an a_i) and inject a value of that type (i.e., B[a_i/x]). To eliminate a dependent sum, you can see what branch a value is in (i.e., recover the a_i) and you can see what the associated data is. This terminology takes a little getting used to because of how we usually present these intro and elim forms syntactically. Consider dependent products. For finite products (e.g., (Int, String)) we introduce a product just by writing down an inhabitant of each component type. However, the dependent product needs one component for each inhabitant of the type A, so we can't in general list them all explicitly. Thus, the usual intro form for a dependent product is to give an inhabitant of B for a generic inhabitant x of A (i.e., a variable x:A). So the intro form is a function. On the other hand, to eliminate a finite product we usually say "I'd like the 2nd component, please". But for a dependent product, you have to say "I'd like the a_i^th component", so the elim is application. Sums are similar. For a finite sum, we usually say "this data is in the second branch", but for a dependent sum, we have to say "this data is in the a_i^th branch". So the intro form is a pair of a tag a_i and a value of type B[a_i/x]. On the other hand, to eliminate a finite sum, we usually do a case with one branch for each of the tags, where in each branch we get the tagged value. To eliminate a dependent sum, we cover all those cases at once by getting (1) a generic tag x:A and (2) a value of the type associated with that tag. But this is exactly a split (x,y) = e1 in e2 pattern-matching style elimination form for a pair. So, dependent products are represented by functions, and dependent sums are represented by pairs. It's confusing at first, but it's established terminology. I tend to use "dependent function" and "dependent pair" myself, since sometimes people use "dependent product" to mean \Sigma rather than \Pi (understandable given the intro and elim for \Sigma!), so I sometimes find it ambiguous. Does that make sense? -Dan On Aug04, Derek Elkins wrote: > On Sat, 2007-08-04 at 23:25 +0800, Shin-Cheng Mu wrote: > > > [...] > > In Haskell, the existential quantifier is mimicked by forall. > > We define: > > > > > data DepSum a p = forall i . DepSum (a i) (p i) > > > > The term "dependent sum" is borrowed from the Omega tutorial > > of Sheard, Hook, and Linger [2] (why is it called a sum, > > not a product?). > > There is already a dependent product. One compelling reason for this > naming comes from category theory and how they relate to each other (the > dependent sum is a left adjoint, the dependent product is a right > adjoint [not directly to each other].) They are related in the same way > products and sums are related, or universal quantification and > existential quantification are. So, looking at the product case > (A,B)=AxB (and ()=1) and the sum case Either A B = A+B we can see how > they generalize to be the above. > > Let's say we have a pair of the same type. We can clearly represent it > as AxA, but another alternative is 1+1->A. We can write the isomorphism > in Haskell: > pToF :: (a,a) -> (Either () () -> a) > pToF (x,_) (Left ()) = x > pToF (_,y) (Right ()) = y > > fToP :: (Either () () -> a) -> (a,a) > fToP f = (f (Left ()), f (Right ())) > > Similarly for sums, A+A can be written (1+1)xA. Again, the Haskell: > sToP :: Either a a -> (Either () (),a) > sToP (Left x) = (Left (), x) > sToP (Right x) = (Right (), x) > > pToS :: (Either () (), a) -> Either a a > pToS (Left (), x) = Left x > pToS (Right (), x) = Right x > > Incidentally, this is how sums are usually encoded, i.e. a pair of a tag > and a value. (Also incidentally, these are almost exactly the > isomorphisms defining adjunctions related to the ones that define > product and sum, i.e. the above definitions immediately fall out of the > category theory.) > > So how to represent AxB or A+B with this encoding? You can't. However, > in a dependently typed language we can write (in some dependently typed > pseudo-Haskell) [for concreteness, let's set A=Int, B=String]: > f :: Either () () -> Type > f (Left ()) = Int > f (Right ()) = String > > Now we use the same definitions as above only with the types, > pToF :: (Int,String) -> (s :: Either () () -> f s) > fToP :: (s :: Either () () -> f s) -> (Int,String) > sToP :: Either Int String -> s :: Either () (). f s > pToS :: (s :: Either () (). f s) -> Either Int String > > This leads to the dependent product being a function space when there is > no dependency, and similarly the dependent sum being a (normal) product. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From dpiponi at gmail.com Sat Aug 4 17:06:53 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Sat Aug 4 16:59:02 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <2ea1ace50708041335t5ba11d22o19bcf8561eaeee55@mail.gmail.com> References: <46B468B3.7000704@btinternet.com> <46B4CC9B.6090003@vex.net> <625b74080708041247p541e4b4etd931f5d827a91f6c@mail.gmail.com> <2ea1ace50708041335t5ba11d22o19bcf8561eaeee55@mail.gmail.com> Message-ID: <625b74080708041406h94d8ce8hbe798315cf30e85e@mail.gmail.com> On 8/4/07, Stephen Forrest wrote: > Of course, taking the nth root is multi-valued, so if you're to return a > single value, you must choose a convention. Many implementations I have > seen choose the solution with lowest argument (i.e. the first solution > encounted by a counterclockwise sweep through the plane starting at (1,0).) This is one approach but not the one used by some languages. Another way of looking at it is this: a function like log is multivalued as you pass around the origin. So what you can do is 'cut' the complex plane so that you're not allowed to cross the cuts. Now you have a region on which a single-valued function can be unambiguously defined. It's fairly standard practice, when documenting functions of a complex variable, to specify precisely which 'branch cuts' are being used. Here's a quote from the Mathematica documentation describing their Log function: "Log[z] has a branch cut discontinuity in the complex z plane running from -infinity to 0". > With this interpretation, (-1)^(1/3) = 0.5 + sqrt(3)/2 * i. If you go with > the real solution (-1) you might need to do so carefully in order to > preserve other useful properties of ^, like continuity. You can guarantee this by making sure you make the right 'cuts'. -- Dan From newsham at lava.net Sat Aug 4 17:46:37 2007 From: newsham at lava.net (Tim Newsham) Date: Sat Aug 4 17:38:48 2007 Subject: [Haskell-cafe] FreeBSD/amd64 support? Message-ID: I noticed that there is no official FreeBSD/amd64 port yet, although there's a binary with a working "ghc" but non-working "ghci." Has there been any progress on the amd64 port? Any estimate on when it will be available? Any known workarounds (is it possible to install and run an x86 ghc in FreeBSD/amd64)? Is hardware access holding anyone up? Tim Newsham http://www.thenewsh.com/~newsham/ From magnus at therning.org Sat Aug 4 18:59:37 2007 From: magnus at therning.org (Magnus Therning) Date: Sat Aug 4 18:51:53 2007 Subject: [Haskell-cafe] c2hs and structs? Message-ID: <20070804225937.GA5657@die.therning.org> I can't seem to find any information on how to deal with C functions that return a (pointer to a) struct. C2hs tells me there's no automatic support for marshalling structs (I'm using version 0.14.5). If I'm to do it by hand, is there a preferred way? (E.g. make the type adhere to the type Storable.) /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus@therning.org Jabber: magnus.therning@gmail.com http://therning.org/magnus Unreadable code, Why would anyone use it? Learn a better way. -- Geoff Kuenning's contribution to the 2004 Perl Haiku Contest, Haikus about Perl - 'Dishonerable Mention' winner -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070804/36ec9da2/attachment.bin From allbery at ece.cmu.edu Sat Aug 4 22:47:38 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sat Aug 4 22:40:05 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <1212495777.20070804225112@gmail.com> References: <1539063779.20070803143725@gmail.com><00f401c7d5cf$f120be70$14217ad5@cr3lt><785460922.20070803173640@gmail.com><015501c7d5e3$1847ce40$14217ad5@cr3lt><1662608023.20070804092646@gmail.com><009401c7d687$78608930$901d8351@cr3lt> <175831851.20070804154711@gmail.com> <00e101c7d6a7$beee76d0$901d8351@cr3lt> <1278932794.20070804191914@gmail.com> <1267644489.20070804194832@gmail.com> <1212495777.20070804225112@gmail.com> Message-ID: On Aug 4, 2007, at 14:51 , Bulat Ziganshin wrote: > Hello Brandon, > > Saturday, August 4, 2007, 8:44:46 PM, you wrote: > >> That would be why I'm using a language which lets me compose things >> in complex ways. And just once, abstracting it away into a library, >> which you seem to be missing. > > and you hate 'do' syntax sugar? Not particularly; I use both do and >>= (even intermixing them), although I'm uncertain that *teaching* Haskell should start with the "do" notation. Your point being? -- 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 dons at cse.unsw.edu.au Sat Aug 4 23:40:20 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Sat Aug 4 23:32:31 2007 Subject: [Haskell-cafe] Haskell FCGI server. In-Reply-To: References: Message-ID: <20070805034019.GA15153@cse.unsw.EDU.AU> george.moschovitis: > > is it possible to create a FCGI server that listens to a > specific port using the Haskell FCGI library? > The front end web server would then communicate with this > back end FCGI server through this port. > A small example would be really appreciated. > thanks, Yep, certainly possible. lambdaweb does this, as should others. AFAIK its just like using fastcgi in any other language. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/fastcgi-3000.0.0 -- Don From bertram.felgenhauer at googlemail.com Sun Aug 5 02:11:03 2007 From: bertram.felgenhauer at googlemail.com (Bertram Felgenhauer) Date: Sun Aug 5 02:03:20 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <351474761.20070804123804@gmail.com> References: <3d96ac180708031114i2f1ab07awc9e98897648aa491@mail.gmail.com> <01dd01c7d5fe$b9f1f5c0$14217ad5@cr3lt> <3d96ac180708031416x5ea6008bk5f6b51c62a5a9f43@mail.gmail.com> <351474761.20070804123804@gmail.com> Message-ID: <20070805061103.GA4583@zombie.inf.tu-dresden.de> Bulat Ziganshin wrote: > Hello apfelmus, > > Saturday, August 4, 2007, 12:18:33 PM, you wrote: > > > Then, mytransaction reads > > > mytransaction = return foo `apT` xvar0 `apT` xvar1 `apT` ... > > how about a+b*(c+d)? That follows the same pattern, return (+) `apT` a `apT` (return (*) `apT` b `apT` (return (+) `apT` c `apT` d)) Bertram From daniel.is.fischer at web.de Sun Aug 5 10:39:39 2007 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Aug 5 10:31:06 2007 Subject: [Haskell-cafe] Re: Knuth Morris Pratt for Lazy Bytestrings implementation In-Reply-To: <46B0F320.7090600@list.mightyreason.com> References: <46B0CB29.5080101@list.mightyreason.com> <46B0F320.7090600@list.mightyreason.com> Message-ID: <200708051632.41297.daniel.is.fischer@web.de> Am Mittwoch, 1. August 2007 22:54 schrieb ChrisK: > My optimized (and fixed) version of the code is attached. I adapted my KMP implementation from one and a half years ago to the problem at hand (no longer search and replace, only find index of first match, and change from Strings to ByteStrings), on my computer, for the few tests I performed, it's about 30-40% faster than Chris' (depending on the input). Chris, could you check whether this holds for your benchmark? If so, any polishing and further optimisations are welcome; if that should be the basis of an addition to the ByteString lib, I'd feel very honoured (in other words, if you consider it useful code, you're welcome to use it). Cheers, Daniel -- KMP algorithm for lazy ByteStrings {-# OPTIONS_GHC -fbang-patterns #-} module KMP (kmpMatch) where import qualified Data.Array.Base as Base (unsafeAt) import Data.Array.Unboxed (UArray, listArray) import qualified Data.Array as A (listArray, (!), elems) import qualified Data.ByteString.Lazy as B import qualified Data.ByteString as S import qualified Data.ByteString.Base as B (unsafeHead, unsafeTail, unsafeDrop, unsafeIndex) import Data.Int (Int64) import Data.Word (Word8) kmpMatch :: B.ByteString -> B.ByteString -> Int64 kmpMatch patLazy search | B.null patLazy = 0 | otherwise = kmp 0 0 search where pat :: S.ByteString pat = S.concat (B.toChunks patLazy) patLen = S.length pat sym :: Int -> Word8 sym = B.unsafeIndex pat bord = A.listArray (0,patLen) $ (-1):0:[getS (sym i) i + 1 | i <- [1 .. patLen - 1]] where getS s n | m < 0 || s == sym m = m | otherwise = getS s m where m = bord A.! n borders :: UArray Int Int borders = listArray (0,patLen) $ A.elems bord (?) :: UArray Int Int -> Int -> Int (?) = Base.unsafeAt getShift :: Word8 -> Int -> Int getShift s n = help n where help k | m < 0 || sym m == s = m | otherwise = help m where m = borders ? k kmp :: Int64 -> Int -> B.ByteString -> Int64 kmp !idx !match !srch | patLen == match = idx - fromIntegral match | B.null srch = -1 | sym match == B.head srch = kmp (idx+1) (match+1) (B.tail srch) | match == 0 = kmp (idx+1) 0 (B.tail srch) | otherwise = case getShift (B.head srch) match of -1 -> kmp idx 0 srch 0 -> kmp (idx+1) 1 (B.tail srch) shft -> kmp (idx + fromIntegral shft) (shft+1) (B.tail srch) From daniel.is.fischer at web.de Sun Aug 5 11:59:18 2007 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Aug 5 11:50:42 2007 Subject: [Haskell-cafe] Re: Knuth Morris Pratt for Lazy Bytestrings implementation In-Reply-To: <200708051632.41297.daniel.is.fischer@web.de> References: <46B0F320.7090600@list.mightyreason.com> <200708051632.41297.daniel.is.fischer@web.de> Message-ID: <200708051759.18400.daniel.is.fischer@web.de> Oooops, stupid error before, fixed below. Missed it due to too few and simple tests, should've quickchecked :-/ > > Cheers, > Daniel > > -- KMP algorithm for lazy ByteStrings > {-# OPTIONS_GHC -fbang-patterns #-} > module KMP (kmpMatch) where > > import qualified Data.Array.Base as Base (unsafeAt) > import Data.Array.Unboxed (UArray, listArray) > import qualified Data.Array as A (listArray, (!), elems) > > import qualified Data.ByteString.Lazy as B > import qualified Data.ByteString as S > import qualified Data.ByteString.Base as B (unsafeHead, unsafeTail, > unsafeDrop, unsafeIndex) > import Data.Int (Int64) > import Data.Word (Word8) > > kmpMatch :: B.ByteString -> B.ByteString -> Int64 > kmpMatch patLazy search > > | B.null patLazy = 0 > | otherwise = kmp 0 0 search > > where > pat :: S.ByteString > pat = S.concat (B.toChunks patLazy) > patLen = S.length pat > sym :: Int -> Word8 > sym = B.unsafeIndex pat > bord = A.listArray (0,patLen) $ > (-1):0:[getS (sym i) i + 1 | i <- [1 .. patLen - 1]] > where > getS s n > > | m < 0 || s == sym m = m > | otherwise = getS s m > > where > m = bord A.! n > borders :: UArray Int Int > borders = listArray (0,patLen) $ A.elems bord > (?) :: UArray Int Int -> Int -> Int > (?) = Base.unsafeAt > getShift :: Word8 -> Int -> Int > getShift s n = help n > where > help k > > | m < 0 || sym m == s = m > | otherwise = help m > > where > m = borders ? k > kmp :: Int64 -> Int -> B.ByteString -> Int64 > kmp !idx !match !srch > > | patLen == match = idx - fromIntegral match > | B.null srch = -1 > | sym match == B.head srch = kmp (idx+1) (match+1) (B.tail > | srch) match == 0 = kmp (idx+1) 0 (B.tail srch) > | otherwise = > case getShift (B.head srch) match of > -1 -> kmp idx 0 srch > shft -> kmp (idx+1) (shft+1) (B.tail srch) From feeder.of.the.bears at gmail.com Sun Aug 5 18:19:25 2007 From: feeder.of.the.bears at gmail.com (David Pollak) Date: Sun Aug 5 18:11:33 2007 Subject: [Haskell-cafe] Navigating Haddock Message-ID: Howdy, As I'm starting to learn the Haskell libraries, I'm having a less than fun time trying to figure out what functions operate on what types. For example, in the documentation for HaXml, there's a description of Document: http://www.cs.york.ac.uk/fp/HaXml/HaXml/Text-XML-HaXml-Types.html#4 However, I can't find any links to what functions accept document as a parameter. Am I missing some magic? A couple of other questions... Can ByteStrings be substituted anywhere that takes a String (e.g., HaXml xmlParse)? Is there a way to deal with UTF-8 encoded byte arrays converting them to Strings other than http://www.gatago.org/fa/haskell/52409638.html ? Thanks, David -- lift, the fast, powerful, easy web framework http://liftweb.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070805/7baed281/attachment.htm From mmitar at gmail.com Sun Aug 5 18:46:21 2007 From: mmitar at gmail.com (Mitar) Date: Sun Aug 5 18:38:27 2007 Subject: [Haskell-cafe] Interval Arithmetics Message-ID: Hi! First, disclaimer: everything I know about interval arithmetics comes from this video: http://video.google.com/videoplay?docid=-2285617608766742834 I would like to know if there is any implementation of interval arithmetics in Haskell? I would like to play a little with that. I checked the web and the straightforward approach I found: http://cs.guc.edu.eg/faculty/sabdennadher/Publikationen/paper-wflp99.ps.gz has from my point of view invalid implementation. For example, lower bound in the sum should not be just calculated as the sum of lower bounds of summands. It should return the greatest representable number which is smaller or equal to the exact value of the sum. With just boldly making a sum we ignore any errors we could introduce and this is somehow against the idea of interval arithmetics. And as it is said at the end of the talk, a system behind interval arithmetics should do a lot of work to make those intervals as small as possible while still correct and counting in all the errors we accumulated. I think a strict-typed and lazy language like Haskell would be a good place to implement this. But I would like to know if this would be possible to do from the language itself, without making changes to the compiler and/or runtime itself? Because, for example, a good implementation should reformulate equations at the runtime accordingly to exact values it wants to compute them on. Has it been done already? Mitar From fb at frank-buss.de Sun Aug 5 18:48:02 2007 From: fb at frank-buss.de (Frank Buss) Date: Sun Aug 5 18:40:12 2007 Subject: [Haskell-cafe] creating graphics the functional way Message-ID: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> I've created a small program to compose images with combinators: http://www.frank-buss.de/haskell/OlympicRings.hs.txt It produces TGA output, but I've converted it to PNG, because this is smaller: http://www.frank-buss.de/haskell/OlympicRings.png This is my first larger Haskell program and I have some questions: Nearly anything works without thinking too much about the types, but I don't like the use of fromInteger in the average and main functions. Is it possible that the integers are automaticly converted to floats? There are many functions like circle1Center, circle2Center, ... Is it possible to rewrite the program that it will be shorter, maybe using lists or an interpreter for a language for this kind of combinator programming style? Is it possible to write functions with an arbitrary number of arguments? Would be nice if the average function would accept any number of pixel values. Is there a PNG writer library for Haskell? I've seen a zlib interface, should be not too difficult to implement it in Haskell itself. Finally, what do you think about using this concept for generating images? It has some advantages, e.g. it is possible to scale the image without quality loss. But it needs some improvement, e.g. the anti-aliasing doesn't look very smooth. And it is very slow, it needs about 40 seconds on my computer to calculate the image. Using parametrized combinators sounds like a good idea for an interactive interface, like it is implemented in this program: http://www.theprodukkt.com/werkkzeug1#28 But this is impossible, if changing one parameter needs so long to update the image. -- Frank Buss, fb@frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From marco-oweber at gmx.de Sun Aug 5 19:12:41 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Sun Aug 5 19:05:22 2007 Subject: [Haskell-cafe] Navigating Haddock In-Reply-To: References: Message-ID: <20070805231033.GB7286@gmx.de> On Sun, Aug 05, 2007 at 03:19:25PM -0700, David Pollak wrote: > Howdy, > As I'm starting to learn the Haskell libraries, I'm having a less than > fun time trying to figure out what functions operate on what types. > For example, in the documentation for HaXml, there's a description of > Document: > [1]http://www.cs.york.ac.uk/fp/HaXml/HaXml/Text-XML-HaXml-Types.html#4 > However, I can't find any links to what functions accept document as a > parameter. Am I missing some magic? There might be better answers. Some ways to achieve what you want: a) use hoogle (haskell.org/hoogle). You can use hoogle to find functions by types. But I don't know haw to create a query such as ... -> Document -> ... b) Use a file search by content tool (grep ...) to either grep the haddock documentation or the source files. c) Use ghci and the :browse command .. (again grep will help) (eg $ghci -package HaXml :browse Text.XML.HaXml.Combinators ) but you need to invoke this command for each module.. You can get a list of exposed modules by querying ghc-pkg.. This kind of references might make sense on special types such as Document, but not on types such as Int (there would be too many matches) > A couple of other questions... > Can ByteStrings be substituted anywhere that takes a String (e.g., > HaXml xmlParse)? In general yes, you should be able to use ByteStrings wherever a String is used.. But remember that a String has some syntactic suggar becuase it's treated as list. Thus the : operator won't work with ByteStrings (I'm sure the module does define functions providing the same functionality) > Is there a way to deal with UTF-8 encoded byte arrays converting them > to Strings other than [2]http://www.gatago.org/fa/haskell/52409638.html Don't know. Marc Weber PS: you wrote: "accept document as a parameter" Be careful with upper /lower case. You want the type *D*ocument here, not the argument named document. From ithika at gmail.com Sun Aug 5 19:16:26 2007 From: ithika at gmail.com (Dougal Stanton) Date: Sun Aug 5 19:08:33 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> Message-ID: <2d3641330708051616k4c69304j811dde3bdb0e7cf1@mail.gmail.com> On 05/08/07, Frank Buss wrote: > Is it possible to write functions with an arbitrary number of arguments? > Would be nice if the average function would accept any number of pixel > values. I think it's possible in some sense, because the Haskell interpretation of printf() works in the normal way. But there might be a bit of voodoo involved. Easier is to just pass a list of arguments to calculate over. (The following is neither correct nor fast...) > avg xs = sum xs `div` length xs Cheers, D. From marco-oweber at gmx.de Sun Aug 5 19:34:59 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Sun Aug 5 19:28:12 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> Message-ID: <20070805233459.GC7286@gmx.de> On Mon, Aug 06, 2007 at 12:48:02AM +0200, Frank Buss wrote: > I've created a small program to compose images with combinators: > > http://www.frank-buss.de/haskell/OlympicRings.hs.txt > > It produces TGA output, but I've converted it to PNG, because this is > smaller: > > http://www.frank-buss.de/haskell/OlympicRings.png > > This is my first larger Haskell program and I have some questions: > > Nearly anything works without thinking too much about the types, but I don't > like the use of fromInteger in the average and main functions. Is it (floor ((fromInteger (r1+r2+r3+r4)) / 4)) ... what about using `div` instead of / ? (ghci sesion) :Loading package base ... linking ... done. Prelude> :t (/) (/) :: (Fractional a) => a -> a -> a Prelude> :t div div :: (Integral a) => a -> a -> a Prelude> There has been a short discussion about this.. > possible that the integers are automaticly converted to floats? > Is it possible to write functions with an arbitrary number of arguments? > Would be nice if the average function would accept any number of pixel > values. I think I've read this question on #haskell once.. The answer of someone else was that he even could'nt think of it... Using one argument for each pixel would be overkill.. because you don't need different kinds of arguments here. So a list should be fine, shouldn't it? There are also some approaches of fixed length lists /Database/HaskellDB/BoundedString.hs (from package haskelldb) and the module SList http://www.haskell.org/haskellwiki/Applications_and_libraries/Data_structures#Serialising_data (-> SList) Think of an error message showing a function having 10.000 arguments? .. - No thanks :) Anyway.. you should have a look at http://haskell.org/haskellwiki/Applications_and_libraries (-> Graphics) Package Haven.. I think this library does what you want as well. Perhaps Pan is also interesting. But I haven't tried either of them yet. Marc Weber From marco-oweber at gmx.de Sun Aug 5 19:39:32 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Sun Aug 5 19:32:18 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: <20070805233459.GC7286@gmx.de> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> <20070805233459.GC7286@gmx.de> Message-ID: <20070805233932.GD7286@gmx.de> > > Nearly anything works without thinking too much about the types, but I don't > > like the use of fromInteger in the average and main functions. Is it I've forgotten to attach this link: http://www.nabble.com/Perl-style-numeric-type-t3948269.html (perhaps use the threaded view to read all messages) Marc From ok at cs.otago.ac.nz Sun Aug 5 22:02:17 2007 From: ok at cs.otago.ac.nz (ok) Date: Sun Aug 5 21:54:28 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <46B32261.1070807@ira.uka.de> References: <1539063779.20070803143725@gmail.com> <46B31269.7010805@ira.uka.de> <155949898.20070803155804@gmail.com> <46B32261.1070807@ira.uka.de> Message-ID: <25AF4A0A-1092-4261-A07F-568F3EE3C4BE@cs.otago.ac.nz> On 4 Aug 2007, at 12:41 am, Mirko Rahn wrote: > >>>> rewrite *p++=*q++ in haskell? > >> it's one of C idioms. probably, you don't have enough C experience to >> understand it :) > > Maybe, but how can *you* understand it, when the standard is vague > about it? > > It could be > > A: *p=*q; p+=1; q+=1; > B: *p=*q; q+=1; p+=1; > C: tp=p; tq=q; p+=1; q+=1; *tp=*tq; > > ...and so on. Which is the "right" version? The standard makes it perfectly clear that they ALL are, as they all produce exactly the same effect. The only case where the exact translation could matter is when the two variables are the same, which the standard forbids (and yes, there are static checkers for that, and smart C programmers use them). Some message I didn't see suggested that good C programmers use memcpy() rather than *p++ = *q++. I would point out that the assignment form is type checked and memcpy() is not, so memcpy() is not always to be preferred. > readability depends on the reader as your C example shows. Some > Haskellers would very quickly recognize some common idioms, where > others need some help... *p++ = *q++ is indeed a C idiom and it is presented and described in the classic C book by Kernighan & Ritchie, which one expects competent C programmers to have read. C does indeed have grave weaknesses, but there are better targets for derision than this. From brianh at metamilk.com Sun Aug 5 23:03:02 2007 From: brianh at metamilk.com (Brian Hulley) Date: Sun Aug 5 22:55:01 2007 Subject: [Haskell-cafe] Re: monad subexpressions Message-ID: <46B68F66.3070502@metamilk.com> On Fri Aug 3 06:06:31 EDT Neil Mitchell wrote: > What are the semantics of > do b >> f (<- a) > where does the evaluation of a get lifted to? I suggest the execution of (a) should be done immediately before the action obtained by applying the monadic function whose argument it is part of: do b >> ( a >>= \ra -> f ra) Similarly, I'd desugar if (<- a) then f (<- b) else g (<- c) to a >>= \ra -> if ra then (b >>= \rb -> f rb) else (c >>= \rc -> g rc) I think it would just be confusing to have to think about lines in the "do" block since "do" blocks are just syntactic sugar. The only possible thing that might be needed by the "do" block is to define what monad the action should be evaluated in. Perhaps the rule could be that if (<- a) occurs in some expression the compiler should search for the nearest enclosing "do" block to identify which monad (a) should be evaluated in, then should again search outwards from the expression (<- a) to find the nearest enclosing expression (mexp) which yields a result in that same monad, then desugar to (a >>= \ra -> mexp') where mexp' is obtained from mexp by replacing that occurrence of (<- a) by (ra). (Evaluations would be done in the same order as depth first traversal of their occurrences in mexp) Regarding objections by others about (<- a) being confused with a section, (<-) is not a valid operator therefore it can't be part of a section so no confusion should arise imho... Best regards, Brian. From scm at iis.sinica.edu.tw Sun Aug 5 23:31:09 2007 From: scm at iis.sinica.edu.tw (Shin-Cheng Mu) Date: Sun Aug 5 23:23:19 2007 Subject: [Haskell-cafe] Re: Developing Programs and Proofs Spontaneously using GADT In-Reply-To: <20070804171408.2D5B3324AC1@www.haskell.org> References: <20070804171408.2D5B3324AC1@www.haskell.org> Message-ID: <4A9BAF3B-16CA-4A3F-A888-A717A609E07C@iis.sinica.edu.tw> Thanks for the comments. I will take a look at the type family extension. The definition of plusFn proposed by Jim Apple worked nicely. The solution from apfelmus works after fixing a small typo: > newtype Equal a b = Proof (forall f . f a -> f b ) > > newtype Succ f a = InSucc { outSucc :: f (S a) } > > equalZ :: Equal Z Z > equalZ = Proof id > > equalS :: Equal m n -> Equal (S m) (S n) -- was (S n) (S m) > equalS (Proof eq) = Proof (outSucc . eq . InSucc) > > plusFn :: Plus m n i -> Plus m n k -> Equal i k > plusFn PlusZ PlusZ = Proof id > plusFn (PlusS x) (PlusS y) = equalS (plusFn x y) Also thanks to Derek Elkins and Dan Licata for interesting discussions about dependent sum/product. :) sincerely, Shin From ok at cs.otago.ac.nz Mon Aug 6 01:28:14 2007 From: ok at cs.otago.ac.nz (ok) Date: Mon Aug 6 01:24:37 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <46B4B6B7.4090005@btinternet.com> References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> <46B4B1AC.5060203@cogito.org.uk> <46B4B6B7.4090005@btinternet.com> Message-ID: <4A163E2E-B989-4169-AADB-5DC291B30730@cs.otago.ac.nz> On 5 Aug 2007, at 5:26 am, Andrew Coppin wrote: > > Infinity times any positive quantity gives positive infinity. > Infinity times any negative quantity gives negative infinity. > Infinity times zero gives zero. > > What's the problem? That in IEEE arithmetic, infinity times zero is *NOT* zero. Everything becomes clear if you think +0 = some non-standard real bigger than 0 but smaller than any standard positive real, a possibly different one every time -0 = some non-standard real smaller than 0 but bigger than any non-standard negative real, a possibly different one every time +oo = 1/(+0), remembering that this is a possibly different one each time -oo = 1/(-0) So +oo * +0 is (1/eps1) * eps2 = eps2/eps1 which could have *any* positive non-standard real value. >> Consider 0.0 / 0.0, which also evaluates to NaN. > > Division by zero is *definitely* undefined. No, division by zero is perfectly well defined in IEEE arithmetic. If x is a strictly positive number then x/(+0) = +Infinity. If x is a strictly negative number then x/(+0) = -Infinity. positive/(-0) = (-positive)/(+0) = -Infinity. negative/(-0) = (-negative)/(+0) = +Infinity. Once again, everything becomes clear when you realise that IEEE arithmetic doesn't really represent 0 but instead has a pair of non-standard reals one on either side (except that you can never depend on exactly what the value is). So 1/(+0) is clearly 1/eps1 = some big non-standard real = +Infinity, but +0/+0 is eps1/eps2 and we don't know what that is. I know that the signed zero and infinities stuff is mathematically odd, but it's closely related to the ability to write floating point stuff without exception handling, so that if at the end you got NaN something went wrong (and you need to try another method), otherwise it didn't. The C99 standard (a draft of which is easy to find on the web) is perhaps the easiest place to find out what this means for functions other than the classical arithmetic operations. (Personally I've always thought that sqrt(-0) = -0 was more confusing than anyone needed, but I can see why they did it.) From alex at alexjacobson.com Mon Aug 6 03:55:06 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Mon Aug 6 03:47:25 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? Message-ID: <46B6D3DA.6020304@alexjacobson.com> This implementation of calculating 10000 primes (compiled with GHC -O2) is 25% slower than the naive python implementation. Shouldn't it be faster? Am I doing something obviously stupid? primes = map (\(x,_,_)->x) $ filter (\(_,isP,_)->isP) candidates candidates = (2,True,[]):(3,True,[]): map next (tail candidates) next (candidate,isP,modCounts) = let newCounts = map incrMod2 modCounts in -- accumulate mods (candidate+2 -- we only need to bother with odd numbers ,(isPrime newCounts) -- track whether this one is prime ,if isP then (candidate,2):newCounts else newCounts) -- add if prime isPrime = and . map ((/=0).snd) incrMod2 (p,mc) = let mc' = mc+2 in if mc'

p then (p,1) else (p,0) Note: It is shorter than the python, but I would have assumed that GHC could deliver faster as well. -Alex- From dons at cse.unsw.edu.au Mon Aug 6 04:03:15 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Mon Aug 6 03:55:22 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: <46B6D3DA.6020304@alexjacobson.com> References: <46B6D3DA.6020304@alexjacobson.com> Message-ID: <20070806080315.GH13048@cse.unsw.EDU.AU> alex: > This implementation of calculating 10000 primes (compiled with GHC -O2) > is 25% slower than the naive python implementation. Shouldn't it be > faster? Am I doing something obviously stupid? Why not just: primes = sieve [2..] sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p > 0] main = print (take 1000 primes) That's super naive, and seems to be around 5x faster than the code you were trying. (So make sure you're doing the same thing as the python version) -- Don From dons at cse.unsw.edu.au Mon Aug 6 04:09:32 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Mon Aug 6 04:01:42 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> Message-ID: <20070806080932.GI13048@cse.unsw.EDU.AU> ptanimoto: > I haven't tried any of those codes, but Don did you notice you're > calculating 1,000 primes while Alex was talking about 10,000? Yeah, I tested both with 1k and 10k :) From alex at alexjacobson.com Mon Aug 6 04:15:46 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Mon Aug 6 04:08:00 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: <20070806080315.GH13048@cse.unsw.EDU.AU> References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> Message-ID: <46B6D8B2.8050708@alexjacobson.com> The challenge was the implement the modcount algorithm not to calculate primes per se. (see e.g. http://jjinux.blogspot.com/2005/11/io-comparison.html). -Alex- Donald Bruce Stewart wrote: > alex: >> This implementation of calculating 10000 primes (compiled with GHC -O2) >> is 25% slower than the naive python implementation. Shouldn't it be >> faster? Am I doing something obviously stupid? > > Why not just: > > primes = sieve [2..] > > sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p > 0] > > main = print (take 1000 primes) > > That's super naive, and seems to be around 5x faster than the code you were > trying. (So make sure you're doing the same thing as the python version) > > -- Don From alex at alexjacobson.com Mon Aug 6 04:22:26 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Mon Aug 6 04:14:44 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: <46B6D8B2.8050708@alexjacobson.com> References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> <46B6D8B2.8050708@alexjacobson.com> Message-ID: <46B6DA42.6020805@alexjacobson.com> Thought perhaps the problem is that modcount is just a slower algorithm. ... nevermind. Thanks. -Alex- Alex Jacobson wrote: > The challenge was the implement the modcount algorithm not to calculate > primes per se. > (see e.g. http://jjinux.blogspot.com/2005/11/io-comparison.html). > > -Alex- > > Donald Bruce Stewart wrote: >> alex: >>> This implementation of calculating 10000 primes (compiled with GHC >>> -O2) is 25% slower than the naive python implementation. Shouldn't >>> it be faster? Am I doing something obviously stupid? >> >> Why not just: >> >> primes = sieve [2..] >> >> sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p > 0] >> >> main = print (take 1000 primes) >> >> That's super naive, and seems to be around 5x faster than the code you >> were >> trying. (So make sure you're doing the same thing as the python version) >> -- Don > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From tanimoto at u.arizona.edu Mon Aug 6 04:23:50 2007 From: tanimoto at u.arizona.edu (Paulo Tanimoto) Date: Mon Aug 6 04:15:55 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: <46B6D8B2.8050708@alexjacobson.com> References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> <46B6D8B2.8050708@alexjacobson.com> Message-ID: Alex: > The challenge was the implement the modcount algorithm not to calculate > primes per se. > (see e.g. http://jjinux.blogspot.com/2005/11/io-comparison.html). Can you show us the Python code? Paulo From apfelmus at quantentunnel.de Mon Aug 6 04:37:42 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Mon Aug 6 04:30:08 2007 Subject: [Haskell-cafe] Re: creating graphics the functional way In-Reply-To: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> Message-ID: Frank Buss wrote: > I've created a small program to compose images with combinators: > > http://www.frank-buss.de/haskell/OlympicRings.hs.txt > > Finally, what do you think about using this concept for generating > images? It has some advantages, e.g. it is possible to scale the > image without quality loss. But it needs some improvement, e.g. the > anti-aliasing doesn't look very smooth. And it is very slow, it > needs about 40 seconds on my computer to calculate the image. The idea of representing images simply by a function Int -> Int -> RGB is great :) You may want to look at Pan and its various offsprings, in particular Pancito http://www.haskell.org/haskellwiki/Applications_and_libraries/Graphics#Pan Unfortunately, there's not much you can do about the speed. Pan is faster, but it creates the illusion that you're programming in Haskell while internally, it compiles the image generation code to C++. Very clever, but hard to maintain and one of the reasons why it only works on Windows. > There are many functions like circle1Center, circle2Center, ... Is it > possible to rewrite the program that it will be shorter, maybe using lists > or an interpreter for a language for this kind of combinator programming > style? Well, you have lists for that type Point = (Int,Int) positions :: [Point] positions = zip [0.5 + fromIntegral n * dx | n <- [-2..2]] (cycle [y1,y2]) where dx = 0.125 y1 = 0.15 y2 = 0.25 colors :: [RGB] colors = [blue, yellow, black, green, red] type Image = Point -> RGB circles :: RGB -> [Image] circles background = map circle (zip positions colors) where circle (p,c) = fillMask (translate p ringCenter) c $ fillMask (translate p ringOutline) white background > Is it possible to write functions with an arbitrary number of arguments? > Would be nice if the average function would accept any number of pixel > values. Lists are the natural choice here. > Is there a PNG writer library for Haskell? I've seen a zlib interface, > should be not too difficult to implement it in Haskell itself. Not that I know of. But gtk2hs has a Cairo-binding and I guess this one supports PNG. Note that this is vector graphics though, your approach is more general. Regards, apfelmus From apfelmus at quantentunnel.de Mon Aug 6 04:50:22 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Mon Aug 6 04:42:38 2007 Subject: [Haskell-cafe] Re: Navigating Haddock In-Reply-To: <20070805231033.GB7286@gmx.de> References: <20070805231033.GB7286@gmx.de> Message-ID: Marc Weber wrote: > On Sun, Aug 05, 2007 at 03:19:25PM -0700, David Pollak wrote: >> Howdy, >> As I'm starting to learn the Haskell libraries, I'm having a less than >> fun time trying to figure out what functions operate on what types. >> For example, in the documentation for HaXml, there's a description of >> Document: >> [1]http://www.cs.york.ac.uk/fp/HaXml/HaXml/Text-XML-HaXml-Types.html#4 >> However, I can't find any links to what functions accept document as a >> parameter. Am I missing some magic? > > There might be better answers. Some ways to achieve what you want: > a) use hoogle (haskell.org/hoogle). You can use hoogle to find functions by types. But I don't > know haw to create a query such as ... -> Document -> ... Hoogle unfortunately doesn't do that very well, although that would be a great feature. But I think that Text.XML.HaXml isn't indexed by Hoogle anyway? >> A couple of other questions... >> Can ByteStrings be substituted anywhere that takes a String (e.g., >> HaXml xmlParse)? > > In general yes, you should be able to use ByteStrings wherever a String > is used.. > But remember that a String has some syntactic suggar becuase it's > treated as list. Thus the : operator won't work with ByteStrings (I'm > sure the module does define functions providing the same functionality) Eh? These two are different types, you have to pack and unpack to convert between. But note that this most likely voids the performance gains from ByteString . In other words, if a library function needs a String , there's not much you can do. However, Henning Thielemann reported that his use of HaXml (I think) for the parallel web (see http://haskell.org/haskellwiki/Monad#Fun) works well with Strings. Regards, apfelmus From scm at iis.sinica.edu.tw Mon Aug 6 04:58:56 2007 From: scm at iis.sinica.edu.tw (Shin-Cheng Mu) Date: Mon Aug 6 04:51:03 2007 Subject: [Haskell-cafe] Re: creating graphics the functional way In-Reply-To: <20070806015437.9958F3241EE@www.haskell.org> References: <20070806015437.9958F3241EE@www.haskell.org> Message-ID: On 05/08/07, Frank Buss wrote: > Is it possible to write functions with an arbitrary number of > arguments? > Would be nice if the average function would accept any number of pixel > values. You may be interested to see Oleg Kiselyov's discussion on polyvariadic functions in Haskell: http://okmij.org/ftp/Haskell/types.html#polyvar-fn sincerely, Shin From j.vimal at gmail.com Mon Aug 6 05:09:38 2007 From: j.vimal at gmail.com (Vimal) Date: Mon Aug 6 05:01:42 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: <20070806080315.GH13048@cse.unsw.EDU.AU> References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> Message-ID: > > Why not just: > > primes = sieve [2..] > > sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p > 0] > > main = print (take 1000 primes) > I am unable to see how exactly this will run. Given that primes is an infinite list, and that when it reaches numbers say, as large as 10000, it will have to keep track of all the numbers (essentially prime numbers, which is the answer), whose mutliples it has to remove! Say for eg: I give > take 100 primes 2 : [ 3...] then 2:3:[4 ... ] It will *now* have to remove 4, 2:3:[5...] Then 2:3:5:[6 ...] Now. It has to remove 6, based on the fact that it was a multiple of 2 ... (or 3? Which one comes first?) This happens in a different order than what would be expected generally in a sieve :-) So, the question is, does this improve efficiency? -- Vimal From dav.vire+haskell at gmail.com Mon Aug 6 05:25:04 2007 From: dav.vire+haskell at gmail.com (david48) Date: Mon Aug 6 05:17:08 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> Message-ID: <4c88418c0708060225i416ef265x198b074ceba12b5e@mail.gmail.com> On 8/6/07, Vimal wrote: > I am unable to see how exactly this will run. Given that primes is an infinite > list, and that when it reaches numbers say, as large as 10000, it will have to > keep track of all the numbers (essentially prime numbers, which is the answer), > whose mutliples it has to remove! > > Say for eg: I give > > take 100 primes > 2 : [ 3...] > then 2:3:[4 ... ] > It will *now* have to remove 4, > 2:3:[5...] > Then 2:3:5:[6 ...] Isn't it how it runs ? : 2: sieve [3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45, 47,49,... ] then 2:3:sieve [5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,... ] then 2:3:5:sieve [7,11,13,17,19,23,29,31,37,41,43,47,49,... ] then 2:3:5:7:sieve [11,13,17,19,23,29,31,37,41,43,47,... ] then 2:3:5:7:11:sieve [13,17,19,23,29,31,37,41,43,47,... ] etc... From hughperkins at gmail.com Mon Aug 6 05:26:32 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Mon Aug 6 05:18:38 2007 Subject: [Haskell-cafe] Perfect example In-Reply-To: <625b74080708030746n112ba14boee79fb1463c5531a@mail.gmail.com> References: <200708022002.14755.jon@ffconsultancy.com> <625b74080708030746n112ba14boee79fb1463c5531a@mail.gmail.com> Message-ID: <837db430708060226q336ba672j2a52fe55f37077b3@mail.gmail.com> There's a neat Haskell solution to the knapsack problem which runs very fast. I'm not 100% sure that it runs faster than an optimal solution in other GC'd imperative languages, but it's very concise and not (too) convoluted. Have a search for the thread with "xkcd" in the title. Chung-chieh Shan wrote: Here's my solution to the xkcd problem (yay infinite lists): xkcd_c287' = foldr (\cost without -> let (poor, rich) = splitAt cost without with = poor ++ zipWith (++) rich (map (map (cost:)) with) in with) ([[]] : repeat []) [215, 275, 335, 355, 420, 580] -- [2, 4, 150001] !! 1505 -- 150005 Replacing the two lines with comments by the comments solves your case quickly. Explication of how it works from "haskell@list.mightyreason.com": I will jump in and explain, using a more finely named version: xkcd_c287' = foldr (\cost without -> let (poor, rich) = splitAt cost without with = poor ++ zipWith (++) rich using_cost using cost = (map (add_cost) with) where add_cost xs = cost:xs in with) ([[]] : repeat []) [215, 275, 335, 355, 420, 580] -- [2, 4, 150001] !! 1505 -- 150005 At the top level it uses (!!) to pick the 1505th element of the list produced by the use of foldr. foldr Here the list of new values is the list of item prices (in pennies) from the menu. The seed result is the answer in the absence of anything on the menu. The seed is ([[]] : repeat []) which is a list of (list of prices). The "n th" member of the outer list holds the solution for a price of "n pennies". Thus the (!! 1505) selects the answer for a target price of $15.05. The seed result has an empty list in the 0th position since ordering nothing is a solution to a target price of $0.00. The function works as follows: > (\cost without -> The 'cost' is the price of the new item on the menu. The 'without' is the answer taking into account all previously processed items on the menu (before the 'cost' item). The result will be a new answer taking into account 'cost' as well. > let (poor, rich) = splitAt cost without The items in the old answer 'without' before the index 'cost' are solutions for a target price cheaper than 'cost' and these are in the 'poor' list. These answers are unchanged by the addition of the 'cost' item. The items in the 'rich' part of the answer may get new solutions that include ordering the new 'cost' item. > with = poor ++ zipWith (++) rich using_cost > using cost = (map add_cost with) > where add_cost xs = cost:xs > in with) The new answer will be 'with' which is defined recursively. The first elements of 'with' are the 'poor' parts of the old answer 'without' that are obviously unchanged. The 'zipWith (++) rich using_cost' combines the previous 'rich' answers without 'cost' with a new list that uses the 'cost' item. This is: using cost = (map add_cost with) where add_cost xs = cost:xs The using_cost list is made from taking the list of answers and prepending the 'cost' item to all the solutions. If this were applied to 'without' instead of 'with'... using cost = (map add_cost without) where add_cost xs = cost:xs ...then the definition of 'with' would not be recursive and would allow for solutions that only order each menu item 0 or 1 times. Since the definition of using_cost does apply the map to 'with' it can add_cost to answers that already have has add_cost applied to them. Thus it finds all answers that order the menu items 0,1,2,3.. arbitrarily many times. The "n th" item in 'with' or 'without' has total price of "n", and after add_cost it has a total price of "cost+n", and must be in the "(cost+n)th" position in the answer 'with'. This is achieve by the using_cost items being after the (poor ++) which means they have been shifted by (length poor) positions which, by the definition of (splitN cost), is equal to 'cost'. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070806/7162aba5/attachment.htm From duncan.coutts at worc.ox.ac.uk Mon Aug 6 05:34:26 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Mon Aug 6 05:25:21 2007 Subject: [Haskell-cafe] c2hs and structs? In-Reply-To: <20070804225937.GA5657@die.therning.org> References: <20070804225937.GA5657@die.therning.org> Message-ID: <1186392866.5989.305.camel@localhost> On Sat, 2007-08-04 at 23:59 +0100, Magnus Therning wrote: > I can't seem to find any information on how to deal with C functions > that return a (pointer to a) struct. C2hs tells me there's no automatic > support for marshalling structs (I'm using version 0.14.5). > > If I'm to do it by hand, is there a preferred way? (E.g. make the type > adhere to the type Storable.) Yes, you want to make it an instance of Storable. You can use c2hs's get and set hooks to help with this. Duncan From j.vimal at gmail.com Mon Aug 6 05:35:51 2007 From: j.vimal at gmail.com (Vimal) Date: Mon Aug 6 05:27:56 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: <4c88418c0708060225i416ef265x198b074ceba12b5e@mail.gmail.com> References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> <4c88418c0708060225i416ef265x198b074ceba12b5e@mail.gmail.com> Message-ID: > Isn't it how it runs ? : > > 2: sieve [3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45, > 47,49,... ] > then > 2:3:sieve [5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,... ] > then > 2:3:5:sieve [7,11,13,17,19,23,29,31,37,41,43,47,49,... ] > then > 2:3:5:7:sieve [11,13,17,19,23,29,31,37,41,43,47,... ] > then > 2:3:5:7:11:sieve [13,17,19,23,29,31,37,41,43,47,... ] > etc... > Well well, see how the values are requested for: print (take 1000 primes) So, after sieve completes its action, the first 1000 elements are taken. Since Haskell is lazy, it doesnt do beyond 1000. I would expect your argument to hold good for something like this: primes n = sieve (take n [2..]) sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p > 0] print (primes 1000) -- Vimal From j.vimal at gmail.com Mon Aug 6 05:37:59 2007 From: j.vimal at gmail.com (Vimal) Date: Mon Aug 6 05:30:05 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> <4c88418c0708060225i416ef265x198b074ceba12b5e@mail.gmail.com> Message-ID: > primes n = sieve (take n [2..]) > sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p > 0] > print (primes 1000) > > -- Vimal But as we can see, this obviously doesn't *take* 1000 primes, :-) -- Vimal From ndmitchell at gmail.com Mon Aug 6 06:01:26 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Mon Aug 6 05:53:31 2007 Subject: [Haskell-cafe] Re: Navigating Haddock In-Reply-To: References: <20070805231033.GB7286@gmx.de> Message-ID: <404396ef0708060301i7b2678e8m406229fe0c2f99f7@mail.gmail.com> Hi > > a) use hoogle (haskell.org/hoogle). You can use hoogle to find functions by types. But I don't > > know haw to create a query such as ... -> Document -> ... > > Hoogle unfortunately doesn't do that very well, although that would be a > great feature. Wait for version 4 :-) - I've added _ 's for wildcard types, _ -> Document -> _ would give you what you want. I've also made it so a search for "Document" can give you all the types which involve document in any way. > But I think that Text.XML.HaXml isn't indexed by Hoogle > anyway? Version 4 will be capable of indexing all of hackage, so hopefully that can be done. Thanks Neil From voigt at tcs.inf.tu-dresden.de Mon Aug 6 06:17:22 2007 From: voigt at tcs.inf.tu-dresden.de (Janis Voigtlaender) Date: Mon Aug 6 06:09:28 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> Message-ID: <46B6F532.3070601@tcs.inf.tu-dresden.de> Vimal wrote: >>Why not just: >> >> primes = sieve [2..] >> >> sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p > 0] >> >> main = print (take 1000 primes) >> > > > I am unable to see how exactly this will run. Given that primes is an infinite > list, and that when it reaches numbers say, as large as 10000, it will have to > keep track of all the numbers (essentially prime numbers, which is the answer), > whose mutliples it has to remove! > > Say for eg: I give > >>take 100 primes > > 2 : [ 3...] > then 2:3:[4 ... ] > It will *now* have to remove 4, > 2:3:[5...] > Then 2:3:5:[6 ...] > Now. It has to remove 6, based on the fact that it was a multiple of 2 ... > (or 3? Which one comes first?) > > This happens in a different order than what would be expected > generally in a sieve :-) To get a grip on the order in which things are sieved, try the following little experiment (should also work for other sieves): The original sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p > 0] is equivalent (by desugaring the list comprehension) to sieve (p : xs) = p : sieve (filter (\x -> x `mod` p > 0) xs) To see the non-primes as well, replace the filter with a map, where the result type is an Either, with Left for primes and Right for non-primes. To keep track of which modules have been tested for each given number, let the element type of the Either-alternatives be a pair consisting of the number and the list of checked modules. This gives: sieve (Left l@(p,_) : xs) = Left l : sieve (map (either (\(x,e) -> (if x `mod` p > 0 then Left else Right) (x,p:e)) Right) xs) sieve (r : xs) = r : sieve xs Now try: > sieve [Left (i,[]) | i <-[2..]] [Left (2,[]),Left (3,[2]),Right (4,[2]),Left (5,[3,2]),Right (6,[2]),Left (7,[5,3,2]),Right (8,[2]),Right (9,[3,2]),Right (10,[2]),Left (11,[7,5,3,2]),... The Left-entries are primes, the Right-entries are non-primes, and the second element of each pair shows against which modules the first pair element has been checked (in reverse order). Ciao, Janis. -- Dr. Janis Voigtlaender http://wwwtcs.inf.tu-dresden.de/~voigt/ mailto:voigt@tcs.inf.tu-dresden.de From alex at alexjacobson.com Mon Aug 6 07:30:43 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Mon Aug 6 07:23:04 2007 Subject: [Haskell-cafe] how to make haskell faster than python at finding primes? In-Reply-To: References: <46B6D3DA.6020304@alexjacobson.com> <20070806080315.GH13048@cse.unsw.EDU.AU> <46B6D8B2.8050708@alexjacobson.com> Message-ID: <46B70663.8090908@alexjacobson.com> Paulo Tanimoto wrote: >> The challenge was the implement the modcount algorithm not to calculate >> primes per se. >> (see e.g. http://jjinux.blogspot.com/2005/11/io-comparison.html). > > Can you show us the Python code? Note this is python for the naive, accumulate and do modulus version. Not for modcount. See below for ocaml version of modcount. Having slept a few hours, I still think the modcount version should be faster than the naive version because you don't have to recalculate a full modulues operator for each new value. You just increment and check equality. So would love to get short fast haskell modcount. -Alex- --- #!/usr/bin/env python -OO """Find prime numbers. See usage() for more information. Author: JJ Behrens Date: Sun Dec 30 03:36:58 PST 2001 Copyright: (c) JJ Behrens Description: Find prime numbers. See usage() for more information. The algorithm used to determine if a given number, n, is prime is to keep a list of prime numbers, p's, less than n and check if any p is a factor of n. """ import sys """Output usage information to the user. mesg -- If this is not NULL, it will be output first as an error message. """ def usage(mesg): if mesg: sys.stderr.write("Error: %s\n" % mesg) sys.stderr.write("Usage: %s NUMBER_OF_PRIMES\n" % sys.argv[0]) sys.stderr.write("Print out the first NUMBER_OF_PRIMES primes.\n") if mesg: sys.exit(1) else: sys.exit(0) """Output a prime number in a nice manner.""" def printPrime(p): print p """Is numCurr prime? primeRecList -- This is the list of primes less than num_curr. """ def isPrime(numCurr, primeRecList): for p in primeRecList: if not numCurr % p: return 0 else: return 1 """Print out the first numPrimes primes. numPrimes must be positive, of course. """ FIRST_PRIME = 2 def findPrimes(numPrimes): numCurr = FIRST_PRIME - 1 primeRecList = [] while numPrimes > 0: numCurr += 1 if isPrime(numCurr, primeRecList): numPrimes -= 1 printPrime(numCurr) primeRecList.append(numCurr) if len(sys.argv) != 2: usage("missing NUMBER_OF_PRIMES") try: numPrimes = int(sys.argv[1]) if numPrimes < 1: raise ValueError except ValueError: usage("NUMBER_OF_PRIMES must be a positive integer") findPrimes(numPrimes) ------------ (* Author: JJ Behrens Date: Sun Nov 4 02:42:42 PST 2001 Copyright: (c) JJ Behrens Description: Find prime numbers. See usage() for more information. The algorithm used to determine if a given number, n, is prime is to keep a list of tuples (p, mc) where each p is a prime less than n and each mc is n % p. If n is prime, then no mc is 0. The effeciency of this algorithm is wholly determined by how efficiently one can maintain this list. mc does not need to be recalculated using a full % operation when moving from n to n + 1 (increment and then reset to 0 if mc = p). Furthermore, another performance enhancement is to use lazy evaluation of mc (i.e. collect multiple increments into one addition and one modulo--this avoids a traversal of the entire list for values of n that are easy to factor). As far as I know, I'm the inventor of this algorithm. *) (* We'll contain a list of [prime_rec]'s that replace the simple list of primes that are used in simple algorithms. [prime] This is the prime, as before. [count] Given [n], [count] = [n] % [prime]. [updated] One way to keep [count] up to date is to update it for each new [n]. However, this would traversing the entire list of [prime_rec]'s for each new value of [n]. Hence, we'll only update [count] each time that [prime] is considered as a possible factor of [n]. When we do update [count], we'll set [updated] to [n]. E.g., if [count] has not been updated since [n1] and [n] is now [n2], then [updated] will be [n1]. If [prime] is now considered as a factor of [n2], then we'll set [updated] to [n2] and [count] to [count] + [n2] - [n1] % [prime]. If [count] is now 0, [prime] is indeed a factor of [n2]. *) type prime_rec = { prime : int; mutable count: int; mutable updated: int } (* Output usage information to the user. If [mesg] is provided, it will be output first as an error message. *) let usage ?(mesg = "") () = if not (mesg = "") then Printf.fprintf stderr "Error: %s\n" mesg; Printf.fprintf stderr "Usage: %s NUMBER_OF_PRIMES\n" Sys.argv.(0); prerr_string "Print out the first NUMBER_OF_PRIMES primes.\n"; if mesg = "" then exit 0 else exit 1 (* Output a prime number in a nice manner. *) let print_prime p = Printf.printf "%d\n" p (* Find [numerator] % [divisor] quickly by assuming that [numerator] will usually be less than [opt_tries] * [divisor]. Just leave [opt_tries] to its default value unless you plan on doing some tuning. *) let rec fast_mod ?(opt_tries = 2) numerator divisor = match opt_tries with 0 -> numerator mod divisor | _ -> begin if numerator < divisor then numerator else fast_mod ~opt_tries:(opt_tries - 1) (numerator - divisor) divisor end (* Loop over the [prime_rec_list] and look for a factor of [num_curr]. Do updates to the [prime_rec]'s as described in the definition of [prime_rec]. If we find a factor, immediately return false. Otherwise, continue until we prove that no prime in [prime_rec_list] is a factor of [num_curr], at which time we can return true. *) let rec is_prime num_curr prime_rec_list = match prime_rec_list with [] -> true | head :: tail -> begin let overflowed = head.count + num_curr - head.updated in head.count <- (fast_mod overflowed head.prime); head.updated <- num_curr; if head.count = 0 then false else is_prime num_curr tail end (* Print out the first [num_primes] primes. [num_primes] must be positive. Leave everything else to its default value. *) let rec find_primes ?(num_curr = 2) ?(prime_rec_list = []) num_primes = match num_primes with 0 -> () | _ -> begin if is_prime num_curr prime_rec_list then begin print_prime num_curr; let to_append = { prime = num_curr; count = 0; updated = num_curr } in find_primes ~num_curr:(num_curr + 1) (* Smallest numbers first for performance. *) ~prime_rec_list:(List.append prime_rec_list [to_append]) (num_primes - 1) end else find_primes ~num_curr:(num_curr + 1) ~prime_rec_list:prime_rec_list num_primes end let main () = try if (Array.length Sys.argv) != 2 then usage ~mesg:"missing NUMBER_OF_PRIMES" (); let num_primes = int_of_string Sys.argv.(1) in if num_primes < 1 then usage ~mesg:"NUMBER_OF_PRIMES must be positive" (); find_primes num_primes; exit 0 with Failure why -> usage ~mesg:"NUMBER_OF_PRIMES must be an integer" ();; main () From aneumann at inf.fu-berlin.de Mon Aug 6 09:07:55 2007 From: aneumann at inf.fu-berlin.de (Adrian Neumann) Date: Mon Aug 6 09:00:29 2007 Subject: [Haskell-cafe] Sudoku Solver Message-ID: <46B71D2B.8080504@inf.fu-berlin.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: RIPEMD160 Hi, I wrote a brute-force sudoku solver. It takes a [[Int]] and spits out the first solution it finds. Why is it, that [0,0,0,7,0,6,9,0,0] [9,0,0,0,0,4,7,0,0] [7,0,0,0,0,0,4,0,0] [0,2,7,0,3,5,8,0,0] [6,9,5,8,2,0,0,0,0] [0,8,0,0,0,0,5,0,0] [0,3,0,0,0,0,0,0,0] [8,7,0,9,0,0,0,0,0] [0,0,0,0,0,0,0,0,0] is solved instantly, but when I remove just one number my program takes forever? === import Array import List import System type Field = Array Int (Array Int Int) isEmpty :: Int -> Bool isEmpty = (==) 0 done :: Field -> Bool done a = isFull a && checkField a isFull::Field -> Bool isFull a = notElem (0) $ (concat.(map elems).elems) a readField :: [[Int]]->Field readField = (listArray (1,9).map (listArray (1,9))) checkField :: Field -> Bool checkField a = check (rows a) && check (columns a) && check (squares a) where check b = and $ ((map ((==1).length)).concat.(map group).clean) b clean = map (dropWhile isEmpty.sort) columns::Field -> [[Int]] columns a = [[a!i!j|i<-[1..9]]|j<-[1..9]] rows :: Field -> [[Int]] rows a = [[a!i!j|j<-[1..9]]|i<-[1..9]] squares :: Field -> [[Int]] squares a = [[a!(i+n)!(j+m)|i<-[1..3],j<-[1..3]] |n<-[0,3,6],m<-[0,3,6]] - -- creates a list of all allowed entries genMoves :: Field -> [Field] genMoves a = concat [update a i j|i<-[1..9],j<-[1..9],isEmpty (a!i!j)] where update b i j= [b //[(i,b!i //[(j,x)])]|x<-[1..9], checkField (b //[(i,b!i //[(j,x)])])] play :: [Field] -> Maybe Field play (f:a) | done f= Just f | isFull f= play a | otherwise = play ((genMoves f)++a) play [] = Nothing main :: IO () main = do x <- getArgs let field = read (x!!0) :: [[Int]] let erg=play [readField field] case erg of Just a -> putStrLn $ concat $ map ((++"\n").show) (rows a) Nothing -> putStrLn "Es gibt keine Loesung" -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGtx0r11V8mqIQMRsRA7P5AJ9lG3mF3fHpUiyOqCeRVOOEGozp1wCeI80C RfD/U5y+yEgF0fe+kRwDbUI= =Ngss -----END PGP SIGNATURE----- From apfelmus at quantentunnel.de Mon Aug 6 11:43:08 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Mon Aug 6 11:35:23 2007 Subject: [Haskell-cafe] Re: Zippers, Random Numbers & Terrain In-Reply-To: <784a62100708011620n40394375m5ffe46acb2da0ca1@mail.gmail.com> References: <784a62100707292326u2b8fb37bl5fccb9b0c86ecf4c@mail.gmail.com> <784a62100708011620n40394375m5ffe46acb2da0ca1@mail.gmail.com> Message-ID: Thomas Conway wrote: > On 8/2/07, apfelmus wrote: >> That concludes the infinite terrain generation for one dimension. For >> higher dimension, one just needs to use 2D objects instead of intervals >> to split into two or more pieces. For instance, one can divide >> equilateral triangles into 4 smaller ones. In fact, it doesn't matter >> whether the starting triangle is equilateral or not when using the >> midpoints of the three sides to split it into four smaller triangles. > > Nice. The issue of the RNG running backwards was what made me realize > that rather than using StdGen in the nodes, if you simply number them > (Hmmm - the nodes are countably infinite :-)), you can then [e.g.] use > a cryptographic hash or similar to turn them into random numbers. You > can seed the hash to generate different terrains. Yes. The number of a node in the tree should be (related to) the path from the top to the tree in binary representation. I.e. if node = zoomInLeft . zoomInLeft . zoomInRight $ top then, number node = 112 in binary with digits 1 and 2 In contrast, breadth first numbering is a bad idea, since that would mean numbering lots of nodes that aren't required when zooming in. It's probably easiest to first create an infinite tree filled with random numbers type Tree a = Branch (Tree a) a (Tree a) type Random = Double mkRandom :: Seed -> Tree Random and then convert that to a landscape afterwards terrain :: Tree Random -> Tree (Height, Height) Yet another option is available if you only use the zipper-operations to navigate in the tree, i.e. data TreeRandom -- abstract and a zipper zoomInLeft, zoomInRight, zoomOut :: TreeRandom -> TreeRandom top :: TreeRandom -> Random In that case, you can represent it by type TreeRandom = (StdGen, Zipper (Maybe Random)) Everytime you visit a node that has not been visited yet (=> Nothing), it gets a new random number from the generator. When it's already been visited (=> Just r), well then the random number associated to it won't change. The resulting zipper may only be used in a single-threaded fashion, however. > You may be interested that in some of the code I wrote for the right > angle isosceles triangle case, I got into precision problems. It turns > out that all the vertices lie on positions with coordinates that are > precisely sums of 2^-k (e.g. 0.5, 0.125, 0.625), yet each time you > subdivide, the scaling factor on the side length is sqrt 2/2. The > resultant rounding meant that instead of getting 0.5, I got > 0.5000000003, or some such. > > After pondering on this for a while, I realized instead of > representing the scale of the triangle as a Double, I could use > (Either Double Double), with Left x representing the scale x, and > Right x representing the scale x * sqrt 2 / 2. That way, all the > rounding problems can be made to go away. Cool :) Of course, the representation with Either requires the knowledge that a scale factor cannot contain both Double-multiples of 1 and Double-multiples of sqrt 2 at the same time. While this is clearly the case, you can avoid thinking about it by operating in the field Q[sqrt 2]: data QSqrt2 = !Double :+ !Double deriving (Eq,Read,Show) instance Nume QSqrt2 where (a :+ b) + (c :+ d) = (a+c) :+ (b+d) (a :+ b) * (c :+ d) = (a*c + 2*b*d) :+ (a*d + b*c) negate (a :+ b) = negate a :+ negate b abs (a :+ b) = (a + sqrt 2 * b) :+ 0 fromInteger n = fromInteger n :+ 0 sqrt2 = 0 :+ 1 Regards, apfelmus From icfp.publicity at googlemail.com Mon Aug 6 11:54:21 2007 From: icfp.publicity at googlemail.com (Matthew Fluet (ICFP Publicity Chair)) Date: Mon Aug 6 11:46:28 2007 Subject: [Haskell-cafe] ICFP07 Call for Participation Message-ID: <53ff55480708060854h603dfb10n8494a7ce608be2da@mail.gmail.com> ===================================================================== Call for Participation The 12th ACM SIGPLAN International Conference on Functional Programming (ICFP 2007) http://www.informatik.uni-bonn.de/~ralf/icfp07.html Freiburg, Germany, 1-3 October 2007 ===================================================================== ICFP 2007 provides a forum for researchers and developers to hear about the latest work on the design, implementations, principles, and uses of functional programming. The conference covers the entire spectrum of work, from practice to theory, including its peripheries. Preliminary program: * http://www.informatik.uni-bonn.de/~ralf/schedule.html * Invited speakers: + John Hughes (Chalmers University of Technology) + Frank Pfenning (Carnegie Mellon University) + John Lloyd (Australian National University) * The Program committee has *deliberately* created extra breaks so as to give participants more time to talk with colleagues. Schedule including related workshops: * 30 Sep: ACM SIGPLAN Haskell Workshop * 30 Sep: ACM SIGPLAN Workshop on Scheme and Functional Programming * 1-3 Oct: ICFP07 * 4 Oct: ACM SIGPLAN Commercial Users of Functional Programming * 4 Oct: ACM SIGPLAN Workshop on Mechanizing Metatheory * 5 Oct: ACM SIGPLAN Erlang Workshop * 5 Oct: ACM SIGPLAN Workshop on ML * 5 Oct: ACM SIGPLAN Programming Languages meets Program Verification Registration information: * http://proglang.informatik.uni-freiburg.de/ICFP2007/registration.shtml * Early registration deadline: September 7, 2007 Accommodations information: * http://proglang.informatik.uni-freiburg.de/ICFP2007/accommodation.shtml * Conference reservation/rate deadline: September 1, 2007 * September/October is Freiburg's main tourist season; participants are advised to book rooms as early as possible. Conference organizers: * General Chair: Ralf Hinze (Universit?t Bonn) * Program Chair: Norman Ramsey (Harvard University) * Local Arrangements Chair: Peter Thiemann (Universit?t Freiburg) * Workshop Co-Chairs: Graham Hutton (University of Nottingham) and Matthias Blume (Toyota Technological Institute at Chicago) * Programming Contest Chair: Johan Jeuring (Universiteit Utrecht) * Publicity Chair: Matthew Fluet (Toyota Technological Institute at Chicago) From bf3 at telenet.be Mon Aug 6 12:36:22 2007 From: bf3 at telenet.be (peterv) Date: Mon Aug 6 12:28:32 2007 Subject: [Haskell-cafe] Newbie question: "multi-methods" in Haskell Message-ID: <008801c7d847$ecdd6b40$c69841c0$@be> In de book Modern C++ design, Andrei Alexandrescu writes that Haskell supports =93multi-methods=94 http://books.google.com/books?id=3DaJ1av7UFBPwC&pg=3DPA3&ots=3DYPiJ_nWi6Y= &dq=3Dmoder n+C%2B%2B&sig=3DFWO6SVfIrgtCWifj9yYHj3bnplQ#PPA263,M1 How is this actually done in Haskell? Maybe this is just a basic feature = of Haskell which I don't grasp yet because of my object-oriented = background? A good example is collision between pairs of objects of type (a,b). In object oriented languages this cannot be handled in a nice way, because neither a.Collide(b) or b.Collide(a) is the correct approach; one would = like to write (a,b).Collide() A specific example might be better here.=20 Assume the following class hierarchy: Solid | +-- Asteroid | +-- Planet | + -- Earth | + -- Jupiter Using multi-methods, I could write (in pseudo code) collide (Asteroid, Planet) =3D "an asteroid hit a planet" collide (Asteroid, Earth) =3D "the end of the dinos" collide (Solid,Solid) =3D " solids collided" collide (Planet, Asteroid) =3D collide (Asteroid, Planet) collide (Earth, Asteroid) =3D collide (Earth, Asteroid) So basically, the "best" collide function is picked, depending on the = type of the arguments. How should I write Haskell code for something like this in general, in = the sense that this hierarchy is typically huge and the matrix (of collide functions for each pair of types) is very sparse. Thanks, Peter No virus found in this outgoing message. Checked by AVG Free Edition.=20 Version: 7.5.476 / Virus Database: 269.11.6/938 - Release Date: = 05/08/2007 16:16 =20 From paul.hudak at yale.edu Mon Aug 6 13:05:17 2007 From: paul.hudak at yale.edu (Paul Hudak) Date: Mon Aug 6 12:57:20 2007 Subject: [Haskell-cafe] [Fwd: PADL 2008: Call for Papers] Message-ID: <46B754CD.3080005@yale.edu> -------- Original Message -------- Subject: PADL 2008: Call for Papers Date: Sat, 4 Aug 2007 19:25:58 -0500 (CDT) From: Gopal Gupta [ Colleagues, note that this will be the 10th PADL; We strongly urge you to submit papers, the deadline is only 3 weeks way] CALL FOR PAPERS!!! Tenth International Symposium on Practical Aspects of Declarative Languages 2008 (PADL '08) http://www.ist.unomaha.edu/padl2008/ San Francisco, USA January 7-8, 2008 Co-located with ACM POPL'08 Declarative languages build on sound theoretical bases to provide attractive frameworks for application development. These languages have been successfully applied to vastly different real-world situations, ranging from data base management to active networks to software engineering to decision support systems. New developments in theory and implementation have opened up new application areas. At the same time, applications of declarative languages to novel problems raises numerous interesting research issues. Well-known questions include designing for scalability, language extensions for application deployment, and programming environments. Thus, applications drive the progress in the theory and implementation of declarative systems, and benefit from this progress as well. PADL is a forum for researchers and practitioners to present original work emphasizing novel applications and implementation techniques for all forms of declarative concepts, including, functional, logic, constraints, etc. Topics of interest include: * innovative applications of declarative languages; * declarative domain-specific languages and applications; * practical applications of theoretical results; * new language developments & their impact on applications; * evaluation of implementation techniques on practical applications; * novel uses of declarative languages in the classroom; and * practical experiences PADL 08 welcomes new ideas and approaches pertaining to applications and implementation of declarative languages. PADL 08 will be co-located with the ACM POPL. IMPORTANT DATES AND SUBMISSION GUIDELINES Paper Submission: August 24, 2007 Notification: September 27, 2007 Camera-ready: October 23, 2007 Symposium: January 7-8, 2008 Authors should submit an electronic copy of the full paper (written in English) in Postscript (Level 2) or PDF. Papers must be no longer than 15 pages, written in 11-point font and with single spacing. Since the final proceedings will be published as Lecture Notes in Computer Science by Springer Verlag, authors are strongly encouraged to use the LNCS paper formatting guidelines for their submission. Each submission must include on its first page the paper title; authors and their affiliations; contact author's email and postal addresses, telephone and fax numbers, abstract, and three to four keywords. The keywords will be used to assist us in selecting appropriate reviewers for the paper. If electronic submission is impossible, please contact the program chair for information on how to submit hard copies. MOST PRACTICAL PAPER AWARD The Most Practical Paper award will be given to the submission that is judged by the program committee to be the best in terms of practicality, originality, and clarity of presentation. The program committee may choose not to make an award, or to make multiple awards. Contacts: For information about papers and submissions, please contact the Program Chair: Paul Hudak PC co-Chair - PADL 2008 Department of Computer Science Yale University P.O. Box 208285 New Haven, CT 06520 - 8285 Email: hudak@cs.yale.edu David S. Warren PC co-Chair - PADL 2008 Department of Computer Science Stony Brook University Stony Brook, NY Email: warren@cs.sunysb.edu For other information about the conference, please contact: Hai-Feng Guo General Chair - PADL 2008 Department of Computer Science College of Information Science & Technology University of Nebraska at Omaha Omaha, NE, U.S.A. Email: haifengguo@mail.unomaha.edu Sponsored by: COMPULOG Americas (http://www.cs.nmsu.edu/~complog) and University of Nebraska at Omaha -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070806/440e5ae6/attachment.htm From brianh at metamilk.com Mon Aug 6 13:19:12 2007 From: brianh at metamilk.com (Brian Hulley) Date: Mon Aug 6 13:11:08 2007 Subject: [Haskell-cafe] Newbie question: "multi-methods" in Haskell In-Reply-To: <008801c7d847$ecdd6b40$c69841c0$@be> References: <008801c7d847$ecdd6b40$c69841c0$@be> Message-ID: <46B75810.9070509@metamilk.com> peterv wrote: > In de book Modern C++ design, Andrei Alexandrescu writes that Haskell > supports “multi-methods” > Using multi-methods, I could write (in pseudo code) > collide (Asteroid, Planet) = "an asteroid hit a planet" > collide (Asteroid, Earth) = "the end of the dinos" > ... > collide (Planet, Asteroid) = collide (Asteroid, Planet) > collide (Earth, Asteroid) = collide (Earth, Asteroid) Hi, In Haskell you can use multi parameter type classes to solve this problem: {-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances #-} module Collide where class Collide a b where collide :: (a,b) -> String data Solid = Solid data Asteroid = Asteroid data Planet = Planet data Jupiter = Jupiter data Earth = Earth instance Collide Asteroid Planet where collide (Asteroid, Planet) = "an asteroid hit a planet" instance Collide Asteroid Earth where collide (Asteroid, Earth) = "the end of the dinos" -- Needs overlapping and undecidable instances instance Collide a b => Collide b a where collide (a,b) = collide (b, a) -- ghci output *Collide> collide (Asteroid, Earth) "the end of the dinos" *Collide> collide (Earth, Asteroid) "the end of the dinos" Best regards, Brian. From westondan at imageworks.com Mon Aug 6 14:37:17 2007 From: westondan at imageworks.com (Dan Weston) Date: Mon Aug 6 14:32:15 2007 Subject: [Haskell-cafe] Newbie question: "multi-methods" in Haskell In-Reply-To: <46B75810.9070509@metamilk.com> References: <008801c7d847$ecdd6b40$c69841c0$@be> <46B75810.9070509@metamilk.com> Message-ID: <46B76A5D.5070607@imageworks.com> Remember that type classes do not provide object-oriented functionality.=20 The dispatch is static, not dynamic. Although OOP can be simulated in=20 Haskell, it is not a natural idiom. If you need dynamic dispatch=20 (including multiple dispatch), you may want to reconsider your solution. Dan Weston Brian Hulley wrote: > peterv wrote: >> In de book Modern C++ design, Andrei Alexandrescu writes that Haskell >> supports =93multi-methods=94 >=20 >> Using multi-methods, I could write (in pseudo code) >> collide (Asteroid, Planet) =3D "an asteroid hit a planet" >> collide (Asteroid, Earth) =3D "the end of the dinos" >> ... >> collide (Planet, Asteroid) =3D collide (Asteroid, Planet) >> collide (Earth, Asteroid) =3D collide (Earth, Asteroid) >=20 > Hi, In Haskell you can use multi parameter type classes to solve this=20 > problem: >=20 > {-# OPTIONS_GHC -fglasgow-exts > -fallow-undecidable-instances > -fallow-overlapping-instances #-} >=20 > module Collide where >=20 > class Collide a b where > collide :: (a,b) -> String >=20 > data Solid =3D Solid > data Asteroid =3D Asteroid > data Planet =3D Planet > data Jupiter =3D Jupiter > data Earth =3D Earth >=20 > instance Collide Asteroid Planet where > collide (Asteroid, Planet) =3D "an asteroid hit a planet" >=20 > instance Collide Asteroid Earth where > collide (Asteroid, Earth) =3D "the end of the dinos" >=20 > -- Needs overlapping and undecidable instances > instance Collide a b =3D> Collide b a where > collide (a,b) =3D collide (b, a) >=20 > -- ghci output > *Collide> collide (Asteroid, Earth) > "the end of the dinos" > *Collide> collide (Earth, Asteroid) > "the end of the dinos" >=20 > Best regards, Brian. > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe >=20 >=20 From rendel at rbg.informatik.tu-darmstadt.de Mon Aug 6 14:58:56 2007 From: rendel at rbg.informatik.tu-darmstadt.de (Tillmann Rendel) Date: Mon Aug 6 14:50:27 2007 Subject: [Haskell-cafe] Newbie question: "multi-methods" in Haskell In-Reply-To: <008801c7d847$ecdd6b40$c69841c0$@be> References: <008801c7d847$ecdd6b40$c69841c0$@be> Message-ID: <46B76F70.2010306@rbg.informatik.tu-darmstadt.de> peterv schrieb: > In de book Modern C++ design, Andrei Alexandrescu writes that Haskell > supports “multi-methods” > > http://books.google.com/books?id=aJ1av7UFBPwC&pg=PA3&ots=YPiJ_nWi6Y&dq=moder > n+C%2B%2B&sig=FWO6SVfIrgtCWifj9yYHj3bnplQ#PPA263,M1 Chapter 11, Page 263 of this books: > The C++ virtual function mechanism allows dispatching of a call > depending on the dynamic type of one object. The multimethods feature > allows dispatching of a function call depending on the types of > multiple objects. A universally good implementation requires language > support, wich is the route that languages such as CLOS, ML, Haskell, > and Dylan have taken. C++ lacks such support, so it's emulation is > left to library writers. I do not see why the author of this book included Haskell in this list. (But from what I know, CLOS is more like a combinator library then like a language, so I don't understand the point of this list at all). Since Haskell has no language support for subtype polymorphism or dynamic dispatch of method calls, there are no dynamic multimethods either. But with multi-parameter typeclasses, we have statically dispatched multimethods, of course. (See Brian's answer). But the author speaks specifically about dynamic dispatch. Sometimes, class hierarchies from an OO design are naturally represented by algebraic data types. Then OO methods become ordinary haskell function, and dynamic dispatch becomes pattern matching, wich is of course possible on all argument positions: data Solid = Asteroid | Planet Planet data Planet = Earth | Jupiter collide :: Solid -> Solid -> String collide Asteroid (Planet Earth) = "the end of the dinos" collide Asteroid (Planet _) = "an asteroid hit a planet" collide p@(Planet _) Asteroid = collide Asteroid p collide _ _ = "solids collided" But you have to sort the definitons for collide yourself, because there is no "selection of the most specific" automatically. While this is a sometimes sensible translation of an OO design into an FP design, it is not the same thing as having objects and subtypes and dynamic dispatch. Tillmann From brianh at metamilk.com Mon Aug 6 15:14:39 2007 From: brianh at metamilk.com (Brian Hulley) Date: Mon Aug 6 15:06:46 2007 Subject: [Haskell-cafe] Newbie question: "multi-methods" in Haskell In-Reply-To: <46B76A5D.5070607@imageworks.com> References: <008801c7d847$ecdd6b40$c69841c0$@be> <46B75810.9070509@metamilk.com> <46B76A5D.5070607@imageworks.com> Message-ID: <46B7731F.3040100@metamilk.com> Dan Weston wrote: > Remember that type classes do not provide object-oriented > functionality. The dispatch is static, not dynamic. Although OOP can > be simulated in Haskell, it is not a natural idiom. If you need > dynamic dispatch (including multiple dispatch), you may want to > reconsider your solution. Dynamic dispatch is easily added to Haskell code by using an existential to represent any collision: {-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances #-} module Collide where -- Changed to a single param to make life easier... class Collide a where collide :: a -> String data Solid = Solid data Asteroid = Asteroid data Planet = Planet data Jupiter = Jupiter data Earth = Earth instance Collide (Asteroid, Planet) where collide (Asteroid, Planet) = "an asteroid hit a planet" instance Collide (Asteroid, Earth) where collide (Asteroid, Earth) = "the end of the dinos" -- Needs overlapping and undecidable instances instance Collide (a, b) => Collide (b, a) where collide (a,b) = collide (b, a) -- This is how you get dynamic dispatch in Haskell data Collision = forall a. Collide a => Collision a instance Collide Collision where collide (Collision a) = collide a -- ghci output *Collide> let ae = Collision (Asteroid, Earth) *Collide> let pa = Collision (Planet, Asteroid) *Collide> collide ae "the end of the dinos" *Collide> collide pa "an asteroid hit a planet" *Collide> map collide [ae, pa] ["the end of the dinos","an asteroid hit a planet"] Best regards, Brian. From monnier at iro.umontreal.ca Mon Aug 6 15:57:57 2007 From: monnier at iro.umontreal.ca (Stefan Monnier) Date: Mon Aug 6 15:50:17 2007 Subject: [Haskell-cafe] Re: Newbie question: "multi-methods" in Haskell References: <008801c7d847$ecdd6b40$c69841c0$@be> <46B75810.9070509@metamilk.com> <46B76A5D.5070607@imageworks.com> Message-ID: > Remember that type classes do not provide object-oriented functionality. > The dispatch is static, not dynamic. I beg to disagree. map (\n. n + n) calls different (+) operations depending on the (type of the) argument list. That's why dictionaries are passed around (they are called vtables in many OO languages) by several Haskell implementations. Stefan From pocm at soton.ac.uk Mon Aug 6 16:11:10 2007 From: pocm at soton.ac.uk (Paulo J. Matos) Date: Mon Aug 6 16:03:13 2007 Subject: [Haskell-cafe] Using haskell with emacs Message-ID: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> Hi all, I'm starting to learn haskell by my own, being currently mostly a Common Lisp, Scheme, C++ programmer... I've got the haskell emacs mode but can't find a manual. Moreover, I've found some keybindings on the net but nothing that allows me to start an interpreter in emacs and send definitions, one by one to the interpreter. Is this possible? Is there any good reference of the emacs keybindings for haskell mode? Cheers, -- Paulo Jorge Matos - pocm at soton.ac.uk http://www.personal.soton.ac.uk/pocm PhD Student @ ECS University of Southampton, UK From coeus at gmx.de Mon Aug 6 16:18:14 2007 From: coeus at gmx.de (Marc A. Ziegert) Date: Mon Aug 6 16:10:30 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> Message-ID: <200708062218.21965.coeus@gmx.de> Am Montag, 6. August 2007 00:48 schrieb Frank Buss: > I've created a small program to compose images with combinators: > > http://www.frank-buss.de/haskell/OlympicRings.hs.txt > ... > look very smooth. And it is very slow, it needs about 40 seconds on my >computer to calculate the image. Using parametrized combinators sounds like ... in that source file, you define Size and Pixel as structs of "Integer"s. that are neither unsigned chars (8_bit) nor ints (32-64_bit) nor floats (32_bit) but an artificial oo_bit int (1 int + list of bytes). i'm sure you will gain a speedup by redefining these structs. i.e. use Float or Int instead of Integer; see Data.Int and Data.Word for more alternatives. - marc > [code snippet from source file] -- image size data Size = Size { width :: Integer, height :: Integer } deriving (Eq, Ord, Show, Read) -- RGB components for an image pixel data Pixel = Pixel { r :: Integer, g :: Integer, b :: Integer } deriving (Eq, Ord, Show, Read) -- helper functions for saving bytes writeByte byte = putWord8 (fromIntegral byte) writeBytes bytes = mapM_ putWord8 bytes -- binary instance for saving Pixels instance Binary Pixel where put (Pixel r g b) = do writeByte b writeByte g writeByte r get = error "Pixel get not supported" [/code] -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070806/ded4d385/attachment.bin From nominolo at googlemail.com Mon Aug 6 16:40:50 2007 From: nominolo at googlemail.com (Thomas Schilling) Date: Mon Aug 6 16:32:58 2007 Subject: [Haskell-cafe] Using haskell with emacs In-Reply-To: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> References: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> Message-ID: On 6 aug 2007, at 22.11, Paulo J. Matos wrote: > Hi all, > > I'm starting to learn haskell by my own, being currently mostly a > Common Lisp, Scheme, C++ programmer... I've got the haskell emacs mode > but can't find a manual. Moreover, I've found some keybindings on the > net but nothing that allows me to start an interpreter in emacs and > send definitions, one by one to the interpreter. Is this possible? Is > there any good reference of the emacs keybindings for haskell mode? If you're used to Slime+Paredit, then there isn't something really comparable, but you get some basic interactive programming with the standard key-bindings: C-c C-b ... when pressed for the first time this will start an interpreter (ghci or hugs most of the time), when pressed with a running interpreter it'll switch to that buffer. C-c C-l ... Load the current file into the editor. There is no function-wise compilation. With the latest Haskell mode, you get clickable error messages, too. Then there is shim[1], which is a start of a Slime-like emacs mode, it can: - compile and show compile errors directly in the source (C-c C-k) - insert the type of a function (C-c C-t) The big problem with shim is, that it is only really useful as long as your code compiles. To have anything more useful you need to have good (incremental) parsing facilities, which Emacs isn't particularly good at. Every once in a while I do some hacking towards this goal, but it's rather low-priority (and I'm no particular Emacs guru either, though with (require 'cl) it get's somewhat more fun.) Many Haskell hackers also prefer Vim, so that doesn't help, either ;) Oh, and there's hoogle.el, which is pretty similar to Hyperspec lookup (actually, I think it's better; more like Lisp-doc lookup). Regards, / Thomas [1] .. http://shim.haskellco.de/trac/shim From bf3 at telenet.be Mon Aug 6 16:44:55 2007 From: bf3 at telenet.be (peterv) Date: Mon Aug 6 16:36:57 2007 Subject: [Haskell-cafe] Newbie question: "multi-methods" in Haskell References: <008801c7d847$ecdd6b40$c69841c0$@be> <46B75810.9070509@metamilk.com> <46B76A5D.5070607@imageworks.com> <46B7731F.3040100@metamilk.com> Message-ID: <000101c7d86a$a54da290$efe8e7b0$@be> This is very nice, but it does not really solve the original problem. In your code, evaluating collide (Jupiter, Asteroid) will result in an endless loop. This is expected in your code, because no "inheritance" relation is present between e.g Jupiter and Planet. With multi-dispatch, it should pick the "best" matching collide function based on inheritance, or raise an error when ambiguous types. I could fix that be just keeping the "leafs" (Earth, Jupiter, Asteroid) as datatypes, and adding type classes for the "super classes" (Planet, Solid), like the code below, but I could not check Asteroid-Asteroid collision with that, GHCi gives an error. {-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances #-} module Collide where class Collide a where collide :: a -> String data Asteroid = Asteroid data Jupiter = Jupiter data Earth = Earth class IsSolid a class IsSolid a => IsPlanet a instance IsSolid Asteroid instance IsSolid Jupiter instance IsSolid Earth instance IsPlanet Earth instance IsPlanet Jupiter instance (IsSolid a, IsSolid b) => Collide (a, b) where collide (x,y) = "generic collision" instance (IsPlanet a) => Collide (Asteroid, a) where collide (x,y) = "an asteroid hit a planet" instance (IsPlanet a) => Collide (a, Asteroid) where collide (x, y) = "an asteroid hit a planet" instance Collide (Asteroid, Earth) where collide (_,_) = "the end of the dinos" instance Collide (Earth, Asteroid) where collide (_,_) = "the end of the dinos" -- This is how you get dynamic dispatch in Haskell data Collision = forall a. Collide a => Collision a instance Collide Collision where collide (Collision a) = collide a ae = collide (Asteroid, Earth) ea = collide (Earth, Asteroid) ja = collide (Jupiter, Asteroid) aj = collide (Asteroid, Jupiter) -- However, this one gives an error? --aa = collide (Asteroid, Asteroid) -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Brian Hulley Sent: Monday, August 06, 2007 9:15 PM To: haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] Newbie question: "multi-methods" in Haskell Dan Weston wrote: > Remember that type classes do not provide object-oriented > functionality. The dispatch is static, not dynamic. Although OOP can > be simulated in Haskell, it is not a natural idiom. If you need > dynamic dispatch (including multiple dispatch), you may want to > reconsider your solution. Dynamic dispatch is easily added to Haskell code by using an existential to represent any collision: {-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances #-} module Collide where -- Changed to a single param to make life easier... class Collide a where collide :: a -> String data Solid = Solid data Asteroid = Asteroid data Planet = Planet data Jupiter = Jupiter data Earth = Earth instance Collide (Asteroid, Planet) where collide (Asteroid, Planet) = "an asteroid hit a planet" instance Collide (Asteroid, Earth) where collide (Asteroid, Earth) = "the end of the dinos" -- Needs overlapping and undecidable instances instance Collide (a, b) => Collide (b, a) where collide (a,b) = collide (b, a) -- This is how you get dynamic dispatch in Haskell data Collision = forall a. Collide a => Collision a instance Collide Collision where collide (Collision a) = collide a -- ghci output *Collide> let ae = Collision (Asteroid, Earth) *Collide> let pa = Collision (Planet, Asteroid) *Collide> collide ae "the end of the dinos" *Collide> collide pa "an asteroid hit a planet" *Collide> map collide [ae, pa] ["the end of the dinos","an asteroid hit a planet"] Best regards, Brian. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From wagner.andrew at gmail.com Mon Aug 6 16:59:01 2007 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Mon Aug 6 16:51:06 2007 Subject: [Haskell-cafe] Using haskell with emacs In-Reply-To: References: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> Message-ID: > C-c C-b ... when pressed for the first time this will start an > interpreter (ghci or hugs most of the time), when pressed with a > running interpreter it'll switch to that buffer. > > C-c C-l ... Load the current file into the editor. There is no > function-wise compilation. > Don't forget C-c C-r to reload the file in the buffer. To the OP: Here's the page I used when I set up emacs for haskell the other week: http://haskell.org/haskellwiki/Haskell_mode_for_Emacs From jules at jellybean.co.uk Mon Aug 6 17:28:04 2007 From: jules at jellybean.co.uk (Jules Bean) Date: Mon Aug 6 17:20:10 2007 Subject: [Haskell-cafe] Using haskell with emacs In-Reply-To: References: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> Message-ID: <46B79264.6050801@jellybean.co.uk> Thomas Schilling wrote: > > On 6 aug 2007, at 22.11, Paulo J. Matos wrote: > If you're used to Slime+Paredit, then there isn't something really > comparable, but you get some basic interactive programming with the > standard key-bindings: (But paredit does work in haskell-mode, and I find it useful...) Jules From bauertim at eecs.orst.edu Mon Aug 6 18:21:09 2007 From: bauertim at eecs.orst.edu (tim.b) Date: Mon Aug 6 18:13:12 2007 Subject: [Haskell-cafe] Java 1.5 parser in Haskell Message-ID: <12025365.post@talk.nabble.com> Does anyone know of a fairly complete Java 1.5 parser and abstract syntax in Haskell? I've looked around quite a bit to no avail. Thanks, - Tim -- View this message in context: http://www.nabble.com/Java-1.5-parser-in-Haskell-tf4227017.html#a12025365 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From hughperkins at gmail.com Mon Aug 6 19:19:01 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Mon Aug 6 19:11:06 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <46B71D2B.8080504@inf.fu-berlin.de> References: <46B71D2B.8080504@inf.fu-berlin.de> Message-ID: <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> Note that the "official" way to solve sudoku is to use "dancing links", but I guess you are creating a naive implementation precisely as a base-line against which to measure other implementations? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070807/630935e7/attachment.htm From rk at trie.org Mon Aug 6 19:23:43 2007 From: rk at trie.org (Rahul Kapoor) Date: Mon Aug 6 19:15:46 2007 Subject: [Haskell-cafe] Type without a data constructor? Message-ID: Most examples for defining algebraic types include data constructors like so: data Tree a = Tip | Node a (Tree a) (Tree a) I by mistake defined a type which did not specify a data constructor : data SearchCondition = Term Bool | SearchCondition :||: (Term Bool) data Term a = Constant a sc :: SearchCondition sc = Term True is ok, but sc :: SearchCondition sc = Constant True is not (though this is what I intended to capture!). So the question is what are types with no constructors good for? A simple example would be appreciated. Rahul From ndmitchell at gmail.com Mon Aug 6 19:32:27 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Mon Aug 6 19:24:31 2007 Subject: [Haskell-cafe] Type without a data constructor? In-Reply-To: References: Message-ID: <404396ef0708061632o19c279aeq4507a358ef05022c@mail.gmail.com> Hi > I by mistake defined a type which did not specify a data constructor > > So the question is what are types with no constructors good for? A > simple example would be appreciated. They are called phantom types, and can be used for ensuring properties at the type level. I wrote about them in a blog post: http://neilmitchell.blogspot.com/2007/04/phantom-types-for-real-problems.html There are probably better references, but that's the easiest for me to find ;-) Thanks Neil From westondan at imageworks.com Mon Aug 6 19:51:39 2007 From: westondan at imageworks.com (Dan Weston) Date: Mon Aug 6 19:43:43 2007 Subject: [Haskell-cafe] Type without a data constructor? In-Reply-To: References: Message-ID: <46B7B40B.2020109@imageworks.com> The answer would be phantom types, but your example doesn't use them. Each of your types has at least one constructor: Possibly you overlooked the infix constructor :||: ? Tree a has 2 constructors: Tip and Node SearchCondition has 2 constructors: Term and (:||:) Term a has 1 constructor : Constant *Prelude> :t Tip Tip :: Tree a *Prelude> :t Node Node :: a -> Tree a -> Tree a -> Tree a *Prelude> :t Term True Term True :: SearchCondition *Prelude> :t (:||:) (:||:) :: SearchCondition -> Term Bool -> SearchCondition *Prelude> :t Constant True Constant True :: Term Bool Dan Weston Rahul Kapoor wrote: > Most examples for defining algebraic types include data constructors like so: > > data Tree a = Tip | Node a (Tree a) (Tree a) > > I by mistake defined a type which did not specify a data constructor : > > data SearchCondition = Term Bool | SearchCondition :||: (Term Bool) > data Term a = Constant a > > sc :: SearchCondition > sc = Term True > > is ok, but > > sc :: SearchCondition > sc = Constant True > > is not (though this is what I intended to capture!). > > So the question is what are types with no constructors good for? A > simple example would be appreciated. > > Rahul > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From robdockins at fastmail.fm Mon Aug 6 18:54:18 2007 From: robdockins at fastmail.fm (Robert Dockins) Date: Mon Aug 6 19:44:06 2007 Subject: [Haskell-cafe] Type without a data constructor? In-Reply-To: References: Message-ID: <200708061854.18346.robdockins@fastmail.fm> On Monday 06 August 2007 19:23, Rahul Kapoor wrote: > Most examples for defining algebraic types include data constructors like > so: > > data Tree a = Tip | Node a (Tree a) (Tree a) > > I by mistake defined a type which did not specify a data constructor : In this example, you have two different uses of the lexical name 'Term', and I think it is confusing you. One kind of use is as a data constructor; the other is as a type constructor. I've annotated the uses below: > data SearchCondition > = Term Bool -- data constructor > | SearchCondition :||: (Term Bool) -- type constructor > data Term a = Constant a -- defn of type constr 'Term' > sc :: SearchCondition > sc = Term True -- data constructor > > is ok, but > > sc :: SearchCondition > sc = Constant True Now, here you have an expression of type 'Term Bool'. These can only appear on the right-hand side of :||: . This probably isn't what you want. Likely what you actually want is: > data SearchCondition > = SearchTerm (Term Bool) | SearchCondition :||: (Term Bool) Here, both uses of 'Term' refer to the type constructor. > is not (though this is what I intended to capture!). > > So the question is what are types with no constructors good for? A > simple example would be appreciated. There are some situations where an explicitly empty type is useful. Type-level programming voodoo is one. Other times the void type is nice because it can be used as a parameter to a type constructor. For example, if you use the nested datatype representation of de Bruijn lambda terms [1], you can use the void type to create the type of closed terms (terms with no free variables). Here's the short version: data Void data Succ a = Zero | Incr a data Term a = Var a | App (Term a) (Term a) | Lam (Term (Succ a)) type ClosedTerm = Term Void [1] Richard Bird and Ross Patterson, _de Brujin Notation as a Nested Datatype_, Journal of Functional Programming 9(1):77-91, January 1999. Rob Dockins From wnoise at ofb.net Mon Aug 6 19:52:34 2007 From: wnoise at ofb.net (Aaron Denney) Date: Mon Aug 6 19:44:44 2007 Subject: [Haskell-cafe] Re: Type without a data constructor? References: Message-ID: On 2007-08-06, Rahul Kapoor wrote: > I by mistake defined a type which did not specify a data constructor : No, you didn't. Both types have data constructors. > data SearchCondition = Term Bool | SearchCondition :||: (Term Bool) > data Term a = Constant a > > sc :: SearchCondition > sc = Term True > > is ok, but > > sc :: SearchCondition > sc = Constant True > > is not (though this is what I intended to capture!). The problem is that Constant True is of type Term Bool, rather than SearchCondition. Constructors and names of data types live in separate namespaces. > So the question is what are types with no constructors good for? A > simple example would be appreciated. See the phantom types answer that someone else gave. -- Aaron Denney -><- From rk at trie.org Mon Aug 6 20:00:49 2007 From: rk at trie.org (Rahul Kapoor) Date: Mon Aug 6 19:52:52 2007 Subject: [Haskell-cafe] Re: Type without a data constructor? In-Reply-To: References: Message-ID: >> Constructors and names of data types live in separate namespaces. The above fact was the cause of all my confusion. It just slipped out of my mind. Cheers, Rahul From daniel.is.fischer at web.de Mon Aug 6 20:38:00 2007 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Aug 6 20:55:33 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <46B71D2B.8080504@inf.fu-berlin.de> References: <46B71D2B.8080504@inf.fu-berlin.de> Message-ID: <200708070238.00912.daniel.is.fischer@web.de> Hi, Am Montag, 6. August 2007 15:07 schrieb Adrian Neumann: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: RIPEMD160 > > Hi, > > I wrote a brute-force sudoku solver. It takes a [[Int]] and spits out > the first solution it finds. > Why is it, that > > [0,0,0,7,0,6,9,0,0] > [9,0,0,0,0,4,7,0,0] > [7,0,0,0,0,0,4,0,0] > [0,2,7,0,3,5,8,0,0] > [6,9,5,8,2,0,0,0,0] > [0,8,0,0,0,0,5,0,0] > [0,3,0,0,0,0,0,0,0] > [8,7,0,9,0,0,0,0,0] > [0,0,0,0,0,0,0,0,0] > > is solved instantly, but when I remove just one number my program takes > forever? > Short answer: because of the enormous number of possibilities to check. You were just incredibly lucky: with the grid above, you needn't backtrack. The problem is genMoves, it produces too many Fields. Point 1: If for, say, the first empty cell, there are no possibilities, you still try out all possibilities for the other empty cells before you backtrack, that's bound to take very long. Point 2: Even if you take care of 1, you have to do it right. Say in one row you have three empty cells with only one or two possibilities altogether. Then it's futile and very time consuming to tinker with the later rows before backtracking. (To see what I mean, make play an IO-action and let it print out the field to be updated, like play :: [Field] -> IO (Maybe Field) play (f:a) | done f = return $ Just f -- | isFull f= play a | otherwise = do printField f getLine play ((genMoves f)++a) play [] = return Nothing ) A solution is to only consider the first empty cell: genMoves a = concat $ take 1 [update a i j|i<-[1..9],j<-[1..9],isEmpty (a!i!j)] That'll be still slow, but should finish before the gnab gib[1]. > - -- creates a list of all allowed entries > genMoves :: Field -> [Field] > genMoves a = concat [update a i j|i<-[1..9],j<-[1..9],isEmpty (a!i!j)] > where update b i j= [b //[(i,b!i //[(j,x)])]|x<-[1..9], checkField (b > //[(i,b!i //[(j,x)])])] > Another thing, I think, it'd look better if You used type Field = Array (Int,Int) Int. Cheers, Daniel [1] Douglas Adams, The Restaurant at the end of the Universe From wagner.andrew at gmail.com Mon Aug 6 21:44:55 2007 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Mon Aug 6 21:36:57 2007 Subject: [Haskell-cafe] Java 1.5 parser in Haskell In-Reply-To: <12025365.post@talk.nabble.com> References: <12025365.post@talk.nabble.com> Message-ID: I know this isn't quite what you asked, but java has a very clearly laid-out grammar in EBNF at http://java.sun.com/docs/books/jls/first_edition/html/19.doc.html . Between that and Parsec, I would think it would be fairly simple to write a parser. Of course, adding semantics is another story. On 8/6/07, tim.b wrote: > > Does anyone know of a fairly complete Java 1.5 parser and abstract syntax in > Haskell? > I've looked around quite a bit to no avail. > Thanks, > - Tim > -- > View this message in context: http://www.nabble.com/Java-1.5-parser-in-Haskell-tf4227017.html#a12025365 > Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From j.vimal at gmail.com Mon Aug 6 21:56:42 2007 From: j.vimal at gmail.com (Vimal) Date: Mon Aug 6 21:48:45 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> Message-ID: On 8/7/07, Hugh Perkins wrote: > Note that the "official" way to solve sudoku is to use "dancing links", but > I guess you are creating a naive implementation precisely as a base-line > against which to measure other implementations? > Well, Dancing Links (DLX) is just a data structure + few techniques to help with the backtrack, after modeling Sudoku as a contraint satisfaction problem. You can write a backtracking algorithm that is at least as fast as DLX :-) -- Vimal From dons at cse.unsw.edu.au Mon Aug 6 22:09:01 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Mon Aug 6 22:01:13 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> Message-ID: <20070807020901.GK8756@cse.unsw.EDU.AU> j.vimal: > On 8/7/07, Hugh Perkins wrote: > > Note that the "official" way to solve sudoku is to use "dancing links", but > > I guess you are creating a naive implementation precisely as a base-line > > against which to measure other implementations? > > > Well, Dancing Links (DLX) is just a data structure + few techniques > to help with the backtrack, after modeling Sudoku as a contraint > satisfaction problem. > > You can write a backtracking algorithm that is at least as fast as DLX :-) See also, http://haskell.org/haskellwiki/Sudoku -- Don From hughperkins at gmail.com Mon Aug 6 22:13:56 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Mon Aug 6 22:06:00 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <20070807020901.GK8756@cse.unsw.EDU.AU> References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> <20070807020901.GK8756@cse.unsw.EDU.AU> Message-ID: <837db430708061913m1fe8c073u9238fe7f10f36798@mail.gmail.com> On 8/7/07, Donald Bruce Stewart wrote: > > See also, > > http://haskell.org/haskellwiki/Sudoku > > -- Don > Just out of ... errr.... curiosity... which of those implementations is the fastest? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070807/0c68bc22/attachment-0001.htm From dons at cse.unsw.edu.au Mon Aug 6 22:17:01 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Mon Aug 6 22:09:07 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <837db430708061913m1fe8c073u9238fe7f10f36798@mail.gmail.com> References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> <20070807020901.GK8756@cse.unsw.EDU.AU> <837db430708061913m1fe8c073u9238fe7f10f36798@mail.gmail.com> Message-ID: <20070807021701.GN8756@cse.unsw.EDU.AU> hughperkins: > > On 8/7/07, Donald Bruce Stewart <[1]dons@cse.unsw.edu.au> > wrote: > > See also, > [2]http://haskell.org/haskellwiki/Sudoku > -- Don > > Just out of ... errr.... curiosity... which of those > implementations is the fastest? > No idea. You could compile them all with -O2, run them on a set of puzzles, and produce a table of results :-) I'm a little surprised no one's tried a parallel solution yet, actually. We've got an SMP runtime for a reason, people! -- Don From rk at trie.org Mon Aug 6 22:33:01 2007 From: rk at trie.org (Rahul Kapoor) Date: Mon Aug 6 22:25:04 2007 Subject: [Haskell-cafe] combinators for a simple grammar Message-ID: I am having problems coming up with nice combinators for a simple DSEL. The abstract syntax is simply given by the types: data SearchCondition = SearchCondition BoolTerm | OpOr SearchCondition BoolTerm data BoolTerm = BoolTerm BoolFactor | OpAnd BoolTerm BoolFactor data BoolFactor = Constant Bool My current combinators are (.||.) :: SearchCondition -> BoolTerm -> SearchCondition (.||.) sc term = OpOr sc term (.&&.) :: BoolTerm -> BoolFactor -> BoolTerm (.&&.) term fact = OpAnd term fact which allow you to write expression of the form factTrue = Constant True termTrue = BoolTerm factTrue scTrue = SearchCondition termTrue sc = scTrue .||. termTrue .||. termTrue .&&. factTrue I am wondering it it is possible to define combinators to hide the structure of the grammar from the user to some extent, so that the user can simply write things like sc = True .||.True .||. True .&&. False or sc = const True .||. const True .||. const True .&&. const False That is the user does not have to worry about the distinction between terms and factors (which exists solely for precedence in this case). Or is it a better idea to just remove the precedence rules from the types and move it the part of the code that evaluates the expressions? Rahul From stefanor at cox.net Mon Aug 6 22:49:30 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 6 22:41:36 2007 Subject: [Haskell-cafe] combinators for a simple grammar In-Reply-To: References: Message-ID: <20070807024930.GB5387@localhost.localdomain> On Mon, Aug 06, 2007 at 10:33:01PM -0400, Rahul Kapoor wrote: > I am having problems coming up with nice combinators for a simple > DSEL. The abstract syntax is simply given by the types: > > data SearchCondition = SearchCondition BoolTerm | OpOr SearchCondition BoolTerm > > data BoolTerm = BoolTerm BoolFactor | OpAnd BoolTerm BoolFactor > > data BoolFactor = Constant Bool > > > My current combinators are > > (.||.) :: SearchCondition -> BoolTerm -> SearchCondition > (.||.) sc term = OpOr sc term > > (.&&.) :: BoolTerm -> BoolFactor -> BoolTerm > (.&&.) term fact = OpAnd term fact > > which allow you to write expression of the form > > factTrue = Constant True > termTrue = BoolTerm factTrue > scTrue = SearchCondition termTrue > > sc = scTrue .||. termTrue .||. termTrue .&&. factTrue > > I am wondering it it is possible to define combinators to hide the > structure of the grammar from the user to some extent, so that the > user can simply write things like > > sc = True .||.True .||. True .&&. False > > or > > sc = const True .||. const True .||. const True .&&. const False > > That is the user does not have to worry about the distinction between > terms and factors (which exists solely for precedence in this case). > > Or is it a better idea to just remove the precedence rules from the > types and move it the part of the code that evaluates the expressions? I think it would be better still to remove it from both and rely on Haskell's built-in precedence parser. data SearchCondition = Constant Bool | SearchCondition :||: SearchCondition | SearchCondition :&&: SearchCondition infixr 3 :&&: infixr 2 :||: true = Constant True false = Constant False sc = true :||: true :||: true :&&: false eval (Constant k) = k eval (l :||: r) = eval l || eval r eval (l :&&: r) = eval l && eval r You can still hide the constructors if you want, of course. Another idea is to directly represent search conditions as functions: type SearchCondition = Object -> Bool -- could be just Bool to match your example, but I imagine you were -- simplifying, and making the leap from Bool to Object -> Bool is -- not always obvious (.||.) sc1 sc2 x = sc1 x || sc2 x (.&&.) sc1 sc2 x = sc1 x && sc2 x true x = True false x = False infixr 3 .&&. infixl 2 .||. -- eval is not needed! You can just apply a search condition to an -- object. The downside of this is that applying is *all* you can do, -- you can't optimize or analyze like you can with the explicit -- approach. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070806/43a8908e/attachment.bin From jcast at ou.edu Mon Aug 6 22:49:58 2007 From: jcast at ou.edu (Jonathan Cast) Date: Mon Aug 6 22:42:23 2007 Subject: [Haskell-cafe] combinators for a simple grammar In-Reply-To: References: Message-ID: <200708061950.12047.jcast@ou.edu> On Monday 06 August 2007, Rahul Kapoor wrote: > I am having problems coming up with nice combinators for a simple > DSEL. The abstract syntax is simply given by the types: > Or is it a better idea to just remove the precedence rules from the > types and move it the part of the code that evaluates the expressions? Exactly thus. Say: data SearchCondition = Constant Bool | SearchCondition :||: SearchCondition | SearchCondition :&&: SearchCondition infixr 3 (:&&:) infixr 2 (:||:) And you're set. Jonathan Cast http://sourceforge.net/projects/fid-core http://sourceforge.net/projects/fid-emacs -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070806/5998537b/attachment.bin From fb at frank-buss.de Mon Aug 6 23:13:34 2007 From: fb at frank-buss.de (Frank Buss) Date: Mon Aug 6 23:05:41 2007 Subject: [Haskell-cafe] Re: creating graphics the functional way In-Reply-To: References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> Message-ID: <021901c7d8a0$f0adfdd0$64c5a8c0@galilei> apfelmus wrote: > The idea of representing images simply by a function > > Int -> Int -> RGB > > is great :) You may want to look at Pan and its various > offsprings, in > particular Pancito > > http://www.haskell.org/haskellwiki/Applications_and_libraries/ > Graphics#Pan this looks interesting. The Java applets demonstrates that it is possible to implement this in realtime. I assume there are some clever optimizations implemented, which could be done with Haskell, too. > positions :: [Point] > positions = > zip [0.5 + fromIntegral n * dx | n <- [-2..2]] (cycle [y1,y2]) > where > dx = 0.125 > y1 = 0.15 > y2 = 0.25 Nice calculation for the positions, but at least for me it is more difficult to understand it than just writing the 5 points. But using lists is a good idea. I've updated the source: http://www.frank-buss.de/haskell/OlympicRings2.hs.txt http://www.frank-buss.de/haskell/OlympicRings2.png The anti-aliasing doesn't look good anyway, so I have removed it. Very cool for me was the "foldr (.) id" construct, which someone on #haskell suggested. Changing separate x/y coordinates to a list with 2 elements helped, too, to cleanup the source code. Maybe some more cleanups and the PNG save implementation, and then this code could be used as a small practical example for other Haskell newbies like me. BTW: Is there any coding standard for Haskell programs? I've seen different formattings, like how to indent "where" and the following parts of the code. Is there a common practice? -- Frank Buss, fb@frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From fb at frank-buss.de Mon Aug 6 23:15:53 2007 From: fb at frank-buss.de (Frank Buss) Date: Mon Aug 6 23:08:30 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: <200708062218.21965.coeus@gmx.de> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> <200708062218.21965.coeus@gmx.de> Message-ID: <023201c7d8a1$55a501c0$64c5a8c0@galilei> Marc A. Ziegert wrote: > in that source file, you define Size and Pixel as structs of > "Integer"s. that are neither unsigned chars (8_bit) nor ints > (32-64_bit) nor floats (32_bit) but an artificial oo_bit int > (1 int + list of bytes). > i'm sure you will gain a speedup by redefining these structs. > i.e. use Float or Int instead of Integer; see Data.Int and > Data.Word for more alternatives. I've tried it, but it was not faster. Using Word8 for the RGB pixels even resulted in wrong colors with the anti-aliased version, maybe because of number overflows. -- Frank Buss, fb@frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From ronguida at mindspring.com Mon Aug 6 23:38:33 2007 From: ronguida at mindspring.com (Ronald Guida) Date: Mon Aug 6 23:32:35 2007 Subject: [Haskell-cafe] Monad for Set? Message-ID: <46B7E939.3020705@mindspring.com> Hi, I'm pondering, is it possible to define a Set monad analogous to the List monad? My thinking is as follows: * "fmap f x" would apply f to each element in a set x * "return x" would create a singleton set {x} * "join x", where x is a set of sets: x = {x1, x2, ... xn}, would form their union (x1 U x2 U ... U xn) The advantage of Set over List is that duplicate elements would be removed automatically. There is just one /slight/ problem: In order to implement set operations, I need to be able to test elements for equality; that is, I need to impose the restriction (Eq a) => Set a. This is a problem because return really needs to work for any type; I have no way to guarantee (Eq a). In my search for answers, I came across "restricted monads". I don't like the idea of restricting the types I can return, and here's why. Suppose I had a way to impose (Eq a). Then I start to wonder: * What happens when I use a monad transformer like "StateT s Set a" or "ContT r Set a", but the types s and r are not equatable? * What happens when I want to define the monad transformer SetT because I need to put the IO monad inside it? In both cases, I feel I'm screwed if I really have to impose the constraint (Eq a) => Set a. This leads me think of a different solution: What if I could define a Set monad that's smart enough to "know", for any type a, whether or not (Eq a) holds, and degenerate to a blind list if the elements can't be equated. Ultimately, what I would need is a way to overload "join" (or "bind") with two different implementations, one for types that satisfy (Eq a), and another implementation for all other types. In my searching so far, I found ways to overload a function when all overloads share a common typeclass, and I have found ways to overload a function for disjoint types, provided that every type to be overload is an instance of some typeclass. All of the methods I have found so far are deficient in the sense that there is no way to provide a default implementation for types that don't fit into any typeclass. I have not been able to find a way to overload a function such that one implementation works for a special class of types, and another implementation works for *all* other types. Question: Is it possible to define join :: [[a]] -> [a], with (1) a special implementation that requires (Eq a) and removes duplicate elements, and (2) a general implementation to fall back on for *any* type that fails the constraint, and (3) a way to make "f" fully generic, such that the correct implementation is chosen automatically from the type variable a? If I had a way to do this, then I could define a Set monad that performs set operations when it can (i.e. when the elements are equatable), but which automatically degenerates to a simple List when it has to (i.e. when there's no equality test). I almost suspect that I might need to use Haskell Templates (I currently know nothing about Haskell Templates). Even better, if this problem is solvable, then the next step would be to overload again to use an efficient implementation when set elements are comparable (Ord a). Any ideas? -- Ron From hughperkins at gmail.com Mon Aug 6 23:49:39 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Mon Aug 6 23:41:43 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <20070807021701.GN8756@cse.unsw.EDU.AU> References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> <20070807020901.GK8756@cse.unsw.EDU.AU> <837db430708061913m1fe8c073u9238fe7f10f36798@mail.gmail.com> <20070807021701.GN8756@cse.unsw.EDU.AU> Message-ID: <837db430708062049t422e725fyf481d92cee02157@mail.gmail.com> On 8/7/07, Donald Bruce Stewart wrote: > > > No idea. You could compile them all with -O2, run them on a set of > puzzles, and produce a table of results :-) Well I could, but I wont ;-) If you had to guess which one is fastest which one would you guess? I'm a little surprised no one's tried a parallel solution yet, actually. > We've got an SMP runtime for a reason, people! > Funny that you should mention that, this was actually one of the Topcoder marathon match contests for multithreading: http://www.topcoder.com/longcontest/?module=ViewProblemStatement&compid=5624&rd=9892 (you'll need to login to see the problem statement, but basically it's Sudoku, on a 16-core Xeon (I think)) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070807/26a456ac/attachment.htm From haskell at brecknell.org Tue Aug 7 00:07:50 2007 From: haskell at brecknell.org (Matthew Brecknell) Date: Mon Aug 6 23:59:53 2007 Subject: [Haskell-cafe] Monad for Set? In-Reply-To: <46B7E939.3020705@mindspring.com> References: <46B7E939.3020705@mindspring.com> Message-ID: <1186459670.32536.1204088619@webmail.messagingengine.com> Ronald Guida: > I'm pondering, is it possible to define a Set monad analogous to the > List monad? [snip] > This leads me think of a different solution: What if I could define a > Set monad that's smart enough to "know", for any type a, whether or > not (Eq a) holds, and degenerate to a blind list if the elements can't > be equated. Ultimately, what I would need is a way to overload "join" > (or "bind") with two different implementations, one for types that > satisfy (Eq a), and another implementation for all other types. You might find this interesting, in case you haven't yet seen it: http://article.gmane.org/gmane.comp.lang.haskell.cafe/18118 If you also read the rest of that thread, you'll see that with a recent GHC HEAD, you should be able to avoid the need for the Teq witness. From brianh at metamilk.com Tue Aug 7 00:49:57 2007 From: brianh at metamilk.com (Brian Hulley) Date: Tue Aug 7 00:41:52 2007 Subject: [Haskell-cafe] Newbie question: "multi-methods" in Haskell In-Reply-To: <000101c7d86a$a54da290$efe8e7b0$@be> References: <008801c7d847$ecdd6b40$c69841c0$@be> <46B75810.9070509@metamilk.com> <46B76A5D.5070607@imageworks.com> <46B7731F.3040100@metamilk.com> <000101c7d86a$a54da290$efe8e7b0$@be> Message-ID: <46B7F9F5.4040008@metamilk.com> peterv wrote: > This is very nice, but it does not really solve the original problem. > To get Haskell to choose the best fit it's necessary to encode the location of each element in the hierarchy, so that elements deeper in the hierarchy are more instantiated than those at the top. Then instance selection chooses the best fit by just choosing the most instantiated match. Encoding can be done using phantom types, so a generic solid has the path IsSolid s a planet has IsSolid (IsPlanet p) and a specific planet eg Earth has path IsSolid (IsPlanet Earth) A newtype can be used to associate the path with the actual object: newtype InH path body = InH body so Earth is represented by InH Earth :: InH (IsSolid (IsPlanet Earth)) Earth A class with a functional dependency gives us the mapping between concrete objects and the objects as viewed by the hierarchy: class ToH body path | body -> path where toH :: body -> InH path body toH = InH The functional dependency means that the path (location in the hierarchy) is uniquely determined by the body, and instance decls then define this relationship: instance ToH Asteroid (IsSolid Asteroid) instance ToH Jupiter (IsSolid (IsPlanet Jupiter)) instance ToH Earth (IsSolid (IsPlanet Earth)) The code is below but as you can see the OOP encoding in Haskell becomes quite heavy and clunky so this style is probably not ideal for a real program - Tillmann's suggestion to use algebraic datatypes instead is more idiomatic - but anyway here goes: {-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances #-} module Collide where class Collide a where collide :: a -> String data Asteroid = Asteroid data Jupiter = Jupiter data Earth = Earth data IsSolid a data IsPlanet a newtype InH path body = InH body class ToH body path | body -> path where toH :: body -> InH path body toH = InH instance ToH Asteroid (IsSolid Asteroid) instance ToH Jupiter (IsSolid (IsPlanet Jupiter)) instance ToH Earth (IsSolid (IsPlanet Earth)) data Collision = forall a. Collide a => Collision a mkCollision :: (ToH a pa, ToH b pb, Collide (InH pa a, InH pb b)) => a -> b -> Collision mkCollision a b = Collision (toH a, toH b) instance Collide (InH (IsSolid a) aa, InH (IsSolid b) bb) where collide _ = "generic collision" instance Collide (InH (IsSolid Asteroid) Asteroid, InH (IsSolid (IsPlanet bb)) cc) where collide _ = "an asteroid hit a planet" instance Collide (InH (IsSolid (IsPlanet a)) aa, InH (IsSolid Asteroid) Asteroid) where collide _ = "an asteroid hit a planet" instance Collide (InH (IsSolid Asteroid) Asteroid, InH (IsSolid (IsPlanet Earth)) Earth) where collide _ = "the end of the dinos" instance Collide (InH (IsSolid (IsPlanet Earth)) Earth, InH (IsSolid Asteroid) Asteroid) where collide _ = "the end of the dinos" instance Collide Collision where collide (Collision a) = collide a ----------------------- ghci output *Collide> mapM_ putStrLn (map collide [ mkCollision Asteroid Earth , mkCollision Earth Asteroid , mkCollision Jupiter Asteroid , mkCollision Asteroid Jupiter , mkCollision Asteroid Asteroid ]) the end of the dinos the end of the dinos an asteroid hit a planet an asteroid hit a planet generic collision *Collide> Best regards, Brian. From hughperkins at gmail.com Tue Aug 7 02:29:10 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 7 02:21:15 2007 Subject: [Haskell-cafe] Any ideas how to go about doing a phd in threading? Message-ID: <837db430708062329mcc0b651gbc45fa2b3a825c57@mail.gmail.com> Hi, Really interested in doing a phd on threading. Any ideas how I'd go about doing/applying for that? Basically, threading seems to be the cutting-edge right out (for a while) as processor frequencies top out, and multicores increase. I dont have any formal CS training, but I do have a degree in natsci from Cambridge, quite a few years experience in industry, and anyone who knows me can attest that I'm highly motivated; a string of opensource work shows that I'm more interested in having fun than earning money, for a geek's definition of having fun :-) No particular preference for language, whatever it takes ;-) The Haskell group seems to have a high percentage of phds, and Haskell is a candidate language for automatic thread management, so seems an appropriate group to ask about this? Here's my cv in case it's useful: http://manageddreams.com/CV_PERKINS.pdf -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070807/1cf09a67/attachment.htm From vitaliy.akimov at gmail.com Tue Aug 7 03:41:29 2007 From: vitaliy.akimov at gmail.com (Vitaliy Akimov) Date: Tue Aug 7 03:33:29 2007 Subject: [Haskell-cafe] Monad for Set? In-Reply-To: <1186459670.32536.1204088619@webmail.messagingengine.com> References: <46B7E939.3020705@mindspring.com> <1186459670.32536.1204088619@webmail.messagingengine.com> Message-ID: > > If you also read the rest of that thread, you'll see that with a recent > GHC HEAD, you should be able to avoid the need for the Teq witness. > http://www.cs.chalmers.se/~rjmh/Papers/restricted-datatypes.ps here is solution which doesn't require GADT and HEAD, but it does require changing of monad interface. This trick is used in SYB3. From mgross21 at verizon.net Tue Aug 7 04:48:03 2007 From: mgross21 at verizon.net (Murray Gross) Date: Tue Aug 7 04:23:53 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <20070807021701.GN8756@cse.unsw.EDU.AU> References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> <20070807020901.GK8756@cse.unsw.EDU.AU> <837db430708061913m1fe8c073u9238fe7f10f36798@mail.gmail.com> <20070807021701.GN8756@cse.unsw.EDU.AU> Message-ID: I am working on a parallel brute-force solver, which will be tested on 25x25 puzzles (my current serial solver requires less than 1 second for the most difficult 9x9 puzzles I've been able to find; while I haven't tried it on 16x16 puzzles on one of the machines in the Brooklyn College Metis cluster, extrapolation from another machine indicates that 16x16 puzzles will take 15-20 minutes; the 25x25 test case I have requires about a week on a cluster machine). Unfortunately, we have a lot of preparatory work to do, so it will be a while before I have any results from a puzzle solver. The parallel work will be done on our parallel version of release 5 Haskell. Murray Gross Brooklyn College On Tue, 7 Aug 2007, Donald Bruce Stewart wrote: > hughperkins: >> >> On 8/7/07, Donald Bruce Stewart <[1]dons@cse.unsw.edu.au> >> wrote: >> >> See also, >> [2]http://haskell.org/haskellwiki/Sudoku >> -- Don >> >> Just out of ... errr.... curiosity... which of those >> implementations is the fastest? >> > > No idea. You could compile them all with -O2, run them on a set of > puzzles, and produce a table of results :-) > > I'm a little surprised no one's tried a parallel solution yet, actually. > We've got an SMP runtime for a reason, people! > > -- Don > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From hughperkins at gmail.com Tue Aug 7 05:27:10 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 7 05:19:12 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> <20070807020901.GK8756@cse.unsw.EDU.AU> <837db430708061913m1fe8c073u9238fe7f10f36798@mail.gmail.com> <20070807021701.GN8756@cse.unsw.EDU.AU> Message-ID: <837db430708070227n4732bb08kf96c2aa2b1ae03e1@mail.gmail.com> On 8/7/07, Murray Gross wrote: > > I am working on a parallel brute-force solver, which will be tested on > 25x25 puzzles (my current serial solver requires less than 1 second for > the most difficult 9x9 puzzles I've been able to find; while I haven't > tried it on 16x16 puzzles on one of the machines in the Brooklyn College > Metis cluster, extrapolation from another machine indicates that 16x16 > puzzles will take 15-20 minutes; the 25x25 test case I have requires about > a week on a cluster machine). > Question: what do you mean by, for example 25x25? Do you mean grids with a total length of 25 on each side, eg: 21 13 4 19 18 17 22 1 6 24 10 11 8 14 12 2 16 23 7 15 25 20 3 5 9 1 16 6 5 10 14 25 2 8 15 23 7 24 21 13 20 3 17 11 9 19 4 18 22 12 3 2 17 9 11 4 18 7 5 12 16 19 25 20 6 22 13 21 24 10 15 14 8 23 1 23 20 25 12 15 11 16 13 19 3 5 9 1 17 22 14 4 18 8 6 7 2 10 21 24 7 14 8 24 22 23 20 9 21 10 4 2 18 15 3 19 12 1 25 5 6 17 16 11 13 18 5 16 11 4 25 23 6 13 1 21 12 10 24 8 15 20 14 3 22 17 9 2 19 7 17 10 22 8 23 15 7 21 20 4 3 6 2 1 19 25 9 5 12 18 11 13 24 16 14 12 19 13 2 6 3 10 14 24 17 7 20 9 11 4 23 1 8 16 21 22 5 25 15 18 15 9 14 20 3 12 8 19 16 5 22 25 17 23 18 11 24 13 2 7 21 6 1 4 10 25 7 1 21 24 2 9 22 11 18 15 5 14 13 16 10 6 19 4 17 23 8 12 3 20 2 17 23 3 19 8 6 12 10 20 14 18 16 25 24 9 21 15 1 4 13 22 11 7 5 13 24 15 1 20 19 21 23 4 7 6 17 5 2 11 16 18 22 10 3 9 12 14 8 25 9 22 12 16 21 1 13 17 18 25 19 8 15 4 7 5 14 2 20 11 24 3 23 10 6 8 6 7 10 14 16 5 3 22 11 12 23 21 9 20 17 25 24 13 19 4 18 15 1 2 11 18 5 4 25 24 2 15 9 14 13 22 3 10 1 8 23 7 6 12 20 16 19 17 21 16 15 19 13 12 10 3 4 17 6 20 21 23 18 25 24 7 9 14 8 1 11 5 2 22 14 21 18 22 9 7 11 16 23 2 8 1 6 12 5 3 19 20 15 13 10 24 17 25 4 6 8 11 7 2 5 1 24 25 9 17 14 13 16 15 18 10 4 22 23 12 19 21 20 3 5 4 20 25 1 13 15 8 12 22 11 24 19 3 10 6 17 16 21 2 18 7 9 14 23 24 3 10 23 17 18 19 20 14 21 9 4 22 7 2 1 11 12 5 25 8 15 13 6 16 10 12 9 6 5 22 14 18 7 13 25 16 11 8 21 4 15 3 17 1 2 23 20 24 19 19 25 24 18 16 20 17 5 2 8 1 10 4 6 23 12 22 11 9 14 3 21 7 13 15 22 23 3 17 7 6 12 25 15 19 2 13 20 5 14 21 8 10 18 24 16 1 4 9 11 4 11 2 15 8 21 24 10 1 16 18 3 7 19 9 13 5 6 23 20 14 25 22 12 17 20 1 21 14 13 9 4 11 3 23 24 15 12 22 17 7 2 25 19 16 5 10 6 18 8 ... or do you mean grids where each subgrid is 25x25, and the entire grid is 625 x 625? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070807/80bd9771/attachment.htm From dons at cse.unsw.edu.au Tue Aug 7 06:02:29 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Tue Aug 7 05:54:36 2007 Subject: [Haskell-cafe] Haskell Weekly News: August 07, 2007 Message-ID: <20070807100228.GY8756@cse.unsw.EDU.AU> --------------------------------------------------------------------------- Haskell Weekly News http://sequence.complete.org/hwn/20070807 Issue 64 - August 07, 2007 --------------------------------------------------------------------------- Welcome to issue 64 of HWN, a weekly newsletter covering developments in the [1]Haskell community. This issue marks the second anniversary of the Haskell (not quite) Weekly News. Thanks to the Haskell community for support, content and for reading over the last two years! 1. http://haskell.org/ Announcements OSCON Haskell Tutorial. Simon Peyton-Jones Appeared at the O'Reilly Open Source Convention (OSCON) in Portland, delivering a range of talks, including [2]A Taste of Haskell, [3]A Keynote on Functional Languages, [4]Nested Data Parallelism and [5]Transactional Memory for Concurrent Programming. Videos are available for most of these talks: [6]A Taste of Haskell: Part 1, [7]A Taste of Haskell: Part 2, [8]slides for A Taste of Haskell, [9]Transactional Memory for Concurrent Programming and [10]the NDP talk at the London Hugs meeting. 2. http://conferences.oreillynet.com/cs/os2007/view/e_sess/14016 3. http://conferences.oreillynet.com/cs/os2007/view/e_sess/14773 4. http://conferences.oreillynet.com/cs/os2007/view/e_sess/14014 5. http://conferences.oreillynet.com/cs/os2007/view/e_sess/14017 6. http://blip.tv/file/324976 7. http://www.blip.tv/file/325646/ 8. http://conferences.oreillynet.com/presentations/os2007/os_peytonjones.pdf 9. http://www.blip.tv/file/317758/ 10. http://video.google.co.uk/videoplay?docid=370317485066035666 hpodder 1.0. John Goerzen [11]announced version 1.0.0 of hpodder, the command-line podcatcher (podcast downloader) that just happens to be written in everyone's favorite language. You can get it [12]here. Version 1.0.0 sports a new mechanism for detecting and disabling feeds or episodes that repeatedly result in errors, updates to the Sqlite database schema, and several bugfixes. 11. http://article.gmane.org/gmane.comp.lang.haskell.general/15452 12. http://software.complete.org/hpodder encoding-0.1. Henning G?nther [13]announced the release of 'encoding', a Haskell library to cope with many character encodings found on modern computers. At the moment it supports (much more is planned): ASCII, UTF-8, -16, -32, ISO 8859-* (alias latin-*), CP125* (windows codepages), KOI8-R, Bootstring (base for punycode) 13. http://article.gmane.org/gmane.comp.lang.haskell.general/15481 Dimensional 0.6: Statically checked physical dimensions. Bj?rn Buckwalter [14]announced a library providing data types for performing arithmetic with physical quantities and units. Information about the physical dimensions of the quantities/units is embedded in their types and the validity of operations is verified by the type checker at compile time. The boxing and unboxing of numerical values as quantities is done by multiplication and division with units. 14. http://article.gmane.org/gmane.comp.lang.haskell.cafe/26944 Hackage This week's new libraries in [15]the Hackage library database. * hgal-1.0.1. Jean Philippe Bernardy. [16]Computation automorphism group and canonical labeling of a graph * hpodder-1.0.3. John Goerzen. [17]Podcast Aggregator (downloader) * dlist-0.3.1. Don Stewart. [18]Differences lists: a list-like type supporting O(1) append * pointfree-1.0. Felix Martini. [19]Stand-alone command-line version of the point-less plugin for lambdabot * encoding-0.1. Henning Guenther. [20]A library for various character encodings * AppleScript-0.1.3. Wouter Swierstra. [21]Call AppleScript from Haskell * SDL-ttf-0.4.0. David Himmelstrup. [22]Binding to libSDL_ttf * Finance-Quote-Yahoo-0.2. Brad Clawsie. [23]Obtain quote data from finance.yahoo.com * xmobar-0.7. Andrea Rossato. [24]A Minimalistic Text Based Status Bar 15. http://hackage.haskell.org/ 16. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hgal-1.0.1 17. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hpodder-1.0.3 18. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/dlist-0.3.1 19. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/pointfree-1.0 20. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/encoding-0.1 21. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/AppleScript-0.1.3 22. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/SDL-ttf-0.4.0 23. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Finance-Quote-Yahoo-0.2 24. http://hackage.haskell.org/cgi-bin/hackage-scripts/package/xmobar-0.7 Conference roundup OSCON. Simon Peyton-Jones gave a series of popular talks about Haskell and functional programming at OSCON, in Portland. Below are collected just some of the posts about Haskell at OSCON. * [25]A brief Haskell-at-OSCON trip report * [26]Wow! OSCON video viewing statistics * [27]OSCon Wednesday Part 2 * [28]A Taste of Haskell, A Taste of C * [29]OSCON Day 1 * [30]A Taste of Haskell * [31]OSCON 2007 * [32]Threading Building Blocks and C++ * [33]OSCON: Wednesday Morning * [34]OSCON: Wednesday Afternoon * [35]OSCON 2007 (July 25) * [36]Nested Data Parallelism in Haskell * [37]OSCON 2007: Wednesday Morning Keynotes * [38]A Taste of Haskell 25. http://www.realworldhaskell.org/blog/2007/08/03/a-brief-haskell-at-oscon-trip-report/ 26. http://www.realworldhaskell.org/blog/2007/08/07/wow-oscon-video-viewing-statistics/ 27. http://changelog.complete.org/posts/632-OSCon-Wednesday-Part-2.html 28. http://www.oreillynet.com/onlamp/blog/2007/07/a_taste_of_haskell_a_taste_of.html 29. http://brycebaril.vox.com/library/post/oscon-2007-day-1.html 30. http://jaortega.wordpress.com/2007/08/04/a-taste-of-haskell/ 31. http://www.sauria.com/blog/2007/08/03/oscon-2007/ 32. http://softwareblogs.intel.com/2007/07/26/threading-building-blocks-and-c/ 33. http://znark.com/blog/2007/07/25/oscon-wednesday-morning 34. http://znark.com/blog/2007/07/25/oscon-wednesday-afternoon 35. http://panela.blog-city.com/oscon_2007_july_25.htm 36. http://ihack.us/2007/07/25/nested-data-parallelism-in-haskell/ 37. http://www.canspice.org/2007/07/25/oscon-2007-wednesday-morning-keynotes/ 38. http://butlerpress.com/2007/07/24/a-taste-of-haskell/ Blog noise [39]Haskell news from the [40]blogosphere. * [41]Ord, Countable Ordinals, and an Idea of sigfpe * [42]Word numbers, Part 1: Billion approaches * [43]Implementing SmallTalk in Haskell * [44]From walking to zipping, Part 1: Moving right * [45]From walking to zipping, Part 2: Down and up * [46]Irrefutable patterns for the ignorant * [47]Making Haskell nicer for game programming * [48]Nested Data Parallelism in Haskell * [49]Compiling Haskell to Erlang * [50]Peano's Axioms IV: Advanced Functions and Integers * [51]37 Reasons to Love Haskell * [52]On the value of strong static typing * [53]Parsec Parser Testing with QuickCheck * [54]Fallacies in the Great Dynamic vs Static Debate * [55]Implementing a dictionary using first class functions * [56]Strong specifications in Coq: the type says everything * [57]Run length encoding in Haskell * [58]Run length encoding and arrows * [59]Playing with Arrows * [60]Monads! (and Why Monad Tutorials Are All Awful) * [61]Haskell: Explaining Arrows through XML Transformations * [62]Monads as computation * [63]Closed Categories * [64]Good Haskell Style * [65]Monads are hard to teach * [66]Parsec * [67]First attempt at using GTK with Haskell * [68]Introduction to Haskell, Part 3: Monads * [69]Programming in Haskell * [70]Haskell Fun * [71]Algebraic Data Types again * [72]DFAs, Categories, and Typecheckers * [73]Haskell State Accessors (second attempt: Composability) * [74]Developing Programs and Proofs Spontaneously using GADT * [75]Encoding Inductive and Coinductive Types in Polymorphic Lambda Calculus * [76]Polymorphic Types in Haskell without Constructors? * [77]Subtraction not Definable in Simply Typed Lambda Calculus * [78]Imperative programming is a special type of functional programming * [79]Binding Haskell to C structs 39. http://planet.haskell.org/ 40. http://haskell.org/haskellwiki/Blog_articles 41. http://blog.jbapple.com/2007/07/ord-countable-ordinals-and-idea-of.html 42. http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers1/ 43. http://lstephen.wordpress.com/2007/07/23/completing-the-spike/ 44. http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WalkZip1/ 45. http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WalkZip2/ 46. http://therning.org/magnus/archives/311 47. http://luqui.org/blog/archives/2007/07/26/making-haskell-nicer-for-game-programming/ 48. http://ihack.us/2007/07/25/nested-data-parallelism-in-haskell/ 49. http://blog.tornkvist.org/?id=1185571582964040 50. http://disparatemathematician.blogspot.com/2007/07/peanos-axioms-iv-advanced-functions-and.html 51. http://cdsmith.wordpress.com/2007/07/29/37-reasons-to-love-haskell-playing-off-the-ruby-article/ 52. http://www.serpentine.com/blog/2007/07/29/on-the-value-of-strong-static-typing/ 53. http://lstephen.wordpress.com/2007/07/29/parsec-parser-testing-with-quickcheck/ 54. http://neilbartlett.name/blog/2007/07/30/fallacies-in-the-great-dynamic-vs-static-debate/ 55. http://lukeplant.me.uk/blog.php?id=1107301671 56. http://www.rubrication.net/2007/04/24/strong-specifications/ 57. http://cgi.cse.unsw.edu.au/~dons/blog/2007/07/31#rle 58. http://community.livejournal.com/evan_tech/229752.html 59. http://unenterprise.blogspot.com/2007/08/playing-with-arrows.html 60. http://ahamsandwich.wordpress.com/2007/07/26/monads-and-why-monad-tutorials-are-all-awful/ 61. http://neilbartlett.name/blog/2007/08/01/haskell-explaining-arrows-through-xml-transformationa/ 62. http://www.haskell.org/haskellwiki/Monads_as_computation 63. http://unapologetic.wordpress.com/2007/08/01/closed-categories/ 64. http://urchin.earth.li/~ian/style/haskell.html 65. http://davblog48.blogspot.com/2007/08/monads-are-hard-to-teach.html 66. http://davblog48.blogspot.com/2007/05/parsec.html 67. http://davblog48.blogspot.com/2007/05/first-attempt-at-using-gtk-with-haskell.html 68. http://www.onlamp.com/pub/a/onlamp/2007/08/02/introduction-to-haskell-pure-functions.html 69. http://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/external.html 70. http://changelog.complete.org/posts/640-guid.html 71. http://blog.tmorris.net/algebraic-data-types-again/ 72. http://disparatemathematician.blogspot.com/2007/08/dfas-categories-and-typecheckers.html 73. http://luqui.org/blog/archives/2007/08/05/haskell-state-accessors-second-attempt-composability/ 74. http://www.iis.sinica.edu.tw/~scm/?p=32 75. http://www.iis.sinica.edu.tw/~scm/?p=31 76. http://www.iis.sinica.edu.tw/~scm/?p=28 77. http://www.iis.sinica.edu.tw/~scm/?p=27 78. http://blog.tmorris.net/imperative-programming-is-a-special-type-of-functional-programming/ 79. http://therning.org/magnus/archives/315 Quotes of the Week * schluehk: ... Haskell taking over the world and troubled parents ask why their kids have turned into math hippies talking about nothing but love and abstract algebra... * JohnGoerzen: Haskell manipulates functions with the same ease that Perl manipulates strings * (anonymous Russian blogger): Glory to Simons! Glory to Swedish professors! * Laurent Sansonetti: I appreciated so much the Haskell talks that I am now learning the language. * dcoutts: Apparently that's only 200x faster than the faster of two common python serialisation libs, so we've got some way to go yet. * slava: [on Isabelle for web frameworks] IM IN UR WEB SITEZ, CODING PROVABLY-CORRECT BLINK TAG!! * gimboland: At present i'd say 'tinkering with a nuclear bomb' is approximately where i am with monads... * jcreigh: Could not find instance Ord for type ProgrammingLanguage * kowey: i suspect we're one of the rare wikibooks to use higher order templates * monochrom: 'm a -> (a -> m b) -> m b' is much more to the point than 'mumble computation mumble computation mumble computation mumble' * roconnor: damn it, Haskell pseudo code is indistinguishable from actual code * slava: Because top enterprise industry analysts recommend Because top enterprise industry analysts recommend that managers need to focus on Agile methodologies, SOA, B2B and Yoneda's lemma in today's rich internet application-driven environment. Don't get left behind by the AJAX craze by missing out on call center outsourcing and Yoneda's lemma! Code Watch Notable new features and bug fixes to the Haskell compilers. Fri Jul 27 03:41:57 PDT 2007. Simon Marlow. Pointer Tagging. This patch implements pointer tagging as per our ICFP'07 paper 'Faster laziness using dynamic pointer tagging'. It improves performance by 10-15% for most workloads, including GHC itself. The original patches were by Alexey Rodriguez Yakushev, with additions and improvements by me. I've re-recorded the development as a single patch. The basic idea is this: we use the low 2 bits of a pointer to a heap object (3 bits on a 64-bit architecture) to encode some information about the object pointed to. For a constructor, we encode the 'tag' of the constructor (e.g. True vs. False), for a function closure its arity. This enables some decisions to be made without dereferencing the pointer, which speeds up some common operations. In particular it enables us to avoid costly indirect jumps in many cases. More information [80]in the commentary. 80. http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/HaskellExecution/PointerTagging About the Haskell Weekly News Each week, new editions are posted to [81]the Haskell mailing list as well as to [82]the Haskell Sequence and [83]Planet Haskell. [84]RSS is also available, and headlines appear on [85]haskell.org. Headlines are available as [86]PDF. To help create new editions of this newsletter, please see the [87]contributing information. Send stories to dons at cse.unsw.edu.au. The darcs repository is available at darcs get [88]http://www.cse.unsw.edu.au/~dons/code/hwn 81. http://www.haskell.org/mailman/listinfo/haskell 82. http://sequence.complete.org/ 83. http://planet.haskell.org/ 84. http://sequence.complete.org/node/feed 85. http://haskell.org/ 86. http://www.cse.unsw.edu.au/~dons/code/hwn/archives/20070807.pdf 87. http://haskell.org/haskellwiki/HWN 88. http://www.cse.unsw.edu.au/~dons/code/hwn From hughperkins at gmail.com Tue Aug 7 06:12:20 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 7 06:04:22 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <837db430708070227n4732bb08kf96c2aa2b1ae03e1@mail.gmail.com> References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> <20070807020901.GK8756@cse.unsw.EDU.AU> <837db430708061913m1fe8c073u9238fe7f10f36798@mail.gmail.com> <20070807021701.GN8756@cse.unsw.EDU.AU> <837db430708070227n4732bb08kf96c2aa2b1ae03e1@mail.gmail.com> Message-ID: <837db430708070312i5a4a90dfpfd29b85672fc7e07@mail.gmail.com> On 8/7/07, Hugh Perkins wrote: > > Question: what do you mean by, for example 25x25? Do you mean grids with > a total length of 25 on each side, eg: > (because on my super-dooper 1.66GHz Celeron, generating 10 random 25x25 grids such as the one above takes about 1.01 seconds; solving an actual puzzle should be faster because the solution space is more tightly constrained?) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070807/3cdb5c8a/attachment.htm From polyomino at f2s.com Tue Aug 7 08:58:17 2007 From: polyomino at f2s.com (DavidA) Date: Tue Aug 7 08:50:44 2007 Subject: [Haskell-cafe] Type classes: Missing language feature? Message-ID: Hi, there's something I'm trying to do with type classes that seems to fit very naturally with my mental model of type classes, but doesn't seem to be supported by the language. I'm wondering whether I'm missing something, or whether there's some language extension that could help me or alternative way of achieving what I'm trying to achieve. I'm trying to define multivariate polynomials, which are sums of monomials - for example x^2y + z^4. In algorithms on multivariate polynomials, one typically wants to support different monomial orders. For example, the lex order is dictionary order - xxy < xy < y < yyy - whereas the graded lex (glex) order also takes into account the degree of the monomials - y < xy < xxy < yyy. Here's some code (based on http://sigfpe.blogspot.com/2007/07/ill-have- buchburger-with-fries.html): import Data.Map as M import Data.List as L newtype Monomial = Monomial (Map String Int) deriving (Eq) x = Monomial $ singleton "x" 1 y = Monomial $ singleton "y" 1 instance Show Monomial where show (Monomial a) = concatMap (\(v,i)-> v ++ "^" ++ show i) $ toList a -- simplified for brevity instance Num Monomial where Monomial a * Monomial b = Monomial $ unionWith (+) a b newtype Lex = Lex Monomial deriving (Eq) newtype Glex = Glex Monomial deriving (Eq) instance Ord Lex where Lex (Monomial m) <= Lex (Monomial m') = toList m <= toList m' instance Ord Glex where Glex (Monomial m) <= Glex (Monomial m') = (sum $ elems m, toList m) <= (sum $ elems m', toList m') Now, what I'd like to do is have Lex and Glex, and any further monomial orderings I define later, automatically derive Show and Num instances from Monomial (because it seems like boilerplate to have to define Show and Num instances by hand). Something like the following (not valid Haskell): class OrdMonomial m where fromRaw :: Monomial -> m toRaw :: m -> Monomial instance OrdMonomial Lex where fromRaw m = Lex m toRaw (Lex m) = m instance OrdMonomial Glex where fromRaw m = Glex m toRaw (Glex m) = m derive OrdMonomial m => Show m where show m = show (toRaw m) derive OrdMonomial m => Num m where m * m' = fromRaw (toRaw m * toRaw m') Is there a way to do what I'm trying to do? (Preferably without resorting to template Haskell, etc) - It seems like a natural thing to want to do. From apfelmus at quantentunnel.de Tue Aug 7 09:46:16 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Tue Aug 7 09:38:34 2007 Subject: [Haskell-cafe] Re: Type classes: Missing language feature? In-Reply-To: References: Message-ID: DavidA wrote: > > newtype Lex = Lex Monomial deriving (Eq) > newtype Glex = Glex Monomial deriving (Eq) > > Now, what I'd like to do is have Lex and Glex, and any further monomial > orderings I define later, automatically derive Show and Num instances from > Monomial (because it seems like boilerplate to have to define Show and Num > instances by hand). Good news: it's already implemented and called newtype deriving :) http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#newtype-deriving In short, you just write newtype Lex = Lex Monomial deriving (Eq, Show, Num) I guess that the Show instance will add the constructor Lex , though. Regards, apfelmus From derek.a.elkins at gmail.com Tue Aug 7 09:59:55 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Tue Aug 7 09:52:12 2007 Subject: [Haskell-cafe] Type classes: Missing language feature? In-Reply-To: References: Message-ID: <1186495195.6796.49.camel@derek-laptop> On Tue, 2007-08-07 at 12:58 +0000, DavidA wrote: > Hi, there's something I'm trying to do with type classes that seems to fit very > naturally with my mental model of type classes, but doesn't seem to be > supported by the language. I'm wondering whether I'm missing something, or > whether there's some language extension that could help me or alternative way > of achieving what I'm trying to achieve. > > I'm trying to define multivariate polynomials, which are sums of monomials - > for example x^2y + z^4. In algorithms on multivariate polynomials, one > typically wants to support different monomial orders. For example, the lex > order is dictionary order - xxy < xy < y < yyy - whereas the graded lex (glex) > order also takes into account the degree of the monomials - y < xy < xxy < yyy. > > Here's some code (based on http://sigfpe.blogspot.com/2007/07/ill-have- > buchburger-with-fries.html): > > import Data.Map as M > import Data.List as L > > newtype Monomial = Monomial (Map String Int) deriving (Eq) > x = Monomial $ singleton "x" 1 > y = Monomial $ singleton "y" 1 > instance Show Monomial where > show (Monomial a) = concatMap (\(v,i)-> v ++ "^" ++ show i) $ toList a -- > simplified for brevity > instance Num Monomial where > Monomial a * Monomial b = Monomial $ unionWith (+) a b > > newtype Lex = Lex Monomial deriving (Eq) > newtype Glex = Glex Monomial deriving (Eq) > > instance Ord Lex where > Lex (Monomial m) <= Lex (Monomial m') = toList m <= toList m' > > instance Ord Glex where > Glex (Monomial m) <= Glex (Monomial m') = (sum $ elems m, toList m) <= (sum > $ elems m', toList m') > > Now, what I'd like to do is have Lex and Glex, and any further monomial > orderings I define later, automatically derive Show and Num instances from > Monomial (because it seems like boilerplate to have to define Show and Num > instances by hand). Something like the following (not valid Haskell): > > class OrdMonomial m where > fromRaw :: Monomial -> m > toRaw :: m -> Monomial > > instance OrdMonomial Lex where > fromRaw m = Lex m > toRaw (Lex m) = m > > instance OrdMonomial Glex where > fromRaw m = Glex m > toRaw (Glex m) = m > > derive OrdMonomial m => Show m where > show m = show (toRaw m) > > derive OrdMonomial m => Num m where > m * m' = fromRaw (toRaw m * toRaw m') > > Is there a way to do what I'm trying to do? (Preferably without resorting to > template Haskell, etc) - It seems like a natural thing to want to do. I don't think there is a way to do exactly what you want. However, there's an alternative approach that you may want to look at. Right now you are using a technique called Wrapper types. An alternative would be to use phantom types and have the ordering be specified by the type parameter. So something like the following, newtype Monomial ord = Monomial (Map String Int) deriving (Eq) instance Show (Monomial ord) where show (Monomial a) = concatMap (\(v,i)-> v ++ "^" ++ show i) $ toList a instance Num (Monomial ord) where Monomial a * Monomial b = Monomial $ unionWith (+) a b data Lex -- this uses a minor extension which is not necessary data GLex instance Ord (Monomial Lex) where Monomial m <= Monomial m' = toList m <= toList m' instance Ord (Monomial GLex) where Monomial m <= Monomial m' = (sum $ elems m, toList m) <= (sum $ elems m', toList m') You can add a trivial conversion function convertOrdering :: Monomial a -> Monomial b convertOrdering (Monomial x) = Monomial x From rendel at rbg.informatik.tu-darmstadt.de Tue Aug 7 11:03:30 2007 From: rendel at rbg.informatik.tu-darmstadt.de (Tillmann Rendel) Date: Tue Aug 7 10:55:00 2007 Subject: [Haskell-cafe] Type classes: Missing language feature? In-Reply-To: References: Message-ID: <46B889C2.2090703@rbg.informatik.tu-darmstadt.de> DavidA wrote: > Now, what I'd like to do is have Lex and Glex, and any further monomial > orderings I define later, automatically derive Show and Num instances from > Monomial (because it seems like boilerplate to have to define Show and Num > instances by hand). Something like the following (not valid Haskell): > > class OrdMonomial m where > fromRaw :: Monomial -> m > toRaw :: m -> Monomial > > instance OrdMonomial Lex where > fromRaw m = Lex m > toRaw (Lex m) = m > > instance OrdMonomial Glex where > fromRaw m = Glex m > toRaw (Glex m) = m > > derive OrdMonomial m => Show m where > show m = show (toRaw m) > > derive OrdMonomial m => Num m where > m * m' = fromRaw (toRaw m * toRaw m') Change "derive" to "instance" and enable some GHC extensions by passing -fglasgow-exts -fallow-overlapping-instances -fallow-undecidable-instances to it (or use a GHC_OPTIONS pragma at the top of your source file) to make your code work with GHC. To go a step further, using functional dependencies, you can write a small framework: -- the class of wrapper types class Wrapper w a | w -> a where wrap :: a -> w unwrap :: w -> a -- the class of types with "derived" show instances class Wrapper w => DeriveShow w -- actual "deriving" of show instances instance (Wrapper w a, Show a, DeriveShow w) => Show w where show = show . unwrap and use it for your situation: -- the inner type to be wrapped and it's instances newtype Monomial = Monomial (Map String Int) deriving (Eq) instance Show Monomial where show (Monomial a) = ... -- some wrappers around this inner type newtype Lex = Lex Monomial deriving (Eq) newtype Glex = Glex Monomial deriving (Eq) instance Wrapper Lex Monomial where wrap x = Lex x unwrap (Lex x) = x instance Wrapper Glex Monomial where wrap x = Glex x unwrap (Glex x) = x -- specialised instances for the wrappers instance Ord Lex where Lex (Monomial m) <= Lex (Monomial m') = ... instance Ord Glex where Glex (Monomial m) <= Glex (Monomial m') = ... -- "derived" instances for the wrappers instance DeriveShow Lex instance DeriveShow Glex But given newtype deriving, wich should work for you for everything except Show and Read, this may well be overkill. Tillmann From conal at conal.net Tue Aug 7 15:17:49 2007 From: conal at conal.net (Conal Elliott) Date: Tue Aug 7 15:09:51 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> Message-ID: On 8/5/07, Frank Buss wrote: > Nearly anything works without thinking too much about the types, but I > don't like the use of fromInteger in the average and main functions. Is it > possible that the integers are automaticly converted to floats? I recommend using Float or Double instead of Int for your point coordinates. You'll eliminate the need to convert to Float/Double. More importantly, your whole model will then be resolution independent, supporting continuous scaling, sub-pixel translation, rotation, etc. See http://conal.net/Pan for examples & papers. Cheers, - Conal -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070807/e6b450fa/attachment.htm From fb at frank-buss.de Tue Aug 7 16:22:00 2007 From: fb at frank-buss.de (Frank Buss) Date: Tue Aug 7 16:14:05 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> Message-ID: <042101c7d930$9cc98aa0$64c5a8c0@galilei> Hi Conal, I've tried some links, e.g. the pre-compiled components from http://conal.net/Pan/Releases/2000-12-06/ or the interactive presentation from http://conal.net/Pan/papers.htm , but file not found. Do you have the files? Would be easier than trying to setup Haskell and Visual C++ environment for compiling it (looks like the sources link works). BTW: There is Visual Studio Express, maybe you want to update your webpage, because Microsoft gives it away for free, if it can be used with Pan. How fast is your implementation? I've downloaded "werkkzeug" from http://www.theprodukkt.com/werkkzeug1#25 . The user interface is a bit unusual, but if you start the tutorial, it can display a texture example with about 50 composed functions and 256x256 pixels with about 300 fps. I've emailed the author and they didn't revealed much about the implementation, but said it was C with some inline assembler. I assume to make it fast, a good idea would be to cache some calculations, e.g. if you want a swirl effect, for all destination image cache all source positions, for the desired destination image size. Regards, Frank From jon at ffconsultancy.com Tue Aug 7 17:34:09 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue Aug 7 17:51:06 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: <042101c7d930$9cc98aa0$64c5a8c0@galilei> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> <042101c7d930$9cc98aa0$64c5a8c0@galilei> Message-ID: <200708072234.10027.jon@ffconsultancy.com> On Tuesday 07 August 2007 21:22:00 Frank Buss wrote: > I assume to make it fast, a good idea would be to cache some calculations... If you want to make it fast you should be using hardware acceleration. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/?e From mgross21 at verizon.net Tue Aug 7 18:22:59 2007 From: mgross21 at verizon.net (Murray Gross) Date: Tue Aug 7 17:58:54 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <837db430708070312i5a4a90dfpfd29b85672fc7e07@mail.gmail.com> References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> <20070807020901.GK8756@cse.unsw.EDU.AU> <837db430708061913m1fe8c073u9238fe7f10f36798@mail.gmail.com> <20070807021701.GN8756@cse.unsw.EDU.AU> <837db430708070227n4732bb08kf96c2aa2b1ae03e1@mail.gmail.com> <837db430708070312i5a4a90dfpfd29b85672fc7e07@mail.gmail.com> Message-ID: Yes, by 25x25 puzzles I mean sudoku puzzles with 25 cells on each side, with the smaller squares being 5x5 (i.e., we need to construct rows with the numbers 1-25, and the smaller squares must each contain all of the numbers 1-25). Murray Gross Brooklyn College On Tue, 7 Aug 2007, Hugh Perkins wrote: > On 8/7/07, Hugh Perkins wrote: >> >> Question: what do you mean by, for example 25x25? Do you mean grids with >> a total length of 25 on each side, eg: >> > > (because on my super-dooper 1.66GHz Celeron, generating 10 random 25x25 > grids such as the one above takes about 1.01 seconds; solving an actual > puzzle should be faster because the solution space is more tightly > constrained?) > From conal at conal.net Tue Aug 7 22:03:56 2007 From: conal at conal.net (Conal Elliott) Date: Tue Aug 7 21:55:57 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: <200708072234.10027.jon@ffconsultancy.com> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> <042101c7d930$9cc98aa0$64c5a8c0@galilei> <200708072234.10027.jon@ffconsultancy.com> Message-ID: I agree with Jon. And hardware acceleration is in tension with the generality of the extreme generality of formulating images as general (computable) functions on space (and hence arbitrary non-linear transformations, etc). *Unless*, you abandon the traditional acceleration of a fixed set of 2D (or 3D) primitives and transformations and instead compile into graphics processor code as in http://conal.net/Vertigo. BTW, I'd love to find one or more enthusiastic collaborators to help create and release open-source, cross-platform, and successors to Pan & Vertigo. Anyone interested? - Conal On 8/7/07, Jon Harrop wrote: > > On Tuesday 07 August 2007 21:22:00 Frank Buss wrote: > > I assume to make it fast, a good idea would be to cache some > calculations... > > If you want to make it fast you should be using hardware acceleration. > > -- > Dr Jon D Harrop, Flying Frog Consultancy Ltd. > OCaml for Scientists > http://www.ffconsultancy.com/products/ocaml_for_scientists/?e > _______________________________________________ > 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/haskell-cafe/attachments/20070807/deba28a4/attachment.htm From conal at conal.net Tue Aug 7 22:11:37 2007 From: conal at conal.net (Conal Elliott) Date: Tue Aug 7 22:03:37 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: <042101c7d930$9cc98aa0$64c5a8c0@galilei> References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> <042101c7d930$9cc98aa0$64c5a8c0@galilei> Message-ID: Hi Frank, Pan has been bit-rotten for a while now. Besides the unfortunate dependency on Visual C++, it used a now long-obsolete GUI library. That's one reason I started working on Pajama (http://conal.net/Pajama). There's no reason not to create modern, cross-platform successors to Pan/Pajama and Vertigo. Since I'm focusing on other projects (related to Eros -- http://conal.net/papers/Eros), I'm waiting for collaborators. Thanks for the VS Express tip. If I wanted to stick with VS, that'd be the way to go. I hadn't heard about werkkzeug. Looks pretty cool. Thanks. Regards, - Conal On 8/7/07, Frank Buss wrote: > > Hi Conal, > > I've tried some links, e.g. the pre-compiled components from > http://conal.net/Pan/Releases/2000-12-06/ or the interactive presentation > from http://conal.net/Pan/papers.htm , but file not found. Do you have the > files? Would be easier than trying to setup Haskell and Visual C++ > environment for compiling it (looks like the sources link works). BTW: > There > is Visual Studio Express, maybe you want to update your webpage, because > Microsoft gives it away for free, if it can be used with Pan. > > How fast is your implementation? I've downloaded "werkkzeug" from > http://www.theprodukkt.com/werkkzeug1#25 . The user interface is a bit > unusual, but if you start the tutorial, it can display a texture example > with about 50 composed functions and 256x256 pixels with about 300 fps. > I've > emailed the author and they didn't revealed much about the implementation, > but said it was C with some inline assembler. I assume to make it fast, a > good idea would be to cache some calculations, e.g. if you want a swirl > effect, for all destination image cache all source positions, for the > desired destination image size. > > Regards, > > Frank > > _______________________________________________ > 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/haskell-cafe/attachments/20070807/de15efb4/attachment.htm From hughperkins at gmail.com Wed Aug 8 00:27:54 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Wed Aug 8 00:19:55 2007 Subject: [Haskell-cafe] creating graphics the functional way In-Reply-To: References: <04f301c7d7b2$ae0210f0$64c5a8c0@galilei> <042101c7d930$9cc98aa0$64c5a8c0@galilei> <200708072234.10027.jon@ffconsultancy.com> Message-ID: <837db430708072127n84e91acw3ede983ff50b32c9@mail.gmail.com> On 8/8/07, Conal Elliott wrote: > > *Unless*, you abandon the traditional acceleration of a fixed set of 2D > (or 3D) primitives and transformations and instead compile into graphics > processor code as in http://conal.net/Vertigo . > Wow, cool :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070808/60f04d1b/attachment.htm From ketil at ii.uib.no Wed Aug 8 03:33:47 2007 From: ketil at ii.uib.no (Ketil Malde) Date: Wed Aug 8 03:25:38 2007 Subject: [Haskell-cafe] OS swapping and haskell data structures In-Reply-To: <46B01E14.2020109@alexjacobson.com> References: <46B01E14.2020109@alexjacobson.com> Message-ID: <1186558427.4442.48.camel@nmd9999> On Tue, 2007-07-31 at 22:45 -0700, Alex Jacobson wrote: > If you create a Data.Map or Data.Set larger than fits in physical > memory, will OS level swapping enable your app to behave reasonably or > will things just die catastrophically as you hit a memory limit? It will die (catastrophically or not is in the eye of the beholder, I guess) when you exhaust heap or swap limits (set with +RTS options), or the maximum available memory (physical+swap or ulimit). In my experience, performance quickly becomes unbearable (and also Linux tends to be less than responsive) when you exceed physical memory, so I generally always use +RTS -Mx, with x about 80% of physical RAM. In fact, I often use a C file to set these parameters directly, I think I ripped it (or the idea) from darcs. See e.g. http://malde.org/~ketil/rbr/src/hooks.c -k From apfelmus at quantentunnel.de Wed Aug 8 03:33:41 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Wed Aug 8 03:26:05 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: <1955583864.20070804083549@gmail.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> Message-ID: Bulat Ziganshin wrote: > apfelmus wrote: >> >> avoid the small layer of imperative code, of course. But the more you >> treat imperative code as somewhat pure, the greater the danger that the >> purely functional logic will be buried inside a mess of imperative code. >> In other words, the goal is exactly to make IO and STM uncommon, >> otherwise you loose the power the purely functional approach offers. > > it's point of view of theoretical purist. i consider Haskell as > language for real world apps and need to write imperative code appears > independently of our wishes. in paricular, it's required to write very > efficient code, to interact with existing imperative APIs, to make > programs which has explicit memory control (as opposite to lazy > evaluation with GC) No and yes. As I said, it is of course desirable to be able to describe genuinely imperative behavior elegantly in Haskell, like explicit memory control or concurrently accessing a bank account. However, most "genuinely imperative" things are often just a building block for a higher level functional model. The ByteString library is a good example: the interface is purely functional, the internals are explicit memory control. It's a bad idea to let the internal memory control leak out and pollute an otherwise purely functional program with IO-types. Also, many "genuinely concurrent" things just aren't. An example are UNIX pipes like say cat Main.hs | grep "Warm, fuzzy thing" The OS creates a processes for "cat" and "grep" running concurrently and "cat" passes a stream of characters to "grep". By blocking on the reader and the write side, "grep" reads what "cat" writes in real-time. Well, but that's just good old lazy evaluation! Regards, apfelmus From kolar at fit.vutbr.cz Wed Aug 8 04:04:32 2007 From: kolar at fit.vutbr.cz (Dusan Kolar) Date: Wed Aug 8 03:55:57 2007 Subject: [Haskell-cafe] Bug in GHCi? Message-ID: <46B97910.9030205@fit.vutbr.cz> Hello all, Maybe this is a wrong place to report, but I have repeatedly performed "funny" calculation in GHCi with strange time report. The version of GHCi is: ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.6, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base ... linking ... done. Prelude> My machine: OS WinXP Pro SP2, Intel Core 2, 2GB RAM. How to reproduce error: :set +s :set -02 :cd :l Primes take 10000 primes1 take 10000 primes2 Yes, that is not a typo. The report of time elapsed is: minus three hundred and twenty six seconds. I'll try the newest version of the GHCi, but it is strange anyway and maybe it should be investigated... Thanks, Dusan -------------- next part -------------- module Primes ( primes1 ,primes2 ,primes3 ,primes2' ,primes3' ) where candidates = map (\x -> (True,x)) [2..] candidates' = [2..] skipmap f toSkip list = domap toSkip list where domap n (x:xs) | n > 1 = x : domap (n-1) xs | True = f x : domap toSkip xs domap _ [] = [] primes1 = sieve candidates where sieve (pp@(isp,p):xs) | isp = p : (sieve $ skipmap (\(_,v) -> (False,v)) p xs) | True = sieve xs primes1' = sieve candidates' where sieve (p:xs) | p > 0 = p : (sieve $ skipmap (\n -> if n>0 then (-n) else n) p xs) | True = sieve xs sieve (p:xs) = p : sieve [y | y <- xs, y `mod` p /= 0] sieve' (p:xs) = p : sieve [y | y <- xs, y `mod` p > 0] primes2 = sieve [2..] primes3 = 2 : sieve [3,5..] primes2' = sieve' [2..] primes3' = 2 : sieve' [3,5..] From pocm at soton.ac.uk Wed Aug 8 04:07:26 2007 From: pocm at soton.ac.uk (Paulo J. Matos) Date: Wed Aug 8 03:59:24 2007 Subject: [Haskell-cafe] Using haskell with emacs In-Reply-To: <46B79264.6050801@jellybean.co.uk> References: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> <46B79264.6050801@jellybean.co.uk> Message-ID: <11b141710708080107i56b589axef006fa58a6ad51a@mail.gmail.com> Thank you all for your references and tips, I'll be using them. :-) On 06/08/2007, Jules Bean wrote: > Thomas Schilling wrote: > > > > On 6 aug 2007, at 22.11, Paulo J. Matos wrote: > > If you're used to Slime+Paredit, then there isn't something really > > comparable, but you get some basic interactive programming with the > > standard key-bindings: > > > (But paredit does work in haskell-mode, and I find it useful...) > > Jules > > > -- Paulo Jorge Matos - pocm at soton.ac.uk http://www.personal.soton.ac.uk/pocm PhD Student @ ECS University of Southampton, UK From bulat.ziganshin at gmail.com Wed Aug 8 06:05:54 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Wed Aug 8 06:36:13 2007 Subject: [Haskell-cafe] Re: monad subexpressions In-Reply-To: References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> Message-ID: <1104462744.20070808140554@gmail.com> Hello apfelmus, Wednesday, August 8, 2007, 11:33:41 AM, you wrote: >> it's point of view of theoretical purist. i consider Haskell as >> language for real world apps and need to write imperative code appears >> independently of our wishes. in paricular, it's required to write very >> efficient code, to interact with existing imperative APIs, to make >> programs which has explicit memory control (as opposite to lazy >> evaluation with GC) > No and yes. As I said, it is of course desirable to be able to describe > genuinely imperative behavior elegantly in Haskell, like explicit memory > control or concurrently accessing a bank account. > However, most "genuinely imperative" things are often just a building > block for a higher level functional model. you say about some imaginary ideal world. i say about my own experience. i write an archiver which includes a lot of imperative code. another my project is I/O library which is imperative too. in both cases i want to make my work easier -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From Christian.Maeder at dfki.de Wed Aug 8 08:40:50 2007 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Wed Aug 8 08:35:38 2007 Subject: [Haskell-cafe] Re: default for quotRem in terms of divMod? In-Reply-To: <46B8DF69.70103@charter.net> References: <46B8DF69.70103@charter.net> Message-ID: <46B9B9D2.6080709@dfki.de> Isaac Dupree wrote: > In class Integral, divMod has a default in terms of quotRem. > (quot,rem,div,mod all have defaults as the both-function they're part > of.) I'm sure divMod is more natural than quotRem to implement for some > types... so why doesn't quotRem have a default in terms of divMod? it > has no default! Then the "minimal to implement" will change from > (toInteger and quotRem) to (toInteger and (quotRem or divMod)). > > Isaac while I don't care if quotRem or divMod should be implemented. I oppose to give both default implementations in terms of the other. Already for the class Eq either == or /= must be defined, with the unpleasant effect that an empty instance like: instance Eq T leads to a loop (when == or /= is called on elements of type T). The empty instance does not even raise a warning about unimplemented methods (since the default definition is used). I'd rather prefer to remove /= as method of Eq. Cheers Christian From a.biurvOir4 at asuhan.com Wed Aug 8 09:32:58 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Wed Aug 8 09:24:55 2007 Subject: [Haskell-cafe] FW: RE Monad Description For Imperative Programmer In-Reply-To: <039801c7d489$cd74a410$933b8351@cr3lt> References: <00d401c7d447$fe1c1bd0$fa545370$@be> <46B0E6A0.3010707@imageworks.com> <039801c7d489$cd74a410$933b8351@cr3lt> Message-ID: <12053227.post@talk.nabble.com> Claus Reinke wrote: > > there is usually a way to interpret monadic structures built in > this way (a 'run' operation of some kind). > The "run" operation of type (m a -> a) is the (comonadic) coreturn. Many monads are almost comonads too, for a meaning of "almost" to be made precise. Claus Reinke wrote: > > - i/o: primitive monadic things are basic i/o operations, > the 'run' operation is outside the language, applied to > 'Main.main', and interprets (abstract) IO monad structures > sequentially, starting with the leftmost innermost i/o > operation in the structure and applying the second > argument of (>>=) to the result of executing the first. > "Run" for IO monad is obviously unsafePerformIO :: IO a -> a. Claus Reinke wrote: > > - []: primitive monadic things are lists, the 'run' operation > is the identity, ie, the lists are directly exposed as data > structures, return creates a singleton list, (>>=) applies > its second argument to each element of its first argument > and concatenates the results (concatMap). > "Run" for [] is almost head :: [a] -> a. For the type of infinite streams, the research community's comonad de rigeur, coreturn _is_ h(ea)d. Claus Reinke wrote: > > - State: primitive monadic things are operations on a state > type, returning a result and a state; return returns its > parameter, passing its input state unchanged, (>>=) applies > its first parameter to the input state, applies its second > parameter to the result value and result state of the first. > 'run' is runState and applies a (possibly) complex monadic > thing to an input state, returning a result and a (modified) > state. > The State monad is almost (there's that word again!) like the Context comonad. And the Context comonad is a comonadification of the suboptimally named Reader monad, a comonadification that wants to be made precise. In fact, there's another comonad that solves the analogical equation: comonad x is to monad State as comonad Context is to monad Reader. Any takers on calling x the Costate comonad and Reader the Ntext monad? -- View this message in context: http://www.nabble.com/FW%3A-RE-Monad-Description-For-Imperative-Programmer-tf4200420.html#a12053227 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From ajb at spamcop.net Wed Aug 8 10:16:45 2007 From: ajb at spamcop.net (ajb@spamcop.net) Date: Wed Aug 8 10:08:43 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> Message-ID: <20070808101645.03oogs0ck8o804g4@webmail.spamcop.net> G'day all. Quoting Vimal : > Well, Dancing Links (DLX) is just a data structure + few techniques > to help with the backtrack, after modeling Sudoku as a contraint > satisfaction problem. DLX is one realisation of an algorithm which works on boolean matrices. It's a pointer-based backtracking algorithm with explicit "undo", so that's arguably not the most appropriate realisation in a declarative language, where undo should be close to free. Just for fun, I tried implementing the exact cover algorithm using a more Haskell-esque data realisation. The bit matrix is represented as a pair of maps: one from column to list of rows, and one from rows to list of columns. The first map (column to list of rows) is implemented as a priority search queue keyed on the number of "ones" in each column. This allows fast selection of the smallest column. http://andrew.bromage.org/darcs/sudoku/ I don't claim that it's fast. I didn't spend a lot of time on it. Cheers, Andrew Bromage From rodrigo.bonifacio at uol.com.br Wed Aug 8 10:56:48 2007 From: rodrigo.bonifacio at uol.com.br (rodrigo.bonifacio) Date: Wed Aug 8 10:48:50 2007 Subject: [Haskell-cafe] mutually recursive types Message-ID: Hi, I am learning the haskell programming language and had tried to define the following types: type Scenario = (String, String, [Step]) type Step = (String, Scenario, String, String, String) Notice that Scenario depends on a list of steps and Step has a dependence with scenario. I know that this is a kind of "bad smell".... in Haskell, are there any pattern or language idiom to deal with cyclical dependences? Regards, Rodrigo. From jon.fairbairn at cl.cam.ac.uk Wed Aug 8 10:58:54 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Wed Aug 8 10:51:06 2007 Subject: [Haskell-cafe] Re: mutually recursive types References: Message-ID: "rodrigo.bonifacio" writes: > Hi, I am learning the haskell programming language and had > tried to define the following types: > > type Scenario = (String, String, [Step]) type Step = > (String, Scenario, String, String, String) data Scenario = Scenario String String [Step] data Step = Step String Scenario String String String -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From brianh at metamilk.com Wed Aug 8 11:00:55 2007 From: brianh at metamilk.com (Brian Hulley) Date: Wed Aug 8 10:52:42 2007 Subject: [Haskell-cafe] Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> Message-ID: <46B9DAA7.4070006@metamilk.com> apfelmus wrote: > However, most "genuinely imperative" things are often just a building > block for a higher level functional model. The ByteString library is a > good example: the interface is purely functional, the internals are > explicit memory control. It's a bad idea to let the internal memory > control leak out and pollute an otherwise purely functional program with > IO-types. > Hi Apfelmus, This is a really interesting discussion that touches on issues I'm currently working with (I'm designing a strict version of Haskell to explore various ideas about modules, namespace management, and how to get really efficient machine code but without losing the convenience of accurate garbage collection etc, but I'm having difficulties deciding between the monadic path and the "impure" path), so I've forked this new thread. Regarding the quote above, if the API must hide explicit memory control from the user the only way I can see of doing this would be to use (unsafePerformIO), which really is unsafe since Haskell relies on the fact that mutable operations can't escape from the IO monad in order to get away with not having to impose a value restriction as in ML. If you don't use (unsafePerformIO), then the slightest need for mutable data structures pollutes the entire interface. For example in the excellent paper you quoted N. Ramsey and J. Dias. An Applicative Control-Flow Graph Based on Huet's Zipper http://www.eecs.harvard.edu/~nr/pubs/zipcfg-abstract.html the authors are pleased to have found an "Applicative" solution, and indeed their solution has many useful and instructive aspects. However on page 111, hidden away in the definition of their API function to create a label, is a call to (ref 0) !!!! ;-) The equivalent implementation in Haskell would completely destroy all hope of using this in a pure context and force all use of the API into the IO monad. Haskell and ML seem to stand at opposite poles. Haskell is designed so that any attempt at abstracting mutable local state will infect the entire program (modulo use of a highly dangerous function whose semantics is entirely unclear, depending on the vagaries of evaluation strategy of the particular compiler) whereas people have been struggling in the ML community for at least 15 years to try and find a way to hide the fact that mutable storage is being used (cf attempts to find a proper solution to the unsoundness introduced by polymorphism and ref without having to use imperative/weak type variables etc). Meanwhile, C++, C#, and Java programmers get a type system (thinking only about static methods using generics/templates) that seems to me no less powerful than that of the prenex polymorphism of ML, yet without any of the unsoundness problems, and therefore without the need of a value restriction (afaiu this is because their template/generic definitions stand in for an infinite family of monomorphic bindings instead of ML which tries unsuccessfully to make one piece of memory represent each element of an infinite family of values simultaneously). Not only this, but there seems to me to be many problems for which it is natural to think in terms of objects with identity and mutable state. I can readily discard the concepts of deep inheritance hierarchies and open recursion but this still leaves the problem of identity and localised mutability. For example consider a simple GUI with 2 edit widgets, a splitter, and a single buffer that contains the text being edited. The idea is that you should be able to use either edit widget to interact with the same buffer eg to edit at different locations in the buffer. A simple imperative solution might be something like: main = do buffer <- createBuffer edit1 <- createEdit buffer edit2 <- createEdit buffer splitter <- createSplitter (wrapWidget edit1) (wrapWidget edit2) runMessageLoopWith splitter Here it's really clear what's happening, and different objects in the program correspond exactly to how I think about what I'm trying to do ie I want to create individual objects with identity and then plug them together. I don't want to have to bother about passing state around, or having to define a new data type every time I want a different configuration of widgets. Thus the ability to abstract mutable state gives to my mind by far the best solution. In contrast, all the pure functional GUIs that I've seen are just wrappers around someone else's imperative code, and moreover, they exchange the simplicity of the object oriented imperative API for a veritable mindstorm of unbelievably heavy, clunky, slow, inefficient, inextensible, hard to understand encodings that seem to me to have the effect of turning a high level language into some kind of circuit board (I'm thinking of arrows etc). Indeed everyone seems to be using either WxWidgets or Gtk2Hs which kind of proves my point that in this domain at least imperative solutions are generally simpler than functional ones... > Also, many "genuinely concurrent" things just aren't. An example are > UNIX pipes like say > > cat Main.hs | grep "Warm, fuzzy thing" > > The OS creates a processes for "cat" and "grep" running concurrently and > "cat" passes a stream of characters to "grep". By blocking on the reader > and the write side, "grep" reads what "cat" writes in real-time. Well, > but that's just good old lazy evaluation! True, but the above program is just a trivial transformation from input to output ie just using the computer as a calculator. For interactive programs you need to be able to implement a different kind of laziness, because the challenge is not just how to compute some output from some input, but how to maintain a mapping between input and output that respects some invariant in the presence of dynamic deltas to the input as the user enters information into the program, ensuring that the amount of computation done between each time the display is rendered is proportional to the delta rather than the entire input. So in summary for me the good things about Haskell are nothing to do with functional purity or laziness but are instead to do with the fact that it's basically the only statically typed modern language (apart from OCaml, MLton, and MLKit) that has a free compiler to unburdened native code (apart from the LGPL gnuMP hard wired into the runtime in ghc which is one reason I'm writing my own compiler so I can actually put my own programs on the web to sell...) and accurate garbage collection (otherwise I'd be happy to use C++). (The great type system, good syntax, well designed foreign function interface, ability to control use of APIs with great precision by using phantom type permissions in the monad(s), and of course millions of interesting research papers and discussions on this list are an extra bonus.) Summary of summary: Haskell is a good language for imperative programming, and the pure functional subset has failed to yield a practical GUI even after more than a decade of research. I've wasted at least a whole year of sleepless nights trying to work out how to represent an efficient GUI without using mutable data, and the feeling that there should be a pure solution made me abandon a perfectly workable imperative GUI that I started 18 months ago, that if I'd written it in any other language without this pure/impure conundrum, would have made me very happy with it. Best regards, Brian. From a.biurvOir4 at asuhan.com Wed Aug 8 11:01:13 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Wed Aug 8 10:53:10 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <46B0B732.1010905@ropine.com> References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> <46B0B732.1010905@ropine.com> Message-ID: <12055086.post@talk.nabble.com> Seth Gordon wrote: > > Functors are a generalization from lists to "things that can be mapped > over" in general, and then monads are a generalization of functors. > Way to go! That way lies true co/monadic enlightenment. Put another way, monads are no more about (only) IO/sequencing than fmap is about (only) lists. To learn about monadic imperative programming there are excellent places for doing so, but to learn about co/monads qua co/monads well, too bad. So here's my co/monad tutorial, or at least the barest outline of one. I guess that almost everyone can "get" fmap :: (a -> b) -> (m a -> m b) if only they got a good workout at it. So let's do lists, then trees, then your favorite exponential types, say parsers. Howsoever it's done, be sure to get a good grip on fmap. Next introduce flip (>>=) :: (a -> m b) -> (m a -> m b) as a left-sided fmap. Thinking what it means to lift just one side "nicely" should motivate the return function and monadic laws. Here "nicely" is in the sense that fmap lifts "nicely." Of course the classy way of figuring out one-sided fmap's is to contemplate both flip (>>=) and (comonadic) coextension :: (m a -> b) -> (m a -> m b) at the same time. This is my preferred approach to a co/monad tutorial. For sure, You Could Have Invented Co/Monads Too. Seth Gordon wrote: > > Haskell solves the "how can I do I/O in a pure functional language" > problem by *turning the world inside-out*. Instead of taking data from > the mutable outside world, using functions to manipulate it, and > depositing results back into that world, you put your functions into the > IO monad. > But (the illusion of) taking data out from the real world, manipulating it, and then putting it back is exactly what the monadic-do syntax sugar accomplishes: do x <- inputFromRealWorld let y = manipulateIt x return y You could use (fmap manipulateIt) to "put" it into the IO monad as you describe, but monadic-do is by far the more common approach. -- View this message in context: http://www.nabble.com/Monad-Description-For-Imperative-Programmer-tf4198417.html#a12055086 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From bf3 at telenet.be Wed Aug 8 11:16:20 2007 From: bf3 at telenet.be (peterv) Date: Wed Aug 8 11:08:27 2007 Subject: [Haskell-cafe] Newbie question (again!) about phantom types Message-ID: <009201c7d9cf$13810a30$3a831e90$@be> I=92m having difficulty to understand what phantom types are good for. = Is this just for improving runtime performance?=20 I read the wiki, and it says "this is useful if you want to increase the type-safety of your code", but the code below does not give a compiler = error for the function test1, I get a runtime error, just like test2. Thanks, Peter -- CODE -- -- With phantom types data T1 a =3D TI1 Int | TS1 String deriving Show foo1 :: T1 String -> T1 String -> T1 String foo1 (TS1 x) (TS1 y) =3D TS1 (x++y) test1 =3D foo1 (TI1 1) (TI1 2) -- Shouldn't this give a compiler error = instead of a runtime error?=20 -- Without phantom types data T2 =3D TI2 Int | TS2 String deriving Show foo2 :: T2 -> T2 -> T2 foo2 (TS2 x) (TS2 y) =3D TS2 (x++y) test2 =3D foo2 (TI2 1) (TI2 2) No virus found in this outgoing message. Checked by AVG Free Edition.=20 Version: 7.5.476 / Virus Database: 269.11.8/941 - Release Date: = 07/08/2007 16:06 =20 From rendel at rbg.informatik.tu-darmstadt.de Wed Aug 8 11:17:31 2007 From: rendel at rbg.informatik.tu-darmstadt.de (Tillmann Rendel) Date: Wed Aug 8 11:08:52 2007 Subject: [Haskell-cafe] mutually recursive types In-Reply-To: References: Message-ID: <46B9DE8B.2020803@rbg.informatik.tu-darmstadt.de> Rodrigo wrote: > type Scenario = (String, String, [Step]) > type Step = (String, Scenario, String, String, String) Recursive types are not supported by type-declarations. use data declarations instead: data Scenario = Scenario String String [Step] data Step = Step String Scenario String String String As a general rule, data declaration are more approbiate then type declarations with a tuple on the right-hand-side. a type declarations introduces a type synonym, that is, a new name for an existing type. Data declarations introduce a new type. most of the time, you want new types, not more names for the same types. different names for the same thing lead to confusion, but different things for different usages lead to static type safety. (But this is only a general rule, and sometimes you want exactly the behaviour of type synonyms, of course) Tillmann From byorgey at gmail.com Wed Aug 8 11:30:20 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Wed Aug 8 11:22:18 2007 Subject: [Haskell-cafe] mutually recursive types In-Reply-To: References: Message-ID: <22fcbd520708080830y1cc6c7a9j8fad1ea04207d5b6@mail.gmail.com> > Notice that Scenario depends on a list of steps and Step has a dependence > with scenario. I know that this is a kind of "bad smell".... in Haskell, are > there any pattern or language idiom to deal with cyclical dependences? Just a little something to add, this is not a "bad smell" at all... in fact, recursive (including mutually recursive) data types are the bread and butter of Haskell (and functional languages in general). For example: data BinTree a = Empty | Branch a (BinTree a) (BinTree a) This says that a binary tree containing 'a's is either Empty, or a Branch consisting of an 'a' and two binary trees. This isn't stinky, it's quite elegant. Your Scenario and Step data types look just peachy from an idiomatic point of view; the solution (as others have pointed out) is to use data declarations rather than type synonyms. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070808/bfb8b3fa/attachment.htm From haskell-cafe at martinpercossi.com Wed Aug 8 11:30:52 2007 From: haskell-cafe at martinpercossi.com (Martin Percossi) Date: Wed Aug 8 11:22:51 2007 Subject: [Haskell-cafe] Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46B9DAA7.4070006@metamilk.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> Message-ID: <46B9E1AC.4040302@martinpercossi.com> Brian Hulley wrote: > hidden away in the definition of their API function to create a label, > is a call to (ref 0) !!!! ;-) The equivalent implementation in Haskell > would completely destroy all hope of using this in a pure context and > force all use of the API into the IO monad. Really? I would have thought this is a job for the ST monad, in which case the API can be wrapped up in a runST or similar; no need for leaking IO monads. Or am I missing something? Regards, Martin My music: http://www.youtube.com/user/thetonegrove (please visit!) From rendel at rbg.informatik.tu-darmstadt.de Wed Aug 8 11:54:13 2007 From: rendel at rbg.informatik.tu-darmstadt.de (Tillmann Rendel) Date: Wed Aug 8 11:45:57 2007 Subject: [Haskell-cafe] Newbie question (again!) about phantom types In-Reply-To: <009201c7d9cf$13810a30$3a831e90$@be> References: <009201c7d9cf$13810a30$3a831e90$@be> Message-ID: <46B9E725.3010406@rbg.informatik.tu-darmstadt.de> peterv wrote: > I’m having difficulty to understand what phantom types are good for. > > I read the wiki, and it says "this is useful if you want to increase the > type-safety of your code", but the code below does not give a compiler error > for the function test1, I get a runtime error, just like test2. > -- With phantom types > data T1 a = TI1 Int | TS1 String deriving Show > > foo1 :: T1 String -> T1 String -> T1 String > foo1 (TS1 x) (TS1 y) = TS1 (x++y) > > test1 = foo1 (TI1 1) (TI1 2) -- Shouldn't this give a compiler error instead > -- of a runtime error? You have to manually instantiate the phantom type variable. In your code, the type of TI1 1 is just T1 a for an unrestricted type variable a. This unifies fine with the expected argument type of foo1, wich is T1 String, by setting a = String. Consider this variant of your code: -- the type of things wich can hold numbers or text -- what exactly they hold is encoded dynamically by the -- constructor used and statically by the phantom type data Container a = NumberContainer Int | TextContainer String data Number = Number data Text = Text -- approbiate smart constructors. only use these for creation -- of containers, never use the real constructors. number :: Int -> Container Number number x = NumberContainer x text :: String -> Container Text text x = TextContainer x -- a function wich works only on containers holding text foo :: Container Text -> Container Text -> Container Text foo (TextContainer a) (TextContainer b) = text (a ++ b) -- testing test1 = text "hello " `foo` text "world" -- works test2 = number 13 `foo` number 19 -- static error This works fine when you can decide statically how to instantiate the phantom type variable (by using the approbiate smart constructor). If you can't (because you read data from same external source, for example), you can restrict the position of dynamic failures to a well-defined point in program execution by defining asText :: Container a -> Maybe (Container Text) asText (TextContainer x) = Just $ text x asText _ = Nothing asNumber :: Container a -> Maybe (Container Number) asNumber (NumberContainer x) = Just $ number x asNumber _ = Nothing Using these functions, you can lift a dynamic typecheck (is it the right constructor?) to a static typecheck (has it the right phantom type?). So you can for example check user input once for having the correct form and then enter the statically typesafe part of your program, where you don't have to worry about people entering numbers instead of text, because you statically know that at this point in program execution, the dynamic typecheck already suceeded. Tillmann From ariep at xs4all.nl Wed Aug 8 11:59:19 2007 From: ariep at xs4all.nl (Arie Peterson) Date: Wed Aug 8 11:51:16 2007 Subject: [Haskell-cafe] Newbie question (again!) about phantom types In-Reply-To: <009201c7d9cf$13810a30$3a831e90$@be> References: <009201c7d9cf$13810a30$3a831e90$@be> Message-ID: <17481.213.84.177.94.1186588759.squirrel@webmail.xs4all.nl> > I?m having difficulty to understand what phantom types are good for. Is > this just for improving runtime performance? No. As the wiki says, you can use them to add static guarantees. > I read the wiki, and it says "this is useful if you want to increase the > type-safety of your code", but the code below does not give a compiler > error > for the function test1, I get a runtime error, just like test2. It seems you're mixing up GADT's and phantom types. > -- CODE -- > -- With phantom types > data T1 a = TI1 Int | TS1 String deriving Show Here, the 'a' is an extra type parameter, which has no manifestation on the value level. Note the type of the constructors: TI1 :: Int -> T1 a TS1 :: String -> T1 a In particular, the 'a' is not related to the 'Int' or 'String' arguments. > foo1 :: T1 String -> T1 String -> T1 String > foo1 (TS1 x) (TS1 y) = TS1 (x++y) > > test1 = foo1 (TI1 1) (TI1 2) -- Shouldn't this give a compiler error > instead > of a runtime error? 'TI1 1' has type 'T1 a', so this unifies with 'T1 String' (the type of the argument of 'foo1'. The type parameter 'a' can still be useful, but you have to use an explicit type signature to constrain the type 'a': ti1 :: Int -> T1 Int ti1 x = TI1 x Now, 'ti1' will create values with the restricted type 'T1 Int', that you can't use as arguments for your 'foo1'. GADTs are perhaps more useful for what you seem to want. Try something like this: data T1 :: * -> * where -- T1 has one type parameter TI1 :: Int -> T1 Int TS1 :: String -> T1 String Now, the type systems guarantees that all values of the form 'TI1 x' have type 'T1 Int'. Greetings, Arie From d at vidplace.com Wed Aug 8 11:59:41 2007 From: d at vidplace.com (David F. Place) Date: Wed Aug 8 11:51:42 2007 Subject: [Haskell-cafe] Newbie question (again!) about phantom types In-Reply-To: <009201c7d9cf$13810a30$3a831e90$@be> References: <009201c7d9cf$13810a30$3a831e90$@be> Message-ID: <64034DD9-8518-4F34-B7C1-A1525D8BB59D@vidplace.com> On Aug 8, 2007, at 11:16 AM, peterv wrote: > I?m having difficulty to understand what phantom types are good > for. Is this > just for improving runtime performance? > > I found phantom types to be useful in the implementation of bit-wise set operations. You can find the code Edison: http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ EdisonCore-1.2.1 in the Data.Edison.Coll.EnumSet module. David F. Place mailto:d@vidplace.com From monnier at iro.umontreal.ca Wed Aug 8 12:11:36 2007 From: monnier at iro.umontreal.ca (Stefan Monnier) Date: Wed Aug 8 12:03:59 2007 Subject: [Haskell-cafe] Re: Using haskell with emacs References: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> Message-ID: >> C-c C-b ... when pressed for the first time this will start an >> interpreter (ghci or hugs most of the time), when pressed with a >> running interpreter it'll switch to that buffer. >> >> C-c C-l ... Load the current file into the editor. There is no >> function-wise compilation. More generally, in Emacs "C-h m" will give you a list of keybindings for the current major mode. Also many major modes offer a menu in the menu-bar where the main special features are advertized. > Don't forget C-c C-r to reload the file in the buffer. I've removed it from the next release of haskell-mode, so if you need it, please explain why. Stefan From wagner.andrew at gmail.com Wed Aug 8 12:21:00 2007 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Wed Aug 8 12:13:02 2007 Subject: [Haskell-cafe] Re: Using haskell with emacs In-Reply-To: References: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> Message-ID: > > I've removed it from the next release of haskell-mode, so if you need it, > please explain why. > So C-c C-l is the preferred method for re-loading? I don't know enough about the details to know if :l and :r do exactly the same things in ghci. From hughperkins at gmail.com Wed Aug 8 12:48:11 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Wed Aug 8 12:40:10 2007 Subject: [Haskell-cafe] Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46B9DAA7.4070006@metamilk.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> Message-ID: <837db430708080948k52554501wdae3963fc46defe6@mail.gmail.com> On 8/8/07, Brian Hulley wrote: > > In contrast, all the pure functional GUIs that I've seen are just > wrappers around someone else's imperative code, and moreover, they > exchange the simplicity of the object oriented imperative API for a > veritable mindstorm of unbelievably heavy, clunky, slow, inefficient, > inextensible, hard to understand encodings that seem to me to have the > effect of turning a high level language into some kind of circuit board > (I'm thinking of arrows etc). > > In defense of Haskell (wow!), note that imperative languages are not without problems in GUIs. In a multithreaded environment, typically only one thread is allowed to manage the GUI, and then you typically need to set up some sort of message-passing system to communicate between this thread and the others AFAIK? This is a total PITA, so if someone has a solution for this that would rock :-) Question: to what extent do the Haskell wrappers around gtk and wxWidgets suffer from this problem? I mean, I havent tried them, so it's a genuine question. (Note: off the top of my head, in an imperative language, I guess one could use some sort of generator to take an interface and generate the message classes, and marshalling classes automatically) (Disclaimer: I havent really searched very hard for ways to handle threading in GUIs in imperative languages, since mostly I either use web pages as the visual interface, which avoids around the problem, or use a single thread, which also avoids the problem) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/d8beaabb/attachment.htm From monnier at iro.umontreal.ca Wed Aug 8 12:57:51 2007 From: monnier at iro.umontreal.ca (Stefan Monnier) Date: Wed Aug 8 12:50:22 2007 Subject: [Haskell-cafe] Re: Using haskell with emacs References: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> Message-ID: >> I've removed it from the next release of haskell-mode, so if you need it, >> please explain why. > So C-c C-l is the preferred method for re-loading? Yes. > I don't know enough about the details to know if :l and :r do exactly the > same things in ghci. I don't either. But experimentation suggests that the only difference is that :r doesn't need an argument (which in the case of haskell-mode doesn't make any difference since the arg is provided by haskell-mode anyway). Stefan From coreyoconnor at gmail.com Wed Aug 8 12:59:12 2007 From: coreyoconnor at gmail.com (Corey O'Connor) Date: Wed Aug 8 12:51:09 2007 Subject: [Haskell-cafe] Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46B9DAA7.4070006@metamilk.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> Message-ID: On 8/8/07, Brian Hulley wrote: > Regarding the quote above, if the API must hide explicit memory control > from the user the only way I can see of doing this would be to use > (unsafePerformIO), which really is unsafe since Haskell relies on the > fact that mutable operations can't escape from the IO monad in order to > get away with not having to impose a value restriction as in ML. My theory is weak. Can somebody point me the way to educate myself about the "value restriction" in ML? Thanks! -Corey -- -Corey O'Connor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070808/30c9d489/attachment.htm From brianh at metamilk.com Wed Aug 8 13:39:10 2007 From: brianh at metamilk.com (Brian Hulley) Date: Wed Aug 8 13:30:56 2007 Subject: [Haskell-cafe] Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46B9E1AC.4040302@martinpercossi.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> <46B9E1AC.4040302@martinpercossi.com> Message-ID: <46B9FFBE.6000003@metamilk.com> Martin Percossi wrote: > Brian Hulley wrote: > >> hidden away in the definition of their API function to create a >> label, is a call to (ref 0) !!!! ;-) The equivalent implementation in >> Haskell would completely destroy all hope of using this in a pure >> context and force all use of the API into the IO monad. > > Really? I would have thought this is a job for the ST monad, in which > case the API can be wrapped up in a runST or similar; no need for > leaking IO monads. > > Or am I missing something? Well I agree you're right on this particular use of a Ref, since their program is only dealing with a mapping from input to output so once they're finished using the data structure there is no longer any need for the ref and so the result can be returned to the rest of the program. However there are 2 problems with this approach in general afaics: 1) All code that uses this data structure ie that participates in the implementation of the transformations by using the API functions will have to be in a monad (ST or IO, it really doesn't matter in terms of all the perceived burdensomeness of do notation relative to normal applicative code). 2) The example doesn't transfer to an interactive situation, where we would need to keep the data structure around and use it forever - because we would be forever trapped inside the ST monad otherwise we'd lose that particular STRef which we were hoping to use to efficiently update the output in the face of a delta in the input. Corey - I found this page helpful to get an understanding of the value restriction in ML: http://www.smlnj.org/doc/Conversion/types.html The restriction was proposed by Andrew Wright in 1995: "Simple Imperative Polymorphism" by Wright http://citeseer.ist.psu.edu/wright95simple.html Some other related papers are: "The Type and effect discipline" by Talpin and Jouvelot 1992 "Standard ML-NJ weak polymorphism and imperative constructs" by Hoang, Mitchell, and Viswanathan "Weak polymorphism can be sound" by Greiner 1993 and more recently (2003) "Relaxing the value restriction" by Garrigue http://citeseer.ist.psu.edu/garrigue03relaxing.html (Note that even now there is still no real solution to it.) Best regards, Brian. From sethg at ropine.com Wed Aug 8 14:02:44 2007 From: sethg at ropine.com (Seth Gordon) Date: Wed Aug 8 13:54:47 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <12055086.post@talk.nabble.com> References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> <46B0B732.1010905@ropine.com> <12055086.post@talk.nabble.com> Message-ID: <46BA0544.3050500@ropine.com> Kim-Ee Yeoh wrote: > > Seth Gordon wrote: >> Functors are a generalization from lists to "things that can be mapped >> over" in general, and then monads are a generalization of functors. >> > > Way to go! That way lies true co/monadic enlightenment. I feel like I still don't understand comonads. Maybe I just need a Zen comaster to hit me with a costick and then I'll become coenlightened. >> Haskell solves the "how can I do I/O in a pure functional language" >> problem by *turning the world inside-out*. Instead of taking data from >> the mutable outside world, using functions to manipulate it, and >> depositing results back into that world, you put your functions into the >> IO monad. >> > > But (the illusion of) taking data out from the real world, manipulating it, > and then putting it back is exactly what the monadic-do syntax sugar > accomplishes: The type system turns the world inside-out and then the do-notation provides a right-side-in syntax to code functions in the inside-out world. From stefanor at cox.net Wed Aug 8 14:05:23 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 8 13:57:20 2007 Subject: [Haskell-cafe] Re: Using haskell with emacs In-Reply-To: References: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> Message-ID: <20070808180523.GA3140@localhost.localdomain> On Wed, Aug 08, 2007 at 12:57:51PM -0400, Stefan Monnier wrote: > >> I've removed it from the next release of haskell-mode, so if you need it, > >> please explain why. > > > So C-c C-l is the preferred method for re-loading? > > Yes. > > > I don't know enough about the details to know if :l and :r do exactly the > > same things in ghci. > > I don't either. But experimentation suggests that the only > difference is that :r doesn't need an argument (which in the case of > haskell-mode doesn't make any difference since the arg is provided by > haskell-mode anyway). :r is also *much* faster in general; :l reloads all modules from scratch, while :r only reloads the modules that have changed. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070808/ea511600/attachment.bin From brianh at metamilk.com Wed Aug 8 14:14:34 2007 From: brianh at metamilk.com (Brian Hulley) Date: Wed Aug 8 14:06:19 2007 Subject: [Haskell-cafe] Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <837db430708080948k52554501wdae3963fc46defe6@mail.gmail.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> <837db430708080948k52554501wdae3963fc46defe6@mail.gmail.com> Message-ID: <46BA080A.80402@metamilk.com> Hugh Perkins wrote: > On 8/8/07, *Brian Hulley* > wrote: > > In contrast, all the pure functional GUIs that I've seen... > > In defense of Haskell (wow!), note that imperative languages are not > without problems in GUIs. In a multithreaded environment, If you're using multiple threads you'd need to be in the IO monad to create/manipulate the MVars or TVars or whatever. (In contrast to eg AliceML where you could easily use a synchronising logic variable without having to leave all the familiar applicative coding comforts behind to brave the fiercesome lonely toil of "Monadia" ;-)) > typically only one thread is allowed to manage the GUI, and then you > typically need to set up some sort of message-passing system to > communicate between this thread and the others AFAIK? This is a total > PITA, so if someone has a solution for this that would rock :-) > > Question: to what extent do the Haskell wrappers around gtk and > wxWidgets suffer from this problem? I mean, I havent tried them, so > it's a genuine question. I don't know though I seem to recall some info on this on the website of Gtk2Hs. > > (Note: off the top of my head, in an imperative language, I guess one > could use some sort of generator to take an interface and generate the > message classes, and marshalling classes automatically) > > (Disclaimer: I havent really searched very hard for ways to handle > threading in GUIs in imperative languages, since mostly I either use > web pages as the visual interface, which avoids around the problem, or > use a single thread, which also avoids the problem) So far I've always managed to get away with just using a single threaded GUI. I think you run into problems with XLib and OpenGL (on GNU/Linux at least) if you try to call into those APIs from multiple threads and also it seems better to separate concerns by having all rendering code, including cacheing of geometry etc, in the same thread since it's easy enough to spawn new threads to do calculations and set a flag in the relevant widget when the result is complete... Best regards, Brian. From rodrigo.bonifacio at uol.com.br Wed Aug 8 14:14:43 2007 From: rodrigo.bonifacio at uol.com.br (rodrigo.bonifacio) Date: Wed Aug 8 14:06:43 2007 Subject: [Haskell-cafe] Defining new operators Message-ID: Hello, I have created the following function: dist :: String -> [[String]] -> [[String]] dist x y = [ x:e | e<-y ] eg.: dist "1M" [[], ["2M"], ["2M, 3M"]] = [["1M"],["1M","2M"],["1M","2M, 3M"]] How can I create an operator that perform the same function as dist? I want to write something like: "1M" ++ [[], ["2M"], ["2M", "3M"]] Thanks in advance. Rodrigo. From bf3 at telenet.be Wed Aug 8 14:16:06 2007 From: bf3 at telenet.be (peterv) Date: Wed Aug 8 14:07:59 2007 Subject: [Haskell-cafe] Newbie question (again!) about phantom types In-Reply-To: <17481.213.84.177.94.1186588759.squirrel@webmail.xs4all.nl> References: <009201c7d9cf$13810a30$3a831e90$@be> <17481.213.84.177.94.1186588759.squirrel@webmail.xs4all.nl> Message-ID: <003b01c7d9e8$2ffc6a60$8ff53f20$@be> Thanks, that is a much clearer explanation than http://en.wikibooks.org/wiki/Haskell/Phantom_types Peter -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Arie Peterson Sent: Wednesday, August 08, 2007 5:59 PM To: haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] Newbie question (again!) about phantom types > I'm having difficulty to understand what phantom types are good for. Is > this just for improving runtime performance? No. As the wiki says, you can use them to add static guarantees. > I read the wiki, and it says "this is useful if you want to increase the > type-safety of your code", but the code below does not give a compiler > error > for the function test1, I get a runtime error, just like test2. It seems you're mixing up GADT's and phantom types. > -- CODE -- > -- With phantom types > data T1 a = TI1 Int | TS1 String deriving Show Here, the 'a' is an extra type parameter, which has no manifestation on the value level. Note the type of the constructors: TI1 :: Int -> T1 a TS1 :: String -> T1 a In particular, the 'a' is not related to the 'Int' or 'String' arguments. > foo1 :: T1 String -> T1 String -> T1 String > foo1 (TS1 x) (TS1 y) = TS1 (x++y) > > test1 = foo1 (TI1 1) (TI1 2) -- Shouldn't this give a compiler error > instead > of a runtime error? 'TI1 1' has type 'T1 a', so this unifies with 'T1 String' (the type of the argument of 'foo1'. The type parameter 'a' can still be useful, but you have to use an explicit type signature to constrain the type 'a': ti1 :: Int -> T1 Int ti1 x = TI1 x Now, 'ti1' will create values with the restricted type 'T1 Int', that you can't use as arguments for your 'foo1'. GADTs are perhaps more useful for what you seem to want. Try something like this: data T1 :: * -> * where -- T1 has one type parameter TI1 :: Int -> T1 Int TS1 :: String -> T1 String Now, the type systems guarantees that all values of the form 'TI1 x' have type 'T1 Int'. Greetings, Arie _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From stefanor at cox.net Wed Aug 8 14:17:51 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 8 14:09:49 2007 Subject: [Haskell-cafe] Defining new operators In-Reply-To: References: Message-ID: <20070808181751.GA5669@localhost.localdomain> On Wed, Aug 08, 2007 at 03:14:43PM -0300, rodrigo.bonifacio wrote: > Hello, > > I have created the following function: > > dist :: String -> [[String]] -> [[String]] > dist x y = [ x:e | e<-y ] > > eg.: > > dist "1M" [[], ["2M"], ["2M, 3M"]] = [["1M"],["1M","2M"],["1M","2M, 3M"]] > > How can I create an operator that perform the same function as dist? I want to write something like: > > "1M" ++ [[], ["2M"], ["2M", "3M"]] (+++) :: String -> [[String]] -> [[String]] x +++ y = [ x:e | e<-y ] "1M" +++ [[], ["2M"], ["2M", "3M"]] Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070808/247a2199/attachment.bin From paul.hudak at yale.edu Wed Aug 8 14:20:39 2007 From: paul.hudak at yale.edu (Paul Hudak) Date: Wed Aug 8 14:12:37 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell Message-ID: <46BA0977.2040207@yale.edu> All of the recent talk of support for imperative programming in Haskell makes me really nervous. To be honest, I've always been a bit uncomfortable even with monad syntax. Instead of: do x <- cmd1 y <- cmd2 ... return e I was always perfectly happy with: cmd1 >>= \x-> cmd2 >>= \y-> ... return e Functions are in my comfort zone; syntax that hides them takes me out of my comfort zone. 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...". I hope I don't start a flame war with this post -- I'm just expressing my opinion, which admittedly is probably regressive rather than progressive :-). -Paul -- Professor Paul Hudak Department of Computer Science Office: (203) 432-1235 Yale University FAX: (203) 432-0593 P.O. Box 208285 email: paul.hudak@yale.edu New Haven, CT 06520-8285 WWW: www.cs.yale.edu/~hudak -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070808/6e703f51/attachment.htm From overdrigzed at gmail.com Wed Aug 8 14:21:09 2007 From: overdrigzed at gmail.com (Rodrigo Queiro) Date: Wed Aug 8 14:13:05 2007 Subject: [Haskell-cafe] Defining new operators In-Reply-To: References: Message-ID: <2eb8984a0708081121v192c6a7ep237d72763efd0f5b@mail.gmail.com> In addition to creating a new operator, you can use the function as an operator with ``, e.g.: "1M" `dist` [[], ["2M"], ["2M, 3M"]] = [["1M"],["1M","2M"],["1M","2M, 3M"]] Rodrigo PS. Sorry if I sent this twice. On 08/08/2007, rodrigo.bonifacio wrote: > Hello, > > I have created the following function: > > dist :: String -> [[String]] -> [[String]] > dist x y = [ x:e | e<-y ] > > eg.: > > dist "1M" [[], ["2M"], ["2M, 3M"]] = [["1M"],["1M","2M"],["1M","2M, 3M"]] > > How can I create an operator that perform the same function as dist? I want to write something like: > > "1M" ++ [[], ["2M"], ["2M", "3M"]] > > Thanks in advance. > > Rodrigo. > > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From bf3 at telenet.be Wed Aug 8 14:31:03 2007 From: bf3 at telenet.be (peterv) Date: Wed Aug 8 14:22:59 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <46BA0977.2040207@yale.edu> References: <46BA0977.2040207@yale.edu> Message-ID: <004f01c7d9ea$470a4ae0$d51ee0a0$@be> IMHO and being a newbie having 20 years of professional C/C++/C# experience but hardly any Haskell experience, I agree with this. I find the monad syntax very confusing, because it looks so much like imperative code, but it isn't. Personally I also liked the Concurrent Clean approach, although this also introduced extra syntax for the compiler, while 'cmd1 >>= \x.' does not. You have to type more, but you see much clearer what is going on. Peter PS: It would be very nice for beginners to have a special tool / text editor that allows you see the desugared form of monads and other constructs. From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Paul Hudak Sent: Wednesday, August 08, 2007 8:21 PM To: haskell-cafe@haskell.org Cc: paul.hudak@yale.edu Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell All of the recent talk of support for imperative programming in Haskell makes me really nervous. To be honest, I've always been a bit uncomfortable even with monad syntax. Instead of: do x <- cmd1 y <- cmd2 ... return e I was always perfectly happy with: cmd1 >>= \x-> cmd2 >>= \y-> ... return e Functions are in my comfort zone; syntax that hides them takes me out of my comfort zone. 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...". I hope I don't start a flame war with this post -- I'm just expressing my opinion, which admittedly is probably regressive rather than progressive :-). -Paul -- Professor Paul Hudak Department of Computer Science Office: (203) 432-1235 Yale University FAX: (203) 432-0593 P.O. Box 208285 email: paul.hudak@yale.edu New Haven, CT 06520-8285 WWW: www.cs.yale.edu/~hudak -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070808/d64dc972/attachment-0001.htm From flippa at flippac.org Wed Aug 8 14:37:51 2007 From: flippa at flippac.org (Philippa Cowderoy) Date: Wed Aug 8 14:27:52 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <004f01c7d9ea$470a4ae0$d51ee0a0$@be> References: <46BA0977.2040207@yale.edu> <004f01c7d9ea$470a4ae0$d51ee0a0$@be> Message-ID: On Wed, 8 Aug 2007, peterv wrote: > PS: It would be very nice for beginners to have a special tool / text editor > that allows you see the desugared form of monads and other constructs. > An editor that can be configured to display various inferred details, annotations and desugarings in the middle of the source would be useful for all kinds of purposes, and certainly not just to newbies! For example, it could be used to show what information the type checker had inferred before hitting an error... -- flippa@flippac.org "The reason for this is simple yet profound. Equations of the form x = x are completely useless. All interesting equations are of the form x = y." -- John C. Baez From isaacdupree at charter.net Wed Aug 8 14:39:07 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Wed Aug 8 14:41:03 2007 Subject: [Haskell-cafe] Re: default for quotRem in terms of divMod? In-Reply-To: <46B9B9D2.6080709@dfki.de> References: <46B8DF69.70103@charter.net> <46B9B9D2.6080709@dfki.de> Message-ID: <46BA0DCB.10204@charter.net> Christian Maeder wrote: > > > Isaac Dupree wrote: >> In class Integral, divMod has a default in terms of quotRem. >> (quot,rem,div,mod all have defaults as the both-function they're part >> of.) I'm sure divMod is more natural than quotRem to implement for some >> types... so why doesn't quotRem have a default in terms of divMod? it >> has no default! Then the "minimal to implement" will change from >> (toInteger and quotRem) to (toInteger and (quotRem or divMod)). >> >> Isaac > > while I don't care if quotRem or divMod should be implemented. I oppose > to give both default implementations in terms of the other. > > Already for the class Eq either == or /= must be defined, with the > unpleasant effect that an empty instance like: > > instance Eq T > > leads to a loop (when == or /= is called on elements of type T). > > The empty instance does not even raise a warning about unimplemented > methods (since the default definition is used). > > I'd rather prefer to remove /= as method of Eq. I second that this is a problem. However, I think that compilers are perfectly justified in replacing nontermination with a runtime error(i.e. exception - the generalization of a call to "error"), and also generating warnings when it's unimplemented class methods, and we could solve it that way. I don't know how hard it is to detect automatically that two default definitions produce a useless loop... if that's too hard, possibly some explicit annotation in the code could be done (Already there is an informal convention of saying exactly what methods must be implemented, so that should be formalize-able...). I _think_ that for Eq and my Integral proposal, GHC's strictness analyser is quite up to the task. In general, what do we think about replacing certain nontermination with an exception, particularly by the compiler's detection? GHC already does it very unreliably with the <> low-level thunk something-or-other.... It might be interesting to see how many spurious warnings would be generated, if GHC also generated a warning for each - i.e. is nontermination ever intentionally used as a _|_ normally? Isaac From yumagene at gmail.com Wed Aug 8 14:49:45 2007 From: yumagene at gmail.com (Gene A) Date: Wed Aug 8 14:41:42 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: References: <46BA0977.2040207@yale.edu> <004f01c7d9ea$470a4ae0$d51ee0a0$@be> Message-ID: <9d8904760708081149n14f091f3l2583102729483b20@mail.gmail.com> On 8/8/07, Philippa Cowderoy wrote: > > On Wed, 8 Aug 2007, peterv wrote: > {... > An editor that can be configured to display various inferred details, > annotations and desugarings in the middle of the source would be useful > for all kinds of purposes, and certainly not just to newbies! ...} I couldn't agree more.. that would be a godsend to have that .. One would think that the code to translate has to be in the compiler code, though I doubt that it does so to a readable format.. oh well. gene -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070808/f4f37573/attachment.htm From donn at drizzle.com Wed Aug 8 14:56:03 2007 From: donn at drizzle.com (Donn Cave) Date: Wed Aug 8 14:48:01 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <46BA0977.2040207@yale.edu> Message-ID: On Wed, 8 Aug 2007, Paul Hudak wrote: ... > 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...". It seems to me that Brian Hulley threw the glove down hard. Does pure functional Haskell offer a better way to write a GUI? I love the functional stuff myself, but if real applications depend on extensive imperative logic, we're best served by a language that cheerfully embraces the inevitable and handles it well. Monads, the do syntax, whatever it takes (I have a soft spot for O'Haskell, but alas I must be nearly alone on that.) Hopefully, it's still better, and not at all irreconcilable with the Functional Way. Donn Cave, donn@drizzle.com (That's a genuine question, by the way - my attempt to build a current Haskell GUI library on NetBSD foundered and I have no experience with Haskell GUI coding, but it's on the list of things I would like to look at. So if there's one that really illustrates the virtues of pure functional Haskell programming, that would be a welcome tip!) From hughperkins at gmail.com Wed Aug 8 14:56:34 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Wed Aug 8 14:48:31 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <004f01c7d9ea$470a4ae0$d51ee0a0$@be> References: <46BA0977.2040207@yale.edu> <004f01c7d9ea$470a4ae0$d51ee0a0$@be> Message-ID: <837db430708081156u2d5cc9dboef28d8eb2fc8ce47@mail.gmail.com> On 8/9/07, peterv wrote: > > IMHO and being a newbie having 20 years of professional C/C++/C# > experience but hardly any Haskell experience, I agree with this? I find the > monad syntax very confusing, because it looks so much like imperative code, > but it isn't. Personally I also liked the Concurrent Clean approach, > although this also introduced extra syntax for the compiler, while 'cmd1 >>= > \x?' does not. You have to type more, but you see much clearer what is going > on. > Yeah, I kind of agree too. The only way I figured out sortof how to use Monads was to write everything out in >>= syntax. It was longer and uglier, but it made more sense. That said, I sortof see Haskell as a prototype language, whose good points will be added into other languages. Every program needs to have a prototype, and Haskell is that. So, whilst I'm tempted to add: an easy language needs to have only a single way of doing anything, so throwing away the "do" syntax makes the language easier by reducing the number of things to learn, actually for a prototype language, the rule is probably "anything goes", and then the best ideas get added to the non-prototype language later on. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/760f1e9e/attachment.htm From jeff.polakow at db.com Wed Aug 8 15:01:46 2007 From: jeff.polakow at db.com (Jeff Polakow) Date: Wed Aug 8 14:53:48 2007 Subject: [Haskell-cafe] Re: Using haskell with emacs In-Reply-To: <20070808180523.GA3140@localhost.localdomain> Message-ID: Hello, > :r is also *much* faster in general; :l reloads all modules from > scratch, while :r only reloads the modules that have changed. > :r also doesn't seem check the import declarations for changes. For example, if I add a new import statement to my file, without adding code which uses the new import, :r will not cause the newly imported things to be in scope, but :l will. BTW this is for GHCi 6.6.1, though I think older versions had the same behavior. -Jeff --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070808/1971c85c/attachment.htm From bf3 at telenet.be Wed Aug 8 15:14:37 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Wed Aug 8 15:06:36 2007 Subject: [Haskell-cafe] Pure functional GUI (was =?us-ascii?Q?=22a?= regressive view of support for imperativeprogramming in =?us-ascii?Q?Haskell=22)?= Message-ID: As a newbie (okay I will not write this again, you all know I'm a newbie by now ;-), I don't understood what the problem of a pure functional GUI is. To me, having an imperative background, a graphical application is just a big tree of data that evolves when events from the OS come in. (this data is NOT per se the data for the GUI element; instead use the model-view-controller design pattern) In Haskell, instead of mutating the data (as done in C/C++), a infinite stream of this tree-data is generated responding to an infinite steam of events, as in Paul's SOE book (the reactive stuff). Since most of the data can be shared, the performance impact should be minimal. So could you please tell me more about the problem with pure functional GUIs and why this is not part of the Haskell library? I mean a GUI library completely written in Haskell, not wrapping a popular library. Thanks, Peter >----- Oorspronkelijk bericht ----- >Van: Donn Cave [mailto:donn@drizzle.com] >Verzonden: woensdag, augustus 8, 2007 08:56 PM >Aan: haskell-cafe@haskell.org >Onderwerp: Re: [Haskell-cafe] a regressive view of support for imperative programming in Haskell > >On Wed, 8 Aug 2007, Paul Hudak wrote: >... >> 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...". > >It seems to me that Brian Hulley threw the glove down hard. Does >pure functional Haskell offer a better way to write a GUI? > >I love the functional stuff myself, but if real applications depend >on extensive imperative logic, we're best served by a language that >cheerfully embraces the inevitable and handles it well. Monads, the >do syntax, whatever it takes (I have a soft spot for O'Haskell, but >alas I must be nearly alone on that.) Hopefully, it's still better, >and not at all irreconcilable with the Functional Way. > > Donn Cave, donn@drizzle.com > >(That's a genuine question, by the way - my attempt to build a >current Haskell GUI library on NetBSD foundered and I have no >experience with Haskell GUI coding, but it's on the list of things >I would like to look at. So if there's one that really illustrates >the virtues of pure functional Haskell programming, that would be >a welcome tip!) > >_______________________________________________ >Haskell-Cafe mailing list >Haskell-Cafe@haskell.org >http://www.haskell.org/mailman/listinfo/haskell-cafe > > From duncan.coutts at worc.ox.ac.uk Wed Aug 8 15:36:00 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 8 15:26:47 2007 Subject: [Haskell-cafe] Pure functional GUI (was "a regressive view of support for imperativeprogramming in Haskell") In-Reply-To: References: Message-ID: <1186601760.12043.29.camel@localhost> On Wed, 2007-08-08 at 19:14 +0000, Peter Verswyvelen wrote: > So could you please tell me more about the problem with pure > functional GUIs and why this is not part of the Haskell library? I > mean a GUI library completely written in Haskell, not wrapping a > popular library. Partly because just getting the drawing and interaction behaviour to be acceptable would be many person-years of work. GUI toolkits are not especially simple things. Even if you could do it in just 1/10th of the number of lines of code of Gtk+ or Qt it'd be a massive undertaking. Duncan From bf3 at telenet.be Wed Aug 8 16:22:41 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Wed Aug 8 16:14:38 2007 Subject: [Haskell-cafe] Pure functional GUI (was Message-ID: Well, if you want to make it as big as QT, yes. But even just a simple purely functionaly GUI framework that is part of the library would be nice, because right now it gives the impression it cannot be done in Haskell... E.g. Concurrent Clean seems to have a simple UI library. >----- Oorspronkelijk bericht ----- >Van: Duncan Coutts [mailto:duncan.coutts@worc.ox.ac.uk] >Verzonden: woensdag, augustus 8, 2007 09:36 PM >Aan: 'Peter Verswyvelen' >CC: 'Donn Cave', haskell-cafe@haskell.org >Onderwerp: re: [Haskell-cafe] Pure functional GUI (was "a regressive view of support for imperativeprogramming in Haskell") > >On Wed, 2007-08-08 at 19:14 +0000, Peter Verswyvelen wrote: > >> So could you please tell me more about the problem with pure >> functional GUIs and why this is not part of the Haskell library? I >> mean a GUI library completely written in Haskell, not wrapping a >> popular library. > >Partly because just getting the drawing and interaction behaviour to be >acceptable would be many person-years of work. > >GUI toolkits are not especially simple things. Even if you could do it >in just 1/10th of the number of lines of code of Gtk+ or Qt it'd be a >massive undertaking. > >Duncan > > > From droundy at darcs.net Wed Aug 8 16:41:03 2007 From: droundy at darcs.net (David Roundy) Date: Wed Aug 8 16:33:02 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <46BA0977.2040207@yale.edu> References: <46BA0977.2040207@yale.edu> Message-ID: <20070808204103.GU13960@darcs.net> On Wed, Aug 08, 2007 at 02:20:39PM -0400, Paul Hudak wrote: > All of the recent talk of support for imperative programming in Haskell > makes me really nervous. To be honest, I've always been a bit > uncomfortable even with monad syntax. Instead of: > > do x <- cmd1 > y <- cmd2 > ... > return e > > I was always perfectly happy with: > > cmd1 >>= \x-> > cmd2 >>= \y-> > ... > return e I may be stating the obvious here, but I strongly prefer the do syntax. It's nice to know the other also, but the combination of do+indenting makes complicated code much clearer than the nested parentheses that would be required with purely >>= syntax. > 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...". (I suppose I just did as you suggested I could...) I'd say that monadic programming is *not* the same as C++ programming. "Normal" programming in a Haskell monad (e.g. parsing, Maybe, IO) does not involve IORefs, and generally behaves quite nicely. Several times since reading the beginning of this discussion I've wished I had the new syntax so I could write something like: do if predicateOnFileContents (<- readFile "foo") then ... instead of either do contents <- readFile "foo" if predicateOnFileContents contents then ... or (as you'd prefer) readFile "foo" >>= \contents -> if predicateOnFileContents contents then ... As long as the sugar has a pretty obvious desugaring (which I seem to recall it did), I don't see how it's likely to make things worse. And there are an awful lot of situations where code would be reduced by a line, and (much more importantly) by a temporary variable. Every temporary variable declared adds that much syntactic overhead to a function, since the reader is forced to scan through the rest of the function to see if it is ever used again before he can understand what is being done and how it's being used. -- David Roundy Department of Physics Oregon State University From d at vidplace.com Wed Aug 8 17:06:09 2007 From: d at vidplace.com (David F. Place) Date: Wed Aug 8 16:58:09 2007 Subject: [Haskell-cafe] Pure functional GUI (was "a regressive view of support for imperativeprogramming in Haskell") In-Reply-To: References: Message-ID: <4D6ACC04-D53E-4187-93F4-0E1C0FF357E8@vidplace.com> On Aug 8, 2007, at 3:14 PM, Peter Verswyvelen wrote: > So could you please tell me more about the problem with pure > functional GUIs and why this is not part of the Haskell library? I > mean a GUI library completely written in Haskell, not wrapping a > popular library. I had quite a lot of experience in pure functional GUI technology in developing the user-interface for the ICAD system -- a domain specific language for mechanical engineering. We developed another domain specific language for describing user-interface objects as a tree structure and implemented commands as applicative transactions using Zippers, though we called them path transactions. (Oh, did I mention this was in 1987?) Redisplay and undo of course were handled automatically. It was developed on Lisp Machines and then ported to X-Windows. I believe there are some nooks and crannies in the aircraft industry were it is still being used. There were some issues which time may have solved. 1.) Redisplay could be a little tedious due to slow video hardware. 2.) Locality became a problem with the shared data-structures being spread throughout memory. Thus performance could be adversely affected by paging. (In 1987, 8MBytes of Lisp Machine memory cost $10,000.) Issues that time won't solve. 1.) It was non-standard -- at the time that meant "not Motif." Does anybody remember Motif? 2.) It is a thankless task. Innovation is not welcomed. It's better left up to committees. I don't believe that there is any technical reason why something interesting couldn't be done. But if you actually want people to use your GUI tools, that is several orders of magnitude more work -- and not the most interesting kind. An interesting possibility that arises when coding has become so effortless as it now has in Haskell, is to create GUI technologies just for a single project. Encourage innovation and experimentation in usability with a captive audience. An example of this is the PureData computer music system. The user-interface is quite innovative and non-standard, but the users of the application have taken it to a cult status even though it's purposefully kind of ugly. http://puredata.info/ ___________________ (---o-------o-o-o---o-o-o----( David F. Place mailto:d@vidplace.com From rk at trie.org Wed Aug 8 17:23:59 2007 From: rk at trie.org (Rahul Kapoor) Date: Wed Aug 8 17:15:55 2007 Subject: [Haskell-cafe] Using HList Records Message-ID: Using The Darcs version of HList (http://darcs.haskell.org/HList/), I can do simple things with (H)lists just fine, so --angus = Key 42 -- .*. Name "Angus" -- .*. Cow -- .*. Price 75.5 -- .*. HNil --main = putStrLn (show angus) works, On the other hand examples from the HList paper for extensible records like --key = firstLabel FootNMouth "key" --name = nextLabel key "name" --breed = nextLabel name "breed" --price = nextLabel breed "price" do not compile with errors --Main.hs:15:8-17: Not in scope: `firstLabel' --Main.hs:16:8-16: Not in scope: `nextLabel' A quick show "ghc-pkg describe HList" shows that --exposed-modules: HList --hidden-modules: Label4 CommonMain Variant GhcSyntax GhcRecord -- Record HZip TIC TIP HTypeIndexed HOccurs HArray GhcExperiments -- HListPrelude TypeEqBoolGeneric TypeEqGeneric1 TypeCastGeneric1 -- FakePrelude So the question is do I need to play around with the cabal file to expose the right stuff? Or has the syntax changed? I get errors running "./setup haddock" (configure, build, install, are fine). Are the HList api docs available anywhere online? Rahul From brianh at metamilk.com Wed Aug 8 17:56:04 2007 From: brianh at metamilk.com (Brian Hulley) Date: Wed Aug 8 17:47:49 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <46BA0977.2040207@yale.edu> References: <46BA0977.2040207@yale.edu> Message-ID: <46BA3BF4.2050204@metamilk.com> Paul Hudak wrote: > All of the recent talk of support for imperative programming in > Haskell makes me really nervous.... > ... 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...". Perhaps I may have sounded unappreciative of all the hard work that's been done trying to find solutions to the problem of GUI programming in a pure functional style. I think the problem is that for the purposes of research, it is sufficient to show that a concept can be implemented but the speed of the resulting program is not that important compared to the essential ideas. Thus the concept of a GUI as a time varying continuous function of events and response pictures (represented as functions:: Vector3 Float -> RGB) is tremendously appealing, and will surely become the standard way when machines get fast enough, but for the moment this nice pure functional way just doesn't seem directly applicable (;-)). I see the problem you're pointing to though - that the language could become caught in the middle trying to serve two rather different purposes namely a pure ground for research and a fast general purpose platform for creating programs now. As for me, the issue is just that after spending almost 2 years with Haskell trying to find/discover a purely functional solution to this problem that will be suitable for a practical high speed graphics application on standard hardware, being unsuccessful, and not having any funding to pursue this research further, my only option is to either use the imperative monadic style of Haskell programming or to use OCaml or C++, because I need to get something written right now that I can put on my website to sell... Personally I don't find the existing do notation all that burdensome - I've got used to it, and even though each action must be explicitly written, the ease with which higher order functions can be introduced to factor out commonality means that the do blocks are often shorter than the corresponding C++ code from my previous GUI. Furthermore, even though I'm using the imperative style, the use of Haskell has led me to surprisingly neat solutions to several problems that I didn't discover when I implemented the previous versions in C++ and C#, so I think there are still great benefits to be had from using Haskell or languages inspired by it. Best regards, Brian. From marco-oweber at gmx.de Wed Aug 8 18:18:36 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Wed Aug 8 18:10:33 2007 Subject: [Haskell-cafe] Pure functional GUI (was In-Reply-To: References: Message-ID: <20070808221836.GA8246@gmx.de> On Wed, Aug 08, 2007 at 08:22:41PM +0000, Peter Verswyvelen wrote: > Well, if you want to make it as big as QT, yes. > > But even just a simple purely functionaly GUI framework that is part of the library would be nice, because right now it gives the impression it cannot be done in Haskell... Perhaps the yi keybaard mapping library can be seen as ui ? At least everything is written in haskell, parsing keyboard events and displaying reactions.. I will never compete with gtk etc though. I think this might be an example that it can be done in haskell Marc Weber From claus.reinke at talk21.com Wed Aug 8 18:57:45 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Wed Aug 8 18:49:46 2007 Subject: [Haskell-cafe] Pure functional GUI (was "a regressive view of support for imperativeprogramming in Haskell") References: Message-ID: <018b01c7da0f$89f8d860$5f168351@cr3lt> FranTk, Haggis, Fudgets, Object I/O for Haskell, Gadgets, Pictures, HTk, Haskell Tk, HToolkit, Gtk+HS, Gtk2Hs, wxHaskell, FunctionalForms, .. and no, that list is not exhaustive by any means (you can find abstracts for some of these in old haskell community reports, but a lot of functional gui lib research pre-dates those reports). functional gui libs used to be one of the favourite haskell research excercises. some of those were low-level bindings, some were high-level declarative abstractions, but that wasn't the problem. the problem was that very nearly all of them came and went. the declared goal of the current generation was to provide more long-lived platforms, leaving most of the maintenance to others by binding directly to popular imperative libraries. it was always the intention that someone would build higher-level declarative approaches on top of those bindings. claus From hughperkins at gmail.com Wed Aug 8 20:59:04 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Wed Aug 8 20:51:00 2007 Subject: [Haskell-cafe] Pure functional GUI (was In-Reply-To: References: Message-ID: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> To be fair, GTK is pretty standard. This is so even for "big name" gc'd imperative languages such as C#. Sure, you can use Windows.Forms in C#, but you often wouldnt, because of the patent burden. Also, gtk in partnership with glade rocks! How easy is gtk to use from haskell by the way? In gc'd imperative languages, typically only one thread is allowed to communicate with the GUI, and you need to set up a whole bunch of message-parsing stuff to communicate with other threads. To what extent is this easier in Haskell? Other question on using gtk from haskell: how easy is it to integrate with glade? ie, can we directly bind glade form elements to haskell variables? How easy is it to bind events to glade form elements from within Haskell? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/01aede5b/attachment.htm From mvanier at cs.caltech.edu Wed Aug 8 20:59:41 2007 From: mvanier at cs.caltech.edu (Michael Vanier) Date: Wed Aug 8 20:51:52 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <837db430708081156u2d5cc9dboef28d8eb2fc8ce47@mail.gmail.com> References: <46BA0977.2040207@yale.edu> <004f01c7d9ea$470a4ae0$d51ee0a0$@be> <837db430708081156u2d5cc9dboef28d8eb2fc8ce47@mail.gmail.com> Message-ID: <46BA66FD.5020007@cs.caltech.edu> I can't agree with your point about Haskell being (just) a prototype language (assuming that's what you meant). If that's the case, it won't last very long. Languages need to be something you can write real, practical applications in. Fortunately, Haskell isn't just a prototype language. I'm running a Haskell program (xmonad) every minute I'm working on my computer, and it's better than the C program (ion) that it replaced (with a code base about 1/40th the size). I'm sure Haskell isn't suitable for all application domains yet, but there's plenty of domains in which it can make its mark, and the frontier is going to keep getting pushed back. Mike Hugh Perkins wrote: > On 8/9/07, *peterv* > wrote: > > IMHO and being a newbie having 20 years of professional C/C++/C# > experience but hardly any Haskell experience, I agree with this??? I > find the monad syntax very confusing, because it looks so much like > imperative code, but it isn't. Personally I also liked the > Concurrent Clean approach, although this also introduced extra > syntax for the compiler, while 'cmd1 >>= \x???' does not. You have > to type more, but you see much clearer what is going on. > > Yeah, I kind of agree too. The only way I figured out sortof how to use > Monads was to write everything out in >>= syntax. It was longer and > uglier, but it made more sense. > > That said, I sortof see Haskell as a prototype language, whose good > points will be added into other languages. Every program needs to have > a prototype, and Haskell is that. > > So, whilst I'm tempted to add: an easy language needs to have only a > single way of doing anything, so throwing away the "do" syntax makes the > language easier by reducing the number of things to learn, actually for > a prototype language, the rule is probably "anything goes", and then the > best ideas get added to the non-prototype language later on. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From dons at cse.unsw.edu.au Wed Aug 8 21:17:51 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Wed Aug 8 21:09:50 2007 Subject: [Haskell-cafe] Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46BA080A.80402@metamilk.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> <837db430708080948k52554501wdae3963fc46defe6@mail.gmail.com> <46BA080A.80402@metamilk.com> Message-ID: <20070809011751.GC4165@cse.unsw.EDU.AU> brianh: > Hugh Perkins wrote: > >On 8/8/07, *Brian Hulley* >> wrote: > > > > In contrast, all the pure functional GUIs that I've seen... > > > >In defense of Haskell (wow!), note that imperative languages are not > >without problems in GUIs. In a multithreaded environment, > If you're using multiple threads you'd need to be in the IO monad to > create/manipulate the MVars or TVars or whatever. (In contrast to eg > AliceML where you could easily use a synchronising logic variable > without having to leave all the familiar applicative coding comforts > behind to brave the fiercesome lonely toil of "Monadia" ;-)) Or use purely functional channels (Chan). -- Don From dons at cse.unsw.edu.au Wed Aug 8 21:21:23 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Wed Aug 8 21:13:20 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <004f01c7d9ea$470a4ae0$d51ee0a0$@be> References: <46BA0977.2040207@yale.edu> <004f01c7d9ea$470a4ae0$d51ee0a0$@be> Message-ID: <20070809012123.GD4165@cse.unsw.EDU.AU> bf3: > > IMHO and being a newbie having 20 years of professional > C/C++/C# experience but hardly any Haskell experience, I > agree with this... I find the monad syntax very confusing, > because it looks so much like imperative code, but it isn't. > Personally I also liked the Concurrent Clean approach, > although this also introduced extra syntax for the compiler, > while `cmd1 >>= \x...' does not. You have to type more, but > you see much clearer what is going on. > > > Peter > > > PS: It would be very nice for beginners to have a special > tool / text editor that allows you see the desugared form of > monads and other constructs... Drop by #haskell and use lambdabot: 11:21 dons> @undo do x <- getChar ; putChar (toUpper x) 11:21 lambdabot> getChar >>= \ x -> putChar (toUpper x) -- Don From marco-oweber at gmx.de Wed Aug 8 22:41:04 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Wed Aug 8 22:33:31 2007 Subject: [Haskell-cafe] Using HList Records In-Reply-To: References: Message-ID: <20070809024104.GB8294@gmx.de> > So the question is do I need to play around with the cabal file to > expose the right stuff? Or has the syntax changed? I'm not absolutely sure. I would have to reread the source code. But there are different kinds of labels. The are in different modules. src/Label{1,2,..} So all you have to do is check which one you need and check wether it's listed in the cabal file. If this didn't help post again. HTH Marc Weber From marco-oweber at gmx.de Wed Aug 8 22:54:05 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Wed Aug 8 22:46:21 2007 Subject: [Haskell-cafe] Pure functional GUI (was In-Reply-To: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> Message-ID: <20070809025405.GC8294@gmx.de> > Other question on using gtk from haskell: how easy is it to integrate > with glade? ie, can we directly bind glade form elements to haskell > variables? How easy is it to bind events to glade form elements from > within Haskell? Download the source and have a look at the demo/glade folder.. ;-) (I've pasted the most important lines below) Marc [...] -- load up the glade file dialogXmlM <- xmlNew "simple.glade" let dialogXml = case dialogXmlM of (Just dialogXml) -> dialogXml Nothing -> error "can't find the glade file \"simple.glade\" \ \in the current directory" -- get a handle on a couple widgets from the glade file window <- xmlGetWidget dialogXml castToWindow "window1" button <- xmlGetWidget dialogXml castToButton "button1" [...] From ok at cs.otago.ac.nz Thu Aug 9 00:02:05 2007 From: ok at cs.otago.ac.nz (ok) Date: Wed Aug 8 23:54:09 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <20070808204103.GU13960@darcs.net> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> Message-ID: <235177FA-A63E-4268-8A94-83C286BA4DD3@cs.otago.ac.nz> On 9 Aug 2007, at 8:41 am, David Roundy wrote: > I may be stating the obvious here, but I strongly prefer the do > syntax. > It's nice to know the other also, but the combination of do > +indenting makes > complicated code much clearer than the nested parentheses that > would be > required with purely >>= syntax. Er, what nested parentheses would those be? do e => e do e => e >> rest rest' do p <- e => e >>= \p -> rest rest' do let d => let d in rest rest' We get extra >>, >>=, \, ->, and "in" tokens, but no new parentheses. The example in the Report makes this clear: do putStr "x: " l <- getLine return (words l) desugars to putStr "x: " >> getLine >>= \l -> return (words l) with no extra parentheses. [Not that this actually works in GHC 6; the implied flush isn't done.] From hughperkins at gmail.com Thu Aug 9 00:46:45 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 9 00:38:41 2007 Subject: [Haskell-cafe] Pure functional GUI (was In-Reply-To: <20070809025405.GC8294@gmx.de> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> <20070809025405.GC8294@gmx.de> Message-ID: <837db430708082146m2ce9cbe1m98ea15e23a49fa04@mail.gmail.com> On 8/9/07, Marc Weber wrote: > > -- load up the glade file > dialogXmlM <- xmlNew "simple.glade" > let dialogXml = case dialogXmlM of > (Just dialogXml) -> dialogXml > Nothing -> error "can't find the glade file \"simple.glade\" > \ > \in the current directory" > > -- get a handle on a couple widgets from the glade file > window <- xmlGetWidget dialogXml castToWindow "window1" > button <- xmlGetWidget dialogXml castToButton "button1" > Oooo... nice :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/be7ac8c9/attachment.htm From hughperkins at gmail.com Thu Aug 9 01:03:32 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 9 00:55:30 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <235177FA-A63E-4268-8A94-83C286BA4DD3@cs.otago.ac.nz> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <235177FA-A63E-4268-8A94-83C286BA4DD3@cs.otago.ac.nz> Message-ID: <837db430708082203k56ed1200s80bf40bf928c1a94@mail.gmail.com> On 8/9/07, ok wrote: > > We get extra >>, >>=, \, ->, and "in" tokens, but no new parentheses. > Yes exactly. It's the >>= and >> that gets rid of the parentheses, and reverses the order of the operations. I cant remember where I saw this, but somewhere there is a monad tutorial that starts really from the basics, which is that a "do" list is essentially something like: f (g (h initialvalue ) ) ... which we can rewrite as something like: h initialvalue |> g |> f .. for a suitable definition of |> , something like (off the top of my head, almost certainly wrong): (|>) f g = g f -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/f11cd2f4/attachment.htm From bulat.ziganshin at gmail.com Thu Aug 9 01:30:04 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 9 01:44:20 2007 Subject: [Haskell-cafe] Pure functional GUI (was "a regressive view of support for imperativeprogramming in Haskell") In-Reply-To: References: Message-ID: <1418427027.20070809093004@gmail.com> Hello Peter, Wednesday, August 8, 2007, 11:14:37 PM, you wrote: > To me, having an imperative background, a graphical application is > just a big tree of data that evolves when events from the OS come > in. (this data is NOT per se the data for the GUI element; instead > use the model-view-controller design pattern) In Haskell, instead of > mutating the data (as done in C/C++), a infinite stream of this > tree-data is generated responding to an infinite steam of events, as > in Paul's SOE book (the reactive stuff). Since most of the data can > be shared, the performance impact should be minimal. > So could you please tell me more about the problem with pure > functional GUIs seems that such program will have no effects :) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From bulat.ziganshin at gmail.com Thu Aug 9 01:34:19 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 9 01:44:27 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <46BA0977.2040207@yale.edu> References: <46BA0977.2040207@yale.edu> Message-ID: <1849868124.20070809093419@gmail.com> Hello Paul, Wednesday, August 8, 2007, 10:20:39 PM, you wrote: > 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...". well, are you ever programmed real world application? i need such design for using it in the cases when functional approach apply - and of course, functional approach will be much nicer in these cases. it is required for situations when i forced to write imperative program due to some environment limitations -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From bulat.ziganshin at gmail.com Thu Aug 9 01:43:41 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 9 01:44:35 2007 Subject: [Haskell-cafe] Pure functional GUI (was In-Reply-To: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> Message-ID: <1533503188.20070809094341@gmail.com> Hello Hugh, Thursday, August 9, 2007, 4:59:04 AM, you wrote: > How easy is gtk to use from haskell by the way?? In gc'd > imperative languages, typically only one thread is allowed to > communicate with the GUI, and you need to set up a whole bunch of > message-parsing stuff to communicate with other threads.? To what > extent is this easier in Haskell? you can just send actions to the GUI thread :) something like this: main = do c <- newChan getChanContents c >>= forkOS . guiThread for [1..10] $ \i -> do writeChan c (print i) ... guiThread (a:actions) = do a guiThread actions -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From miguelimo38 at yandex.ru Thu Aug 9 02:30:15 2007 From: miguelimo38 at yandex.ru (Miguel Mitrofanov) Date: Thu Aug 9 02:23:36 2007 Subject: [Haskell-cafe] Re: Using haskell with emacs In-Reply-To: References: <11b141710708061311u640d24d4u27150c37ba1aec15@mail.gmail.com> Message-ID: <1509771151.20070809103015@yandex.ru> >> I don't know enough about the details to know if :l and :r do >> exactly the same things in ghci. SM> I don't either. But experimentation suggests that the only SM> difference is that :r doesn't need an argument (which in the case SM> of haskell-mode doesn't make any difference since the arg is SM> provided by haskell-mode anyway). But sometimes it's not the right argument if you have several haskell source files opened. I don't find C-c C-r to be of much use, but it's useful sometimes. From jules at jellybean.co.uk Thu Aug 9 05:41:30 2007 From: jules at jellybean.co.uk (Jules Bean) Date: Thu Aug 9 05:33:30 2007 Subject: [Haskell-cafe] Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46B9DAA7.4070006@metamilk.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> Message-ID: <46BAE14A.1040909@jellybean.co.uk> Brian Hulley wrote: > Haskell is designed so > that any attempt at abstracting mutable local state will infect the > entire program (modulo use of a highly dangerous function whose > semantics is entirely unclear, depending on the vagaries of evaluation > strategy of the particular compiler) (Your email message is long and very interesting, and it does an a considerable injustice to take one sentence out of context, but...) This echoes a misconception that I see here on haskell-cafe quite often. Mutable local state *really* doesn't need to infect the whole program, and haskell is certainly not designed so it must. We have all kinds of techniques for ensuring that the pure parts of your code can remain pure, and only the impure parts get 'infected' with an IO signature. Additionally, if it's just refs, you can use ST, which is totally pure. If it's literally just state, you can use the techniques of the State monad and the Reader monad: but you don't necessarily have to use them explicitly with those names. Sometimes it is actually simpler just to use the types s -> (a,s) and s -> a directly; only in certain circumstances is the extra plumbing useful. Often different parts of your program have different needs; some parts actually need the ability to make fresh names (and so need STRefs) other parts merely read the state (and can use Reader techniques) and other parts alter it (and can use State techniques). You need some plumbing to connect the different parts together, but fortunately haskell has powerful abstraction and it's quite easy to slap together the higher-order functions (combinators!) to do this. Jules From simonpj at microsoft.com Thu Aug 9 05:53:24 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Thu Aug 9 05:45:20 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: References: <46B468B3.7000704@btinternet.com> <46B494D4.5000709@cogito.org.uk> <46B49D60.402@btinternet.com> Message-ID: Indeed! Getting the library numerics to do the Right Thing is something that can only be done by people who know about numerics. People who build compilers aren't, alas. It's quite a specialised subject, and very easy to screw up. And there's performance to worry about too in the common case when the corner cases don't appear. So if there are folk out there who care about getting numerics correct, we would welcome your direct involvement. Look at the code, make it right, send patches to libraries@haskell.org. It's all open source, and you'll be benefiting lots of people. Simon From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Lennart Augustsson Sent: 04 August 2007 16:47 To: Andrew Coppin Cc: haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] How odd... Haskell doesn't know much about infinity, but Haskell implementations are allowed to use IEEE floating point which has infinity. And to get things right, there needs to be a few changes to the library to do the right thing for certain numbers, this is not news. In fact I filed a bug report a while back about it. -- Lennart On 8/4/07, Andrew Coppin > wrote: Paul Johnson wrote: > Andrew Coppin wrote: >> > 0**2 >> 0 >> >> > (0 :+ 0)**2 >> NaN :+ NaN >> >> (Is this a bug?) > According to the Standard Prelude, > # x ** y = exp (log x * y) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/55ccc64f/attachment.htm From bf3 at telenet.be Thu Aug 9 06:34:38 2007 From: bf3 at telenet.be ('Peter Verswyvelen') Date: Thu Aug 9 06:26:27 2007 Subject: [Haskell-cafe] Pure functional GUI (was "a regressive view of support for imperativeprogramming in Haskell") References: <1418427027.20070809093004@gmail.com> Message-ID: <000701c7da70$e35836b0$aa08a410$@be> LOL. Yeah you are correct I guess. Oh well ;-) -----Original Message----- From: Bulat Ziganshin [mailto:bulat.ziganshin@gmail.com] Sent: Thursday, August 09, 2007 7:30 AM To: Peter Verswyvelen Cc: Donn Cave; haskell-cafe@haskell.org Subject: Re[2]: [Haskell-cafe] Pure functional GUI (was "a regressive view of support for imperativeprogramming in Haskell") Hello Peter, Wednesday, August 8, 2007, 11:14:37 PM, you wrote: > To me, having an imperative background, a graphical application is > just a big tree of data that evolves when events from the OS come > in. (this data is NOT per se the data for the GUI element; instead > use the model-view-controller design pattern) In Haskell, instead of > mutating the data (as done in C/C++), a infinite stream of this > tree-data is generated responding to an infinite steam of events, as > in Paul's SOE book (the reactive stuff). Since most of the data can > be shared, the performance impact should be minimal. > So could you please tell me more about the problem with pure > functional GUIs seems that such program will have no effects :) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From duncan.coutts at worc.ox.ac.uk Thu Aug 9 06:53:03 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Thu Aug 9 06:43:48 2007 Subject: [Haskell-cafe] Pure functional GUI (was In-Reply-To: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> Message-ID: <1186656783.19215.6.camel@localhost> On Thu, 2007-08-09 at 08:59 +0800, Hugh Perkins wrote: > To be fair, GTK is pretty standard. This is so even for "big name" > gc'd imperative languages such as C#. Sure, you can use Windows.Forms > in C#, but you often wouldnt, because of the patent burden. > Also, gtk in partnership with glade rocks! > > How easy is gtk to use from haskell by the way? In gc'd imperative > languages, typically only one thread is allowed to communicate with > the GUI, and you need to set up a whole bunch of message-parsing stuff > to communicate with other threads. To what extent is this easier in > Haskell? The story on this isn't as nice as it could be. It depends on which GHC runtime system you choose to use. In the single threaded rts, you can use threads willy nilly as they all run in the context of one OS thread (though it requires a little bit of code to set up cooperative scheduling). In the fully threaded rts you have to be very careful to only use GUI stuff from a single OS thread. Gtk2Hs provides a couple functions to post actions to the main GUI thread. We've been thinking of ways to make this more transparent but it's not so easy. > Other question on using gtk from haskell: how easy is it to integrate > with glade? ie, can we directly bind glade form elements to haskell > variables? How easy is it to bind events to glade form elements from > within Haskell? It's pretty easy, see the Gtk2Hs/Glade tutorial: http://haskell.org/gtk2hs/docs/tutorial/glade/ Duncan From j.vimal at gmail.com Thu Aug 9 08:21:27 2007 From: j.vimal at gmail.com (Vimal) Date: Thu Aug 9 08:13:22 2007 Subject: [Haskell-cafe] Slow IO or bad code? Message-ID: Hi I am practicing writing code in haskell, by solving problems at this site. http://spoj.pl. The problem http://spoj.pl/problems/FASHION , is pretty simple. 1. Given two lists A,B , of N numbers, sort them and take sum of products. i.e. Sum ai * bi I wrote a code, but seems to give "Time limit exceeded"! >> Beginning of CODE loop t function | t == 1 = do function | otherwise = do { function; loop (t - 1) function } prod [] [] = 0 prod (a:as) (b:bs) = a*b + prod as bs to_int :: [String] -> [Integer] to_int [] = [] to_int (x:xs) = (read x) : to_int xs doit = do n <- getLine a <- getLine b <- getLine let la = to_int (words a); lb = to_int (words b); in print (prod la lb) main = do t <- getLine loop (read t) doit << END OF CODE I would love to see if there is any improvement that can be done, to the code ... Thanks! Vimal From dons at cse.unsw.edu.au Thu Aug 9 08:25:42 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Thu Aug 9 08:17:46 2007 Subject: [Haskell-cafe] Slow IO or bad code? In-Reply-To: References: Message-ID: <20070809122542.GA8318@cse.unsw.EDU.AU> j.vimal: > Hi > I am practicing writing code in haskell, by solving problems at this > site. http://spoj.pl. > The problem http://spoj.pl/problems/FASHION , is pretty simple. > > 1. Given two lists A,B , of N numbers, sort them and take sum of products. > i.e. Sum ai * bi > > I wrote a code, but seems to give "Time limit exceeded"! We have a page for these SPOJ problems: http://haskell.org/haskellwiki/SPOJ#Techniques_for_dealing_with_problems_efficiently With bytestring IO, you can aim to be around the speed of OCaml or C++, according to the existing bytestring entries. -- Don From lutz at iks-jena.de Thu Aug 9 08:38:22 2007 From: lutz at iks-jena.de (Lutz Donnerhacke) Date: Thu Aug 9 08:30:19 2007 Subject: [Haskell-cafe] Slow IO or bad code? References: Message-ID: * Vimal wrote: >>> Beginning of CODE > loop t function > | t == 1 = do function > | otherwise = do { function; loop (t - 1) function } > > prod [] [] = 0 > prod (a:as) (b:bs) = a*b + prod as bs prod = sum . zipWith (*) > to_int :: [String] -> [Integer] > to_int [] = [] > to_int (x:xs) = (read x) : to_int xs This is the slow part. Prelude.read ist really slow. Futhermore use the recusion pattern again: to_int = map read > doit = do > n <- getLine > a <- getLine > b <- getLine > let la = to_int (words a); > lb = to_int (words b); in > print (prod la lb) What is n used for? From jules at jellybean.co.uk Thu Aug 9 09:08:20 2007 From: jules at jellybean.co.uk (Jules Bean) Date: Thu Aug 9 09:00:15 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <20070808204103.GU13960@darcs.net> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> Message-ID: <46BB11C4.4060107@jellybean.co.uk> David Roundy wrote: > On Wed, Aug 08, 2007 at 02:20:39PM -0400, Paul Hudak wrote: > As long as the sugar has a pretty obvious desugaring (which I seem to > recall it did), I don't see how it's likely to make things worse. And Some people are arguing that the desugaring isn't obvious. Although I like the proposal to start with, I am beginning to be convinced by those arguments. For example: > do foo x can be simplified to > foo x under the new proposals > do x <- bar y > foo x would shorten to > do foo (<- bar y) and now you really really want to remove the do, to get simply > foo (<- bar y) but that would be illegal. The new sugar is going to remove all kinds of substitution and simplification lemmas that we have got used to. There is also the fact that if : foo x = bar x x then you call foo monadically as in do foo (<- baz) You can no longer "replace foo with its definition", because if replace that with do bar (<- baz) (<- baz) ...that means something rather different :( A third example is with nested dos: do x <- bar y baz something $ do foo x is not the same as do baz something $ do foo (<- bar y) Jules From feeder.of.the.bears at gmail.com Thu Aug 9 09:58:16 2007 From: feeder.of.the.bears at gmail.com (David Pollak) Date: Thu Aug 9 09:50:19 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <46BA0977.2040207@yale.edu> References: <46BA0977.2040207@yale.edu> Message-ID: For what it's worth from a Haskell newbie (and from someone who's been doing FP since November, mainly in Scala.) I really like Haskell's purity and having the clear separation between zero side effects and monads is most excellent. It was quite a brain change to program functionally. It took a lot of work and a lot of discipline. In Scala, I set myself the goal of not having any variables (except as instance variables of a very limited number of classes... Scala doesn't support monads), but to only use single-assignment values. At first, it was really hard to think in a new way. Now, I find that, even when I write Java code, I write in a functional style. The benefit for me is reducing the number of moving parts as well as forcing me to do significantly more design work up front. Now, the OO ideal was to model ones class hierarchy and the messages and the code will all flow automagically. In my 17 years, dozens of commercial applications, and 1M+ LoC of OO programming, it's never worked that way for me. On the other hand, programming in a state-minimized (or state-free) way makes me work a lot more to define my types and how the types interact with each other. I find that I'm spending a lot more time "up front" piecing the types together. I am spending no time worrying about hidden state (gee, if I call X before I call Y, the state will not be set up, so I have to shoe-horn some sort of test to make sure that the state is set up correctly.) I also find that my code is shorter and less dense at the same time. The "what" part of my code is easier to see because filter/map/zip constructs are a lot less distracting than "new array/for/if/..." constructs. The proof is in the output for me. My web framework (http://liftweb.net) and the commercial product that my team is building with Scala ( http://www.circleshare.com) have been remarkably stable and low in bugs. And the bugs have by and large been "logic" bugs rather than "changing X which caused a bug in Z because the state was wrong" bugs. The code bases are large enough, that I'd normally be expecting to see breakage from unexpected side effects from code changes. That hasn't started happening. Part of the challenge that Haskell and Scala and the other FP languages face is the pain developers face as they change the way they approach and solve problems. Based on my 28 years of professional coding, I think that FP is the single best and single most important technology that I've invested my time in. I think that Haskell's brand of purity is hyper-important and will allow for assembly of significantly more complex systems than will any other technology that I've seen. Please, keep to the vision. The vision is powerful, inspiring, and I believe correct. Thanks, David On 8/8/07, Paul Hudak wrote: > > All of the recent talk of support for imperative programming in Haskell > makes me really nervous. To be honest, I've always been a bit uncomfortable > even with monad syntax. Instead of: > > do x <- cmd1 > y <- cmd2 > ... > return e > > I was always perfectly happy with: > > cmd1 >>= \x-> > cmd2 >>= \y-> > ... > return e > > Functions are in my comfort zone; syntax that hides them takes me out of > my comfort zone. > > 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...". > > I hope I don't start a flame war with this post -- I'm just expressing my > opinion, which admittedly is probably regressive rather than progressive > :-). > > -Paul > > -- > Professor Paul Hudak > Department of Computer Science Office: (203) 432-1235 > Yale University FAX: (203) 432-0593 > P.O. Box 208285 email: paul.hudak@yale.edu > New Haven, CT 06520-8285 WWW: www.cs.yale.edu/~hudak > > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > -- lift, the fast, powerful, easy web framework http://liftweb.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/ac1e5e85/attachment.htm From rodrigo.bonifacio at uol.com.br Thu Aug 9 09:59:43 2007 From: rodrigo.bonifacio at uol.com.br (rodrigo.bonifacio) Date: Thu Aug 9 09:51:39 2007 Subject: [Haskell-cafe] New Eq instance Message-ID: Hello, I had defined the follwing data type: data Step = Step Id Scenario Action State Response How can I define Step as an "Eq Instance", in such way that two steps are equals if they have the same Id (Id is defined as a synonimous for the String type). I tried the following code, but something is wrong.... instance Eq Step where Step id1 scenario1 action1 state1 response1 == Step id2 scenario2 action2 state2 response2 = id == id _ == _ = False ps.: sorry, this kind of basic question can be sent to this list? Thanks in advance. Rodrigo. From j.vimal at gmail.com Thu Aug 9 10:05:31 2007 From: j.vimal at gmail.com (Vimal) Date: Thu Aug 9 09:57:26 2007 Subject: [Haskell-cafe] Slow IO or bad code? In-Reply-To: References: Message-ID: @Donald: Thanks for the link. > prod = sum . zipWith (*) > > This is the slow part. Prelude.read ist really slow. > > Futhermore use the recusion pattern again: > to_int = map read > > What is n used for? @Lutz: Those are some nice tricks... Thanks! Now, the 'n' is for getting the number of numbers in the list. Which I don't need, since I had a way around it. I just had to skip that line... From Alistair_Bayley at invescoperpetual.co.uk Thu Aug 9 10:11:05 2007 From: Alistair_Bayley at invescoperpetual.co.uk (Bayley, Alistair) Date: Thu Aug 9 10:03:00 2007 Subject: [Haskell-cafe] New Eq instance In-Reply-To: References: Message-ID: <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0A@GBLONXMB02.corp.amvescap.net> > From: haskell-cafe-bounces@haskell.org > [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of > rodrigo.bonifacio > > data Step = Step Id Scenario Action State Response > > How can I define Step as an "Eq Instance", in such way that > two steps are equals if they have the same Id (Id is defined > as a synonimous for the String type). > > I tried the following code, but something is wrong.... > > instance Eq Step where > Step id1 scenario1 action1 state1 response1 == Step id2 > scenario2 action2 state2 response2 = id == id > _ == _ = False What error messages are you getting? Anyway, you have the right idea, you just need a bit of cleaning up and correct syntax. As I don't have your definitions for Scenario, Action, etc, I'll just ignore them (we don't need them for your Eq anyway): > data Step = Step String String > instance Eq Step where > Step id1 _ == Step id2 _ = id1 == id2 Note: - the _ == _ case will never be reached (AFAICT) - I assume " = id == id" is a typo, and that you intended "id1 == id2" Alistair ***************************************************************** Confidentiality Note: The information contained in this message, and any attachments, may contain confidential and/or privileged material. It is intended solely for the person(s) or entity to which it is addressed. Any review, retransmission, dissemination, or taking of any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you received this in error, please contact the sender and delete the material from any computer. ***************************************************************** From marco-oweber at gmx.de Thu Aug 9 10:27:22 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Thu Aug 9 10:19:18 2007 Subject: [Haskell-cafe] Slow IO or bad code? In-Reply-To: References: Message-ID: <20070809142722.GA18563@gmx.de> > I wrote a code, but seems to give "Time limit exceeded"! ?? Your code writes 15 to stdout which is correct (with the example given on the page).. You have to explain what you mean by >>seems to give "Time limit exceeded"<< > loop t function Does already exist. sequence $ replicate 10 function is a much shorter way :-) oor perhaps mapM_ [ function | i <- [1..10] ] ) prod, to_int: You can both implement using higher order functions prod = sum . zipWith (*) to_int = map read Marc From jules at jellybean.co.uk Thu Aug 9 10:34:02 2007 From: jules at jellybean.co.uk (Jules Bean) Date: Thu Aug 9 10:25:59 2007 Subject: [Haskell-cafe] New Eq instance In-Reply-To: References: Message-ID: <46BB25DA.8010105@jellybean.co.uk> rodrigo.bonifacio wrote: > > instance Eq Step where > Step id1 scenario1 action1 state1 response1 == Step id2 scenario2 action2 state2 response2 = id == id > _ == _ = False Almost. You just used 'id' and 'id' when you meant 'id1' and 'id2'. > instance Eq Step where > Step id1 scenario1 action1 state1 response1 == Step id2 scenario2 action2 state2 response2 = id1 == id2 but it's a common idiom not to bother to name unused parameters, so: > instance Eq Step where > Step id1 _ _ _ _ == Step id2 _ _ _ _ = id1 == id2 (and the default case is never reached so you don't need it) > > ps.: sorry, this kind of basic question can be sent to this list? Yes, that's fine. You may get quicker answers if you hop onto IRC at #haskell, though. Jules From byorgey at gmail.com Thu Aug 9 11:24:52 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Thu Aug 9 11:16:47 2007 Subject: [Haskell-cafe] Slow IO or bad code? In-Reply-To: <20070809142722.GA18563@gmx.de> References: <20070809142722.GA18563@gmx.de> Message-ID: <22fcbd520708090824g495995avf1ac06862a6171b1@mail.gmail.com> On 8/9/07, Marc Weber wrote: > > > I wrote a code, but seems to give "Time limit exceeded"! > ?? > Your code writes > 15 to stdout which is correct (with the example given on the page).. > You have to explain what you mean by >>seems to give "Time limit > exceeded"<< > I think Vimal is referring to a message from SPOJ rather than the compiler. I.e. the program runs too slowly so it is rejected by the judging software. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/3c8eb2fe/attachment.htm From ithika at gmail.com Thu Aug 9 11:57:26 2007 From: ithika at gmail.com (Dougal Stanton) Date: Thu Aug 9 11:49:21 2007 Subject: [Haskell-cafe] Derivation of Eq given Ord Message-ID: <2d3641330708090857x25e082c1q89763f2335b5f6e0@mail.gmail.com> Is there a reason why automatic derivation of Ord without Eq doesn't do "the sensible thing" and just derive Eq anyway? > newtype Id a = Id { a :: String } > deriving (Read, Show, Eq, Ord) > newtype Ego a = Ego { b :: String } > deriving (Read, Show, Ord) Both will type check, but if you try any (in)equality operators on the second they'll be spat back at you. > *Main> let e1 = Ego "" > *Main> let e2 = Ego "" > *Main> e1 < e2 > > :1:0: > No instance for (Eq (Ego a)) > arising from use of `<' at :1:0-6 > Possible fix: add an instance declaration for (Eq (Ego a)) > In the expression: e1 < e2 > In the definition of `it': it = e1 < e2 It doesn't seem *much* of a hardship, but it wasn't what I expected. I'm not used to GHC accepting input and silently dropping stuff it doesn't like... Cheers, D. From chaddai.fouche at gmail.com Thu Aug 9 12:10:52 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Thu Aug 9 12:02:48 2007 Subject: [Haskell-cafe] Slow IO or bad code? In-Reply-To: <22fcbd520708090824g495995avf1ac06862a6171b1@mail.gmail.com> References: <20070809142722.GA18563@gmx.de> <22fcbd520708090824g495995avf1ac06862a6171b1@mail.gmail.com> Message-ID: I get "Wrong answer" with the following code for the same problem... Is there something strange in this code : module Main where import qualified Data.ByteString.Char8 as B main = B.getLine >>= sequence_ . flip replicate hot . maybe 0 fst . B.readInt hot = do B.getLine men <- B.getLine women <- B.getLine print $ sum $ zipWith (*) (map (maybe 0 fst . B.readInt) $ B.words men) (map (maybe 0 fst . B.readInt) $ B.words women) ??? I get the expected results with my tests. -- Jeda? From thomas.hartman at db.com Thu Aug 9 12:12:27 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Thu Aug 9 12:04:24 2007 Subject: [Haskell-cafe] (no subject) Message-ID: In the following code which uses template haskell, how can I get back the macro-expanded code generated from $(inferStartState ''MyState) I *can* recover the macro-expanded code for $(cnst 1 "x") using a debugging technique bulat describes on his tutorial at http://www.haskell.org/bz/th3.htm You can see what's going on in the function debugTemplates below. I'm trying to do this actually, to better understand how HAppS deals with state. It's a bit opaque now since the example on the tutorial uses TH. I think I would understand it better if I had code that didn't depend on TH. (MyState is from the happs tutorial at http://www.haskell.org/haskellwiki/HAppS_tutorial ) thanks! thomas. {-# OPTIONS -fglasgow-exts -fth #-} module MyState where import HAppS import HAppS.Protocols.SimpleHTTP2 import Data.Monoid import Data.Typeable import Control.Monad.State (get, put) import Language.Haskell.TH import Language.Haskell.TH.Syntax data MyState = MySt { appVal :: Int } deriving (Read, Show, Typeable) instance Serialize MyState where encodeStringM = defaultEncodeStringM decodeStringM = defaultDecodeStringM instance Monoid MyState where mempty = MySt 0 mappend (MySt x) (MySt y) = MySt (x+y) -- in ghci... -fth, :m + -- ghci... :t (inferStartState ''MyState) :: (Quasi m) => m [Dec] $(inferStartState ''MyState) -- boilerplate that will eventually be SYB -- ghci... :t cnst 1 "x" :: (Monad m) => m Exp cnst n s = return (LamE (replicate n WildP) (LitE (StringL s))) dumpSplice splice = runQ splice >>= putStrLn . pprint debugTemplates = do dumpSplice (cnst 1 "x") dumpSplice (inferStartState ''MyState) {- *MyState> debugTemplates \_ -> "x" Template Haskell error: Can't do `reify' in the IO monad *** Exception: user error (Template Haskell failure) -} --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/cb795cd4/attachment.htm From malte at gmx-topmail.de Thu Aug 9 12:20:57 2007 From: malte at gmx-topmail.de (Malte Milatz) Date: Thu Aug 9 12:10:05 2007 Subject: [Haskell-cafe] Derivation of Eq given Ord In-Reply-To: <2d3641330708090857x25e082c1q89763f2335b5f6e0@mail.gmail.com> References: <2d3641330708090857x25e082c1q89763f2335b5f6e0@mail.gmail.com> Message-ID: <20070809182057.6d009ec2@aligatoro.ret> Dougal Stanton, Thu, 9 Aug 2007 16:57:26 +0100: > Is there a reason why automatic derivation of Ord without Eq doesn't > do "the sensible thing" and just derive Eq anyway? > > > newtype Id a = Id { a :: String } > > deriving (Read, Show, Eq, Ord) > > newtype Ego a = Ego { b :: String } > > deriving (Read, Show, Ord) > > Both will type check, but if you try any (in)equality operators on the > second they'll be spat back at you. According to the output of ghci's info command, deriving Ord without deriving Eq is equivalent to instance Eq Ego => Eq Ord where ... That is, if there's an Eq instance declaration for Ego, then Ego will be an instance of Ord, too. This may come in handy if you want to declare the Eq instance yourself, possibly even in another module. The compiler cannot know about instances you're up to declare in other places, so it would probably not be convenient for the compiler to derive Eq behind the scenes. > It doesn't seem *much* of a hardship, but it wasn't what I expected. > I'm not used to GHC accepting input and silently dropping stuff it > doesn't like... Well, obviously, you will still get a type error when trying to use the instance without an Eq instance declaration, so it is not really a matter of ?silently dropping stuff?, I suppose. Malte From thomas.hartman at db.com Thu Aug 9 12:23:35 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Thu Aug 9 12:15:35 2007 Subject: [Haskell-cafe] how can I get template haskell macro-expanded code from inferStartState? (repeated post, now with subject) Message-ID: (sorry, forgot the subject on my first post) In the following code which uses template haskell, how can I get back the macro-expanded code generated from $(inferStartState ''MyState) I *can* recover the macro-expanded code for $(cnst 1 "x") using a debugging technique bulat describes on his tutorial at http://www.haskell.org/bz/th3.htm You can see what's going on in the function debugTemplates below. I'm trying to do this actually, to better understand how HAppS deals with state. It's a bit opaque now since the example on the tutorial uses TH. I think I would understand it better if I had code that didn't depend on TH. (MyState is from the happs tutorial at http://www.haskell.org/haskellwiki/HAppS_tutorial ) thanks! thomas. {-# OPTIONS -fglasgow-exts -fth #-} module MyState where import HAppS import HAppS.Protocols.SimpleHTTP2 import Data.Monoid import Data.Typeable import Control.Monad.State (get, put) import Language.Haskell.TH import Language.Haskell.TH.Syntax data MyState = MySt { appVal :: Int } deriving (Read, Show, Typeable) instance Serialize MyState where encodeStringM = defaultEncodeStringM decodeStringM = defaultDecodeStringM instance Monoid MyState where mempty = MySt 0 mappend (MySt x) (MySt y) = MySt (x+y) -- in ghci... -fth, :m + -- ghci... :t (inferStartState ''MyState) :: (Quasi m) => m [Dec] $(inferStartState ''MyState) -- boilerplate that will eventually be SYB -- ghci... :t cnst 1 "x" :: (Monad m) => m Exp cnst n s = return (LamE (replicate n WildP) (LitE (StringL s))) dumpSplice splice = runQ splice >>= putStrLn . pprint debugTemplates = do dumpSplice (cnst 1 "x") dumpSplice (inferStartState ''MyState) {- *MyState> debugTemplates \_ -> "x" Template Haskell error: Can't do `reify' in the IO monad *** Exception: user error (Template Haskell failure) -} --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/5f128025/attachment-0001.htm From Andreas-Haskell at gmx.net Thu Aug 9 12:26:30 2007 From: Andreas-Haskell at gmx.net (Andreas Marth) Date: Thu Aug 9 12:25:08 2007 Subject: [Haskell-cafe] Derivation of Eq given Ord References: <2d3641330708090857x25e082c1q89763f2335b5f6e0@mail.gmail.com> Message-ID: <2b4b01c7daa2$1df21530$6702a8c0@GPO> I would say that qualifies as a bug because it relays an error from compile time to run time. Andreas ----- Original Message ----- From: "Dougal Stanton" To: "haskell-cafe" Sent: Thursday, August 09, 2007 5:57 PM Subject: [Haskell-cafe] Derivation of Eq given Ord > Is there a reason why automatic derivation of Ord without Eq doesn't > do "the sensible thing" and just derive Eq anyway? > > > newtype Id a = Id { a :: String } > > deriving (Read, Show, Eq, Ord) > > newtype Ego a = Ego { b :: String } > > deriving (Read, Show, Ord) > > Both will type check, but if you try any (in)equality operators on the > second they'll be spat back at you. > > > *Main> let e1 = Ego "" > > *Main> let e2 = Ego "" > > *Main> e1 < e2 > > > > :1:0: > > No instance for (Eq (Ego a)) > > arising from use of `<' at :1:0-6 > > Possible fix: add an instance declaration for (Eq (Ego a)) > > In the expression: e1 < e2 > > In the definition of `it': it = e1 < e2 > > It doesn't seem *much* of a hardship, but it wasn't what I expected. > I'm not used to GHC accepting input and silently dropping stuff it > doesn't like... > > Cheers, > > D. > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From chaddai.fouche at gmail.com Thu Aug 9 12:35:22 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Thu Aug 9 12:27:20 2007 Subject: [Haskell-cafe] Slow IO or bad code? In-Reply-To: References: <20070809142722.GA18563@gmx.de> <22fcbd520708090824g495995avf1ac06862a6171b1@mail.gmail.com> Message-ID: Note that this code isn't more successful, clearly I have misunderstood one requirement : import qualified Data.ByteString.Char8 as B import Data.List (unfoldr) main = B.interact $ hot hot = B.unlines . map (B.pack . show) . processList . tail . unfoldr readInt1 readInt1 cs = do (n, cs') <- B.readInt cs return (n, B.tail cs') processList [] = [] processList (x:xs) = (sum $ zipWith (*) men women) : processList rest where (men,r1) = splitAt x xs (women,rest) = splitAt x r1 -- Jeda? From malte at gmx-topmail.de Thu Aug 9 12:47:04 2007 From: malte at gmx-topmail.de (Malte Milatz) Date: Thu Aug 9 12:36:02 2007 Subject: [Haskell-cafe] Derivation of Eq given Ord In-Reply-To: <20070809182057.6d009ec2@aligatoro.ret> References: <2d3641330708090857x25e082c1q89763f2335b5f6e0@mail.gmail.com> <20070809182057.6d009ec2@aligatoro.ret> Message-ID: <20070809184704.530fc916@aligatoro.ret> I wrote: > instance Eq Ego => Eq Ord where ... This should have been instance Eq (Ego a) => Ord (Ego a) Malte From brian.brunswick at gmail.com Thu Aug 9 13:28:16 2007 From: brian.brunswick at gmail.com (Brian Brunswick) Date: Thu Aug 9 13:20:11 2007 Subject: [Haskell-cafe] how can I get template haskell macro-expanded code from inferStartState? (repeated post, now with subject) In-Reply-To: References: Message-ID: <6f680f6d0708091028xe140d91ha77306b25466d6c0@mail.gmail.com> On 09/08/07, Thomas Hartman wrote: > > (sorry, forgot the subject on my first post) > > In the following code which uses template haskell, how can I get back the > macro-expanded code generated from > > $(inferStartState ''MyState) > I just recently used ghc -ddump-splices to debug this very same problem. It turns out to be due to overlapping instances - inferStartState generates a (from memory) specific StartStateEx instance, but actually theres a general StartState => StartStateEx, and also a general Monoid=>StartState instance, and thats why the error message mentions Monoid. I guess this teaches us the reason that overlapping instances are bad: ***They don't work across modules**** Another module can add an instance which wasn't visible when a first module was compiled, and the two modules end up using different instances than expected. I've been meaning to start trying to contribute to improving the HAppS documentation, since its been such a struggle to start learning it. So the question to the HAppS people is, where is the canonical place for this documentation, where should one work? Is it the wiki page above, or the stuff inside the HAppS repository? -- Brian_Brunswick____brian@ithil.org____Wit____Disclaimer____!Shortsig_rules! From andrewcoppin at btinternet.com Thu Aug 9 13:30:57 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 9 13:22:19 2007 Subject: [Haskell-cafe] Pure functional GUI In-Reply-To: <1186656783.19215.6.camel@localhost> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> <1186656783.19215.6.camel@localhost> Message-ID: <46BB4F51.4090801@btinternet.com> Duncan Coutts wrote: > On Thu, 2007-08-09 at 08:59 +0800, Hugh Perkins wrote: > >> uestion on using gtk from haskell: how easy is it to integrate >> with glade? ie, can we directly bind glade form elements to haskell >> variables? How easy is it to bind events to glade form elements from >> within Haskell? >> > > It's pretty easy, see the Gtk2Hs/Glade tutorial: > > http://haskell.org/gtk2hs/docs/tutorial/glade/ > Indeed - the *hard* part seems to be figuring out how to run Glade on Windoze... From andrewcoppin at btinternet.com Thu Aug 9 13:37:32 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 9 13:28:54 2007 Subject: [Haskell-cafe] Small question Message-ID: <46BB50DC.8020404@btinternet.com> Which of these is likely to go faster? type Quad = (Bool,Bool) foo (r,t) = let x = if r ... y = if t ... in ... data Quad = BL | BR | TL | TR foo q = let x = if q == TL | q == TR ... y = if q == BR | q == TR ... in ... (Unless somebody has a better idea...) I'm hoping that the latter one will more more strict / use less space. But I don't truely know... From andrewcoppin at btinternet.com Thu Aug 9 13:47:04 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 9 13:38:26 2007 Subject: [Haskell-cafe] Matters of precision Message-ID: <46BB5318.7080904@btinternet.com> Hi folks. I'm trying to write a Mandelbrot generator, and I've having a few problems with precision. First of all, currently I'm just using Double to represent coordinates. Can anybody tell me what the smallest value you can represent with one is? (Not including denormals.) (I've built a function that checks for cycles in the orbit - by looking for previous points that are sufficiently "near" to the current one. But I want to know how much precision a Double gives me so I can figure out how near is "near".) Next up, at some point I'm going to need more precision than a Double can give me. (But, obviously, I still want the thing to go as fast as humanly possible.) In particular, I do NOT want to go into "infinite" precision. (E.g., exact arithmetic with arbitrary fractions.) I want to be able to make the precision arbitrarily high, but still finite and fixed. (The idea being that the further you zoom in, the more the computer turns up the precision.) Is there anything useful for this in the standard libraries? Or will I have to write something? From bf3 at telenet.be Thu Aug 9 14:07:02 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Thu Aug 9 14:02:39 2007 Subject: [Haskell-cafe] Problem with question 3 about knights and knaves on wikipedia Message-ID: <004701c7dab0$165f92d0$431eb870$@be> I was writing some haskell code for fun to solve some "knights and knaves" problems, and I have troubles with http://en.wikipedia.org/wiki/Knights_and_knaves#Question_3 So knights always tell the truth and knaves always lie. John and Bill are two persons, but you don't know what they are, and you have to find out. Question 3 You: Are you both knights? John: answers either Yes or No, but you don't have enough information to solve the problem. You: Are you both knaves? John: answers either Yes or No, and you can now solve the problem. My haskell code gave the following result: --(what is john, what is bill, first answer from john, second answer from john) ("John is a knight","Bill is a knight","Yes","No ") ("John is a knight","Bill is a knave ","No ","No ") ("John is a knave ","Bill is a knight","Yes","Yes") ("John is a knave ","Bill is a knave ","Yes","No ") Anyone has an idea what I missed here? Thanks, Peter PS: The (quick and dirty) haskell code I wrote for this is: infixl 1 <=> infixl 1 ==> -- Equivalence x <=> y = (x == y) -- Implication True ==> False = False _ ==> _ = True -- Knights tell the truth name `isa` True = name ++ " is a knight" -- Knaves always lie name `isa` False = name ++ " is a knave " answer True = "Yes" answer False = "No " --Logician: Are you both knights? --John answers either Yes or No, but the Logician does not have enough information to solve the problem. --Logician: Are you both knaves? --John answers either Yes or No, and the Logician can now solve the problem. condition j b answer1 answer2 = (j <=> ((b && j) == answer1)) && (j <=> ((not b && not j) == answer2)) solution = [("John" `isa` j, "Bill" `isa` b, answer answer1, answer answer2) | j <- [True,False], b <- [True, False], answer1 <- [True, False], answer2 <- [True, False], condition j b answer1 answer2 ] main = mapM_ putStrLn (map show solution) From sebastian.sylvan at gmail.com Thu Aug 9 14:12:12 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Thu Aug 9 14:04:10 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <46BB50DC.8020404@btinternet.com> References: <46BB50DC.8020404@btinternet.com> Message-ID: <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> On 09/08/07, Andrew Coppin wrote: > Which of these is likely to go faster? > > type Quad = (Bool,Bool) > > foo (r,t) = > let > x = if r ... > y = if t ... > in ... > > > > data Quad = BL | BR | TL | TR > > foo q = > let > x = if q == TL | q == TR ... > y = if q == BR | q == TR ... > in ... > > > > (Unless somebody has a better idea...) > > I'm hoping that the latter one will more more strict / use less space. > But I don't truely know... > Sounds like the perfect candidate for a benchmark, then! Another tool for your toolbox: {-#OPTIONS -funbox-strict-fields #-} data Quad = Quad !Bool !Bool foo True True = ... foo True False = .... ... etc... The GHC option just causese GHC to unbox primitive types when they're strict in the data type, and the bangs cause them to be strict. -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From stefanor at cox.net Thu Aug 9 14:16:37 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 9 14:08:36 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> Message-ID: <20070809181637.GA3716@localhost.localdomain> On Thu, Aug 09, 2007 at 07:12:12PM +0100, Sebastian Sylvan wrote: > {-#OPTIONS -funbox-strict-fields #-} > > data Quad = Quad !Bool !Bool > > foo True True = ... > foo True False = .... > ... etc... > > > The GHC option just causese GHC to unbox primitive types when they're > strict in the data type, and the bangs cause them to be strict. Unfortunately, Bool is not a sufficiently primitive type for that to work. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/16c74077/attachment-0001.bin From isaacdupree at charter.net Thu Aug 9 14:06:54 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Thu Aug 9 14:09:05 2007 Subject: [Haskell-cafe] Derivation of Eq given Ord In-Reply-To: <2b4b01c7daa2$1df21530$6702a8c0@GPO> References: <2d3641330708090857x25e082c1q89763f2335b5f6e0@mail.gmail.com> <2b4b01c7daa2$1df21530$6702a8c0@GPO> Message-ID: <46BB57BE.9000601@charter.net> Andreas Marth wrote: > I would say that qualifies as a bug because it relays an error from compile > time to run time. It doesn't relay anything to run time - ghci has to _compile_ the expressions you give it too. If you _compile something_ successfully, you will know that _it_ will not fail in the stated way (which is all you need to know for a normal program with 'main'). However it does relay an error from deriving module to using [module/ghci], which may not be right. HOWEVER, I can't reproduce it - ghc (6.6.1) always tells me No instance for (Eq Foo) arising from the superclasses of an instance declaration whether data or newtype, deriving Ord, no Eq instance, and no using operations at all, and Hugs does too (in different words). Isaac From byorgey at gmail.com Thu Aug 9 14:17:23 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Thu Aug 9 14:09:19 2007 Subject: [Haskell-cafe] Slow IO or bad code? In-Reply-To: References: <20070809142722.GA18563@gmx.de> <22fcbd520708090824g495995avf1ac06862a6171b1@mail.gmail.com> Message-ID: <22fcbd520708091117r8e500dcv62404d0980ff3030@mail.gmail.com> On 8/9/07, Chadda? Fouch? wrote: > > I get "Wrong answer" with the following code for the same problem... > Is there something strange in this code : This problem description is not worded very well. You have to figure out the matching that maximizes the sum of hotnesses; you don't necessarily just do a sum . zipWith (*). -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/8ab58fcb/attachment.htm From benjamin.franksen at bessy.de Thu Aug 9 14:18:25 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Thu Aug 9 14:10:30 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell References: <46BA0977.2040207@yale.edu> Message-ID: Donn Cave wrote: > (I have a soft spot for O'Haskell, but > alas I must be nearly alone on that.) You are /not/ alone :-) I always found it very sad that O'Haskell and also its sucessor Timber (with all the good real-time stuff added) died the 'quick death' of most research languages. Cheers Ben From rodrigo.bonifacio at uol.com.br Thu Aug 9 14:19:51 2007 From: rodrigo.bonifacio at uol.com.br (rodrigo.bonifacio) Date: Thu Aug 9 14:11:45 2007 Subject: [Haskell-cafe] Operator overloading Message-ID: Hi all. I want to overload the operator "^" for working instead of the following "+++" operator: (+++) :: String -> [[String]] -> [[String]] x +++ y = [ x:e | e<-y ] How can I overload the "^" operator? Thanks a lot. Rodrigo. From bulat.ziganshin at gmail.com Thu Aug 9 14:20:32 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 9 14:13:13 2007 Subject: [Haskell-cafe] (no subject) In-Reply-To: References: Message-ID: <189286548.20070809222032@gmail.com> Hello Thomas, Thursday, August 9, 2007, 8:12:27 PM, you wrote: > In the following code which uses template haskell, how can I get > back the macro-expanded code generated from citating http://www.haskell.org/bz/thdoc.htm : In order to make debugging Template Haskell programs easier, compiler supports flag -ddump-splices, which shows the expansion of all top-level splices as they happen. -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From steve at fenestra.com Thu Aug 9 14:21:55 2007 From: steve at fenestra.com (Steve Schafer) Date: Thu Aug 9 14:13:49 2007 Subject: [Haskell-cafe] Problem with question 3 about knights and knaves onw ikipedia In-Reply-To: <004701c7dab0$165f92d0$431eb870$@be> References: <004701c7dab0$165f92d0$431eb870$@be> Message-ID: On Thu, 9 Aug 2007 20:07:02 +0200, you wrote: >("John is a knight","Bill is a knight","Yes","No ") >("John is a knight","Bill is a knave ","No ","No ") >("John is a knave ","Bill is a knight","Yes","Yes") >("John is a knave ","Bill is a knave ","Yes","No ") > >Anyone has an idea what I missed here? You're missing a key element of the problem: After John answers the first question, the Logician doesn't have enough information to solve the problem. Think about that for a second, and you will see the light. Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ From sebastian.sylvan at gmail.com Thu Aug 9 14:28:41 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Thu Aug 9 14:20:37 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070809181637.GA3716@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> Message-ID: <3d96ac180708091128q2ab89f3cj80e424c6c2bc2ddc@mail.gmail.com> On 09/08/07, Stefan O'Rear wrote: > On Thu, Aug 09, 2007 at 07:12:12PM +0100, Sebastian Sylvan wrote: > > {-#OPTIONS -funbox-strict-fields #-} > > > > data Quad = Quad !Bool !Bool > > > > foo True True = ... > > foo True False = .... > > ... etc... > > > > > > The GHC option just causese GHC to unbox primitive types when they're > > strict in the data type, and the bangs cause them to be strict. > > Unfortunately, Bool is not a sufficiently primitive type for that to > work. Ah good point. Well I'd guess a Word8 would do (might be faster to use a Word32 or Word64 depending on your machine though?). -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From bf3 at telenet.be Thu Aug 9 14:29:27 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Thu Aug 9 14:21:15 2007 Subject: [Haskell-cafe] Pure functional GUI In-Reply-To: <46BB4F51.4090801@btinternet.com> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> <1186656783.19215.6.camel@localhost> <46BB4F51.4090801@btinternet.com> Message-ID: <004f01c7dab3$37d75ad0$a7861070$@be> > Indeed - the *hard* part seems to be figuring out how to run Glade on Windoze... I did not dare to ask this question because I could not believe this was hard... So anybody know how to do this? Run Glade on Window$? -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Andrew Coppin Sent: Thursday, August 09, 2007 7:31 PM To: haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] Pure functional GUI Duncan Coutts wrote: > On Thu, 2007-08-09 at 08:59 +0800, Hugh Perkins wrote: > >> uestion on using gtk from haskell: how easy is it to integrate >> with glade? ie, can we directly bind glade form elements to haskell >> variables? How easy is it to bind events to glade form elements from >> within Haskell? >> > > It's pretty easy, see the Gtk2Hs/Glade tutorial: > > http://haskell.org/gtk2hs/docs/tutorial/glade/ > Indeed - the *hard* part seems to be figuring out how to run Glade on Windoze... _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From byorgey at gmail.com Thu Aug 9 14:32:54 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Thu Aug 9 14:24:49 2007 Subject: [Haskell-cafe] Operator overloading In-Reply-To: References: Message-ID: <22fcbd520708091132r6a56238cr7f46430c85615b8f@mail.gmail.com> On 8/9/07, rodrigo.bonifacio wrote: > > Hi all. > > I want to overload the operator "^" for working instead of the following > "+++" operator: > > (+++) :: String -> [[String]] -> [[String]] > x +++ y = [ x:e | e<-y ] > > How can I overload the "^" operator? import Prelude hiding ( (^) ) -- this is the key (^) :: String -> [[String]] -> [[String]] x ^ y = [ x:e | e<-y ] By the way, there's nothing special about Strings here: if you made the type of ^ (^) :: a -> [[a]] -> [[a]] it would work on lists of any type, including String. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/1e178ede/attachment.htm From droundy at darcs.net Thu Aug 9 14:42:12 2007 From: droundy at darcs.net (David Roundy) Date: Thu Aug 9 14:34:08 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <235177FA-A63E-4268-8A94-83C286BA4DD3@cs.otago.ac.nz> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <235177FA-A63E-4268-8A94-83C286BA4DD3@cs.otago.ac.nz> Message-ID: <20070809184207.GD30903@darcs.net> On Thu, Aug 09, 2007 at 04:02:05PM +1200, ok wrote: > On 9 Aug 2007, at 8:41 am, David Roundy wrote: > >I may be stating the obvious here, but I strongly prefer the do syntax. > >It's nice to know the other also, but the combination of do +indenting > >makes complicated code much clearer than the nested parentheses that > >would be required with purely >>= syntax. > > Er, what nested parentheses would those be? do x1 <- e1 if x1 then do x2 <- e2 xx <- if x2 then e3 else do x4 <- e4 x5 <- e5 e6 x4 x5 e7 xx x1 else do x8 <- e8 x9 <- e9 e10 x8 x9 x1 x11 would become something like e1 >>= \x1 -> if x1 then e2 >>= \x2 -> if x2 then e3 else e4 >>= \x4 -> e5 >>= \x5 -> e6 x4 x5 >>= (flip e7) x1 else e8 >>= \x8 -> e9 >>= \x9 -> e10 x8 x9 x1 >> x11 except that you'd have to figure out where to add parentheses. I'm sure I'd end up writing extra parentheses, but if you put in the minimal number of parentheses, then I doubt I'd be able to read the code. If you only consider the case of trivial code, then you're right, there are no extra parentheses required. This is the beauty of the do notation, it allows one to write actual real complicated monadic code in a form that is actually comprehensible. -- David Roundy Department of Physics Oregon State University From benjamin.franksen at bessy.de Thu Aug 9 14:45:14 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Thu Aug 9 14:37:25 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> Message-ID: David Roundy wrote: > Several times since reading the beginning of this discussion I've wished I > had the new syntax so I could write something like: > > do if predicateOnFileContents (<- readFile "foo") then ... > > instead of either > > do contents <- readFile "foo" > if predicateOnFileContents contents then ... > > or (as you'd prefer) > > readFile "foo" >>= \contents -> > if predicateOnFileContents contents then ... Isn't this problem, namely being forced to name intermediate results, also solved by some sort of idiom bracket sugar, maybe together with the lambda case proposal? I would prefer both very much to the proposed (<- action) syntax for the same reasons that e.g. Jules Bean nicely summarized. Cheers Ben From droundy at darcs.net Thu Aug 9 14:52:17 2007 From: droundy at darcs.net (David Roundy) Date: Thu Aug 9 14:44:17 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <46BB11C4.4060107@jellybean.co.uk> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <46BB11C4.4060107@jellybean.co.uk> Message-ID: <20070809185217.GE30903@darcs.net> On Thu, Aug 09, 2007 at 02:08:20PM +0100, Jules Bean wrote: > David Roundy wrote: > >On Wed, Aug 08, 2007 at 02:20:39PM -0400, Paul Hudak wrote: > >As long as the sugar has a pretty obvious desugaring (which I seem to > >recall it did), I don't see how it's likely to make things worse. And > > Some people are arguing that the desugaring isn't obvious. That's a reasonable objection (although I disagree). > Although I like the proposal to start with, I am beginning to be > convinced by those arguments. > > For example: > > > do foo x > > can be simplified to > > > foo x > > under the new proposals > > > do x <- bar y > > foo x > > would shorten to > > > do foo (<- bar y) > > and now you really really want to remove the do, to get simply > > > foo (<- bar y) > > but that would be illegal. The new sugar is going to remove all kinds of > substitution and simplification lemmas that we have got used to. I guess I'd just have to argue that like the <- notation, the (<- ) notation is *part* of the do notation. Just as you can't pull a <- out of a do loop and expect it to behave identically, you can't do the same with a (<- ). To me, the similarity with existing do-dependent syntax (and it helps that except for pattern guards, <- is *only* used within a do block. > There is also the fact that if : > > foo x = bar x x > > then you call foo monadically as in > > do foo (<- baz) > > You can no longer "replace foo with its definition", because if replace > that with > > do bar (<- baz) (<- baz) > > ...that means something rather different :( Again, this seems obvious, and it doesn't seem like "replace foo with its definition" is something I think of. > A third example is with nested dos: > > do x <- bar y > baz > something $ do foo x > > is not the same as > > do baz > something $ do foo (<- bar y) Again, it all comes down to whether the "find the nearest do" is obvious. It seems pretty obvious to me. And I like the idea of someone just implementing this, and then those of us to whom it appeals can try it. I've longed for something like this (mostly for monadic ifs and cases) for quite a while now... -- David Roundy Department of Physics Oregon State University From zednenem at psualum.com Thu Aug 9 14:56:47 2007 From: zednenem at psualum.com (David Menendez) Date: Thu Aug 9 14:48:41 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell In-Reply-To: References: <46BA0977.2040207@yale.edu> Message-ID: <49a77b7a0708091156l38327aabua7550a1c290d3505@mail.gmail.com> On 8/9/07, Benjamin Franksen wrote: > Donn Cave wrote: > > (I have a soft spot for O'Haskell, but > > alas I must be nearly alone on that.) > > You are /not/ alone :-) I always found it very sad that O'Haskell and also > its sucessor Timber (with all the good real-time stuff added) died > the 'quick death' of most research languages. There is also RHaskell, which implements an O'Haskell-like system as a Haskell library. From droundy at darcs.net Thu Aug 9 14:56:59 2007 From: droundy at darcs.net (David Roundy) Date: Thu Aug 9 14:48:57 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell In-Reply-To: References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> Message-ID: <20070809185658.GF30903@darcs.net> On Thu, Aug 09, 2007 at 08:45:14PM +0200, Benjamin Franksen wrote: > David Roundy wrote: > > Several times since reading the beginning of this discussion I've wished I > > had the new syntax so I could write something like: > > > > do if predicateOnFileContents (<- readFile "foo") then ... > > > > instead of either > > > > do contents <- readFile "foo" > > if predicateOnFileContents contents then ... > > > > or (as you'd prefer) > > > > readFile "foo" >>= \contents -> > > if predicateOnFileContents contents then ... > > Isn't this problem, namely being forced to name intermediate results, also > solved by some sort of idiom bracket sugar, maybe together with the lambda > case proposal? I would prefer both very much to the proposed (<- action) > syntax for the same reasons that e.g. Jules Bean nicely summarized. I'm not familiar with the lambda case proposal, and don't know what you mean by idiom bracket sugar, but I haven't had an idea (or heard of one) that was nearly so elegant as the (<- action) proposal, which neatly allows one to lift any existing pure function or syntactic construct (except lambda expressions?) into a monad. i.e. we don't need to define a separate 'if', 'case', etc, and we don't need liftM, liftM2, liftM3, liftM4andahalf, all of which are subsumed by a single pretty syntax. The only cost is that this syntax relies on the do notation, and thus makes the desugaring of that do notation slightly more complicated when used. -- David Roundy Department of Physics Oregon State University From j.vimal at gmail.com Thu Aug 9 15:08:59 2007 From: j.vimal at gmail.com (Vimal) Date: Thu Aug 9 15:00:53 2007 Subject: [Haskell-cafe] Slow IO or bad code? In-Reply-To: <22fcbd520708091117r8e500dcv62404d0980ff3030@mail.gmail.com> References: <20070809142722.GA18563@gmx.de> <22fcbd520708090824g495995avf1ac06862a6171b1@mail.gmail.com> <22fcbd520708091117r8e500dcv62404d0980ff3030@mail.gmail.com> Message-ID: On 8/9/07, Brent Yorgey wrote: > On 8/9/07, Chadda? Fouch? wrote: > > I get "Wrong answer" with the following code for the same problem... > > Is there something strange in this code : > > This problem description is not worded very well. You have to figure out > the matching that maximizes the sum of hotnesses; you don't necessarily just > do a sum . zipWith (*). > Exactly. The description says: "Company XYZ has done the work for you, and now do xxx". This confused me a lot :-) From j.vimal at gmail.com Thu Aug 9 15:13:30 2007 From: j.vimal at gmail.com (Vimal) Date: Thu Aug 9 15:05:23 2007 Subject: [Haskell-cafe] Slow IO or bad code? In-Reply-To: <20070809142722.GA18563@gmx.de> References: <20070809142722.GA18563@gmx.de> Message-ID: On 8/9/07, Marc Weber wrote: > > I wrote a code, but seems to give "Time limit exceeded"! > ?? > Your code writes > 15 to stdout which is correct (with the example given on the page).. > You have to explain what you mean by >>seems to give "Time limit exceeded"<< > > > loop t function > Does already exist. > sequence $ replicate 10 function > is a much shorter way :-) > > oor perhaps mapM_ [ function | i <- [1..10] ] ) > > prod, to_int: > You can both implement using higher order functions > > prod = sum . zipWith (*) > to_int = map read > Thanks :) Yes, I see no reason why the code should be rejected by the judge (Time limit exceeded) just because I had defined all the functions. I had done this on many other occasions, and they all had worked well. I think that it has a lot to do with the (read) function and how it is implemented. So parsing takes quite a bit of time, and eventually most of the time gets used up in processing input. But the new functions are wonderful :-) I had a hunch that these functions should have been defined, but I learnt a lot in the process of writing those functions again! -- Vimal From miguelimo38 at yandex.ru Thu Aug 9 11:53:47 2007 From: miguelimo38 at yandex.ru (Miguel Mitrofanov) Date: Thu Aug 9 15:09:42 2007 Subject: [Haskell-cafe] New Eq instance In-Reply-To: References: Message-ID: <176558192.20070809195347@yandex.ru> rb> data Step = Step Id Scenario Action State Response rb> instance Eq Step where rb> Step id1 scenario1 action1 state1 response1 == Step id2 rb> scenario2 action2 state2 response2 = id == id rb> _ == _ = False "id == id" must be replaced with "id1 == id2". Error message you've got might be confusing, since "id" is already defined as an identity function, and functions are not Eq instances. I'd suggest something like data Step = Step {stepId :: Id, stepScen :: Scenario, steAction :: Action, stepState :: State, stepResp :: Responce} instance Eq Step where step1 == step2 = stepId step1 == stepId step2 From Andreas-Haskell at gmx.net Thu Aug 9 15:21:12 2007 From: Andreas-Haskell at gmx.net (Andreas Marth) Date: Thu Aug 9 15:19:20 2007 Subject: [Haskell-cafe] Derivation of Eq given Ord References: <2d3641330708090857x25e082c1q89763f2335b5f6e0@mail.gmail.com> <2b4b01c7daa2$1df21530$6702a8c0@GPO> <46BB57BE.9000601@charter.net> Message-ID: <2be201c7daba$737f4000$6702a8c0@GPO> I have to admit that I didn't test it before my first response. But now I did and can verify that it in deed "it does relay an error from deriving module to using [module/ghci]". So if I don't do any comparisons on Ego everything succeeds. If there is any comparision then ghc (6.6 in my case) returns the appropriate error. Still a bit strange for me, but now atleast I know it. :-) Andreas ----- Original Message ----- From: "Isaac Dupree" To: "Andreas Marth" Cc: "Dougal Stanton" ; "haskell-cafe" Sent: Thursday, August 09, 2007 8:06 PM Subject: Re: [Haskell-cafe] Derivation of Eq given Ord > Andreas Marth wrote: > > I would say that qualifies as a bug because it relays an error from compile > > time to run time. > > It doesn't relay anything to run time - ghci has to _compile_ the > expressions you give it too. If you _compile something_ successfully, > you will know that _it_ will not fail in the stated way (which is all > you need to know for a normal program with 'main'). > > However it does relay an error from deriving module to using > [module/ghci], which may not be right. HOWEVER, I can't reproduce it - > ghc (6.6.1) always tells me > No instance for (Eq Foo) > arising from the superclasses of an instance declaration > whether data or newtype, deriving Ord, no Eq instance, and no using > operations at all, and Hugs does too (in different words). > > Isaac From thomas.hartman at db.com Thu Aug 9 15:28:21 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Thu Aug 9 15:20:22 2007 Subject: [Haskell-cafe] how can I get template haskell macro-expanded code from inferStartState? (repeated post, now with subject) In-Reply-To: <6f680f6d0708091028xe140d91ha77306b25466d6c0@mail.gmail.com> Message-ID: I would say both. The stuff under Examples in the repo should all run with 8.8. (I think currently it doesn't.) The stuff in the wiki should say what is 8.8, what is 8.4, and obviously also give examples that work. The advantage of the wiki is you can make a change that propogates to the community without having commit priviliges for the repo. at least, that's how I've been working. Just changing the wiki for now, and maybe someday when I'm more confident about what I'm doing I'll ask for a commit bit for the repo. thomas. "Brian Brunswick" 08/09/2007 01:28 PM To Thomas Hartman/ext/dbcom@DBAmericas cc haskell-cafe , HAppS@googlegroups.com Subject Re: [Haskell-cafe] how can I get template haskell macro-expanded code from inferStartState? (repeated post, now with subject) On 09/08/07, Thomas Hartman wrote: > > (sorry, forgot the subject on my first post) > > In the following code which uses template haskell, how can I get back the > macro-expanded code generated from > > $(inferStartState ''MyState) > I just recently used ghc -ddump-splices to debug this very same problem. It turns out to be due to overlapping instances - inferStartState generates a (from memory) specific StartStateEx instance, but actually theres a general StartState => StartStateEx, and also a general Monoid=>StartState instance, and thats why the error message mentions Monoid. I guess this teaches us the reason that overlapping instances are bad: ***They don't work across modules**** Another module can add an instance which wasn't visible when a first module was compiled, and the two modules end up using different instances than expected. I've been meaning to start trying to contribute to improving the HAppS documentation, since its been such a struggle to start learning it. So the question to the HAppS people is, where is the canonical place for this documentation, where should one work? Is it the wiki page above, or the stuff inside the HAppS repository? -- Brian_Brunswick____brian@ithil.org____Wit____Disclaimer____!Shortsig_rules! --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/ca8d1004/attachment-0001.htm From benjamin.franksen at bessy.de Thu Aug 9 15:45:18 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Thu Aug 9 15:37:33 2007 Subject: [Haskell-cafe] Re: Re: a regressive view of support for imperative programming in Haskell References: <46BA0977.2040207@yale.edu> <49a77b7a0708091156l38327aabua7550a1c290d3505@mail.gmail.com> Message-ID: David Menendez wrote: > On 8/9/07, Benjamin Franksen wrote: >> Donn Cave wrote: >> > (I have a soft spot for O'Haskell, but >> > alas I must be nearly alone on that.) >> >> You are /not/ alone :-) I always found it very sad that O'Haskell and also >> its sucessor Timber (with all the good real-time stuff added) died >> the 'quick death' of most research languages. > > There is also RHaskell, which implements an O'Haskell-like system as a > Haskell library. > > Thanks for the pointer, I didn't know about this. Will take a look. Cheers Ben From edward.ing at gmail.com Thu Aug 9 15:51:06 2007 From: edward.ing at gmail.com (Edward Ing) Date: Thu Aug 9 15:43:00 2007 Subject: [Haskell-cafe] Haskell DB tutorial link is broken. Message-ID: <8f66da400708091251m1621a497q15d231c8b03f10eb@mail.gmail.com> Hi, The following link is broken. http://www.haskell.org/hawiki/HaskellDbTutorial Edward Ing From brian.brunswick at gmail.com Thu Aug 9 16:14:39 2007 From: brian.brunswick at gmail.com (Brian Brunswick) Date: Thu Aug 9 16:06:38 2007 Subject: [Haskell-cafe] Explaining monads Message-ID: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> (Better view the below in a fixed-width font!) With all the recent monad discussions, I embarked on trying to clarify my own thoughts about them, and started to think about things in terms of just /where/ extra structure is 'understood'. I think I can explain why 'a->IO b' is better than 'IO a->b'. The full title of this is really 'Explaining monads by comparison with comonads and arrows', but I didn't want to scare people off without putting in the above hook! We start with a simple single value of type 'a', and then we move into some other category, where the objects are 'thing a' instead, encapsulating some additional complexity - perhaps the possible absence or multiplicity of the value, perhaps extra state, opacity, etc. But whatever it is, the a-ness is still key for combing these objects. So lets look how they combine. Pay special attention to the f column. g f ??? g ??? f application a a->b flip ($) b monad bind m a a->m b >>= m b comonad cobind w a w a->b =>> w b arrow arr a b arr b c >>> arr a c simple application: f takes one argument, returns one result. monad: f still takes one argument, but now understands how to put things /into/ m. (Perhaps it just uses return::a->m a) comonad: f has access to the entire complexity of 'w a', understands how to get thing(s) out of it (coreturn), and distills it all down to one simple b. arrow: f has access to the entire complexity of the 'input' of arr b c, and does whatever is needed, to make the complexity of the 'output' of arr b c. Input/output may even be bidirectional! Also we can look at the job that ??? does. Remember that ??? has access to f as a function and can call it as many or as few times as it wishes. $: feeds a to f, once. >>=: picks zero or more a's from 'm a', feeds each one separately to f. opens up each of the 'm b' results to combine them into one 'm b'. =>>: feeds one or more versions of 'w a' to f, then builds a 'w b' in some way using the single b's (Perhaps inspired by 'w a') >>>: links g to f in some way, so they can interact in as complex a way as they like. Maybe it also contributes to that complexity. So now perhaps we can come to some conclusion about why monads are so useful and universal as control structures. It seems that monads are somehow the /simplest/ way of adding general control structure on top of single values. Notice how in a monad, the things that are combined together, the f's, still take just one 'a' argument. So theres no extra complexity for f in understanding its input. f can, however, put some additional complexity into its output - it can fail, or return multiple values, or whatever else is possible to encode in 'm a'. Still, f can be dumb, and just pass the problem onto some other function, maybe return. The complexity of the monad lives in one place, bind, >>=. It is bind that has the choice of calling f multiple times if it feels like it, and has the job of combining the results. bind is in control. f can only give it directions by returning one 'm b' for a given a. Contrast a comonad. Each f has to cope with an entire 'w a' on input. Moreover, it can't communicate any of that complexity back to cobind - it can only return one b. cobind only has the structure of 'w a' to inspire it in how to put together 'w b', it can receive /no/ instructions from f. Arrows are of course most general. Nothing is determined except that f talks with g in some way, and the compatibility is named 'b'. So given the choice of the above, which would /you/ choose, when the nature of the problem means one-on-one application is too simple? Surely a monad is the pick of the bunch! * f gives merely directions on control to >>= * f has to understand merely one single argument. (the monad can supply extra specialized functions like get/put, if we do want some complexity in there) * All the complex control structure is handled in one place - bind. And it has all the information available to do it well. Pity the poor comonad, only really suitable for infinite sequences! Shudder at the thought of the total complexity possible using arrows, and use them only when /really/ necessary. monad is king! -- Brian_Brunswick____brian@ithil.org____Wit____Disclaimer____!Shortsig_rules! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/fd720c0a/attachment.htm From radoslawg at gmail.com Thu Aug 9 16:22:03 2007 From: radoslawg at gmail.com (=?UTF-8?Q?Rados=C5=82aw_Grzanka?=) Date: Thu Aug 9 16:13:58 2007 Subject: [Haskell-cafe] Pure functional GUI In-Reply-To: <004f01c7dab3$37d75ad0$a7861070$@be> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> <1186656783.19215.6.camel@localhost> <46BB4F51.4090801@btinternet.com> <004f01c7dab3$37d75ad0$a7861070$@be> Message-ID: <9d55dbaf0708091322m32bdb85axaccf70096e0aae40@mail.gmail.com> 2007/8/9, Peter Verswyvelen : > > Indeed - the *hard* part seems to be figuring out how to run Glade on > Windoze... > > I did not dare to ask this question because I could not believe this was > hard... So anybody know how to do this? Run Glade on Window$? The google knows?? http://gladewin32.sourceforge.net/modules/news/ Frankly, I'm using Linux now, and even under windows (I must use it at work) I use vmware with ubuntu.. But not so long ago I ran glade on windows using stuff from this page. HTH, Radek. -- Przedszkole Miejskie nr 86 w Lodzi: http://www.pm86.pl/ From andrewcoppin at btinternet.com Thu Aug 9 16:27:23 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 9 16:18:45 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070809181637.GA3716@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> Message-ID: <46BB78AB.3050802@btinternet.com> Stefan O'Rear wrote: > On Thu, Aug 09, 2007 at 07:12:12PM +0100, Sebastian Sylvan wrote: > >> {-#OPTIONS -funbox-strict-fields #-} >> >> data Quad = Quad !Bool !Bool >> >> foo True True = ... >> foo True False = .... >> ... etc... >> >> >> The GHC option just causese GHC to unbox primitive types when they're >> strict in the data type, and the bangs cause them to be strict. >> > > Unfortunately, Bool is not a sufficiently primitive type for that to > work. > > Stefan > Don't ya just hate it when that happens? (I.e., you say something and sound all cleaver, and then an expert points out that "actually, no".) Happens to me all the time... heh. OOC, in what way is Bool not "primitive enough"? You mean because it's an algebraic data type, rather than a bunch of bits in the machine? For that matter, just how much space does such a type typically use? (Questions, questions, so many questions...) From benjamin.franksen at bessy.de Thu Aug 9 16:30:54 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Thu Aug 9 16:23:10 2007 Subject: [Haskell-cafe] Re: Re: a regressive view of support for imperative programming in Haskell References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <20070809185658.GF30903@darcs.net> Message-ID: David Roundy wrote: > On Thu, Aug 09, 2007 at 08:45:14PM +0200, Benjamin Franksen wrote: >> David Roundy wrote: >> > Several times since reading the beginning of this discussion I've wished I >> > had the new syntax so I could write something like: >> > >> > do if predicateOnFileContents (<- readFile "foo") then ... >> > >> > instead of either >> > >> > do contents <- readFile "foo" >> > if predicateOnFileContents contents then ... >> > >> > or (as you'd prefer) >> > >> > readFile "foo" >>= \contents -> >> > if predicateOnFileContents contents then ... >> >> Isn't this problem, namely being forced to name intermediate results, also >> solved by some sort of idiom bracket sugar, maybe together with the lambda >> case proposal? I would prefer both very much to the proposed (<- action) >> syntax for the same reasons that e.g. Jules Bean nicely summarized. > > I'm not familiar with the lambda case proposal, http://hackage.haskell.org/trac/haskell-prime/wiki/LambdaCase or, quoting from a recent post by Stefan O'Rear in this thread: > I think the CaseLambda proposal on the Haskell' wiki solves this one > nicely. > > mexpr >>= case of > ? p1 -> branch1 > ? p2 -> branch2 > > You still have to use >>=, but you don't have to name the scrutinee (and > names are expensive cognitively). i.e. your example would become fmap predicateOnFileContents (readFile "foo") >>= case of True -> ... False -> ... (use liftM instead of fmap, if you prefer) > and don't know what you mean by idiom bracket sugar, As has been already mentioned in this thread, in http://www.soi.city.ac.uk/~ross/papers/Applicative.html Conor McBride and Ross Paterson invent/explain a new type class that is now part of the base package (Control.Applicative). They also use/propose syntactic sugar for it, i.e. pure f <*> u1 <*> ... <*> un ~~> (| f u1 ... un |) (I just made up the symbols '(|' and '|)', the concrete syntax would have to be fixed by people more knowledgeable than me.) As to the pros and cons of (<- action) proposal, I think everything has been said. I'd vote for giving IdiomBrackets and/or LambdaCase a chance for being implemented, too, so we can try and evaluate different ways to simplify monadic code. One reason why I like IdiomBrackets is that they are more generally applicable (no pun intended ;:) i.e. they would work not just for Monads but for anything in Applicative. (Of course, that is also their weakness.) Similary, LambdaCase has more applications than just simplifying monadic code by avoiding to name an intermediate result. Cheers Ben From stefanor at cox.net Thu Aug 9 16:54:45 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 9 16:46:40 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <46BB78AB.3050802@btinternet.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> Message-ID: <20070809205445.GA4357@localhost.localdomain> On Thu, Aug 09, 2007 at 09:27:23PM +0100, Andrew Coppin wrote: > OOC, in what way is Bool not "primitive enough"? You mean because it's an > algebraic data type, rather than a bunch of bits in the machine? For that > matter, just how much space does such a type typically use? Yes. data Bool = False | True In general, GHC doesn't do "unboxing". Instead it has a simpler and more general approach, where it passes the fields of a single-constructor type instead of the type itself; this is as good as true unboxing in most of the interesting cases: data Int = I# Int# data Float = F# Float# data Double = D# Double# data Char = C# Char# data Ptr = Ptr Addr# ... but not always: data Bool = False | True data Integer = S# Int# | J# ByteArray# Int# As far as actual heap usage goes, GHC creates single static values for all 0-argument constructors; so all Bool WHNFs are one of two addresses, one for True and one for False. But GHC isn't quite smart enough for the -funbox-strict-fields mechanism to understand this... > (Questions, questions, so many questions...) I like answering them. :) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/1094fbcd/attachment.bin From bf3 at telenet.be Thu Aug 9 17:14:11 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Thu Aug 9 17:05:58 2007 Subject: [Haskell-cafe] Pure functional GUI In-Reply-To: <9d55dbaf0708091322m32bdb85axaccf70096e0aae40@mail.gmail.com> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> <1186656783.19215.6.camel@localhost> <46BB4F51.4090801@btinternet.com> <004f01c7dab3$37d75ad0$a7861070$@be> <9d55dbaf0708091322m32bdb85axaccf70096e0aae40@mail.gmail.com> Message-ID: <000101c7daca$3b01a140$b104e3c0$@be> Yeah I tried that one, but only the runtime, because I assumed that glade would be part of it, but I could not find it. I guess I should install the development version. Windows users look differently at these things, they expect all tools to be precompiled ;) I'll try again and dig deeper. -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Radoslaw Grzanka Sent: Thursday, August 09, 2007 10:22 PM To: Haskell-Cafe@haskell.org Subject: Re: [Haskell-cafe] Pure functional GUI 2007/8/9, Peter Verswyvelen : > > Indeed - the *hard* part seems to be figuring out how to run Glade on > Windoze... > > I did not dare to ask this question because I could not believe this was > hard... So anybody know how to do this? Run Glade on Window$? The google knows?? http://gladewin32.sourceforge.net/modules/news/ Frankly, I'm using Linux now, and even under windows (I must use it at work) I use vmware with ubuntu.. But not so long ago I ran glade on windows using stuff from this page. HTH, Radek. -- Przedszkole Miejskie nr 86 w Lodzi: http://www.pm86.pl/ _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From andrewcoppin at btinternet.com Thu Aug 9 17:19:59 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 9 17:11:20 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070809205445.GA4357@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> Message-ID: <46BB84FF.9020800@btinternet.com> Stefan O'Rear wrote: > On Thu, Aug 09, 2007 at 09:27:23PM +0100, Andrew Coppin wrote: > >> OOC, in what way is Bool not "primitive enough"? You mean because it's an >> algebraic data type, rather than a bunch of bits in the machine? For that >> matter, just how much space does such a type typically use? >> > > Yes. > > data Bool = False | True > > In general, GHC doesn't do "unboxing". Instead it has a simpler and > more general approach, where it passes the fields of a > single-constructor type instead of the type itself; this is as good as > true unboxing in most of the interesting cases: > > data Int = I# Int# > data Float = F# Float# > data Double = D# Double# > data Char = C# Char# > data Ptr = Ptr Addr# > ... > I see. (I think!) > but not always: > > data Bool = False | True > data Integer = S# Int# | J# ByteArray# Int# > > As far as actual heap usage goes, GHC creates single static values for > all 0-argument constructors; so all Bool WHNFs are one of two addresses, > one for True and one for False. But GHC isn't quite smart enough for > the -funbox-strict-fields mechanism to understand this... > Right. So a Bool is a 32 or 64 bit quantity. (Rather like Smalltalk...) That presumably means that a (Double,Double) is going to be a thunk that evaluates to a (,) pointing to two thunks that evaluate to pointers... IOW, something like 3 pointers' worth of space. Whereas my Quad object is going to be a pointer to one of 4 values... so it looks like Quads save space. (And they're more strict.) OTOH, I'm not sure what the time penalty is like... It would be nice if there were some general mechanism for turning a bunch of Bool flags into a single machine word. E.g., if I did a data Foo = Foo {flagX, flagY, flagZ :: !Bool} and it ends up that a Foo value is just a single machine word, and GHC picks which bit each flag is... I guess if you want that at present you'd have to code it all by hand. Hmm, I think this might work out better than my current Quad thing... I could do something like type Quad = Word8 foo q = let x = if testBit 0 q ... y = if testBit 1 q ... That should be quite fast... (?) >> (Questions, questions, so many questions...) >> > > I like answering them. :) > Heh. I'll have to pester you more often. :-P PS. Somewhere they should write a page entitled "Optimisations that GHC does (and doesn't) do"... PPS. Hmm. Might be out of date fast? ;-) From andrewcoppin at btinternet.com Thu Aug 9 17:21:13 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 9 17:12:34 2007 Subject: [Haskell-cafe] Pure functional GUI In-Reply-To: <9d55dbaf0708091322m32bdb85axaccf70096e0aae40@mail.gmail.com> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> <1186656783.19215.6.camel@localhost> <46BB4F51.4090801@btinternet.com> <004f01c7dab3$37d75ad0$a7861070$@be> <9d55dbaf0708091322m32bdb85axaccf70096e0aae40@mail.gmail.com> Message-ID: <46BB8549.3070104@btinternet.com> Rados?aw Grzanka wrote: > The google knows?? > http://gladewin32.sourceforge.net/modules/news/ > Ah - most optimal... Now finally I can try Glade. :-D From steve at fenestra.com Thu Aug 9 17:23:56 2007 From: steve at fenestra.com (Steve Schafer) Date: Thu Aug 9 17:15:50 2007 Subject: [Haskell-cafe] Problem with question 3 about knights and knaves onw ikipedia In-Reply-To: <000001c7dac9$18bb53c0$4a31fb40$@be> References: <004701c7dab0$165f92d0$431eb870$@be> <000001c7dac9$18bb53c0$4a31fb40$@be> Message-ID: On Thu, 9 Aug 2007 23:06:04 +0200, you wrote: >Is still don't get it completely... Could you give me an extra hint? I'm >getting crazy here, especially because I was really good at this stuff 20 >years ago! :) > >Here's the reasoning > >The first answer could not be "no" because from that I can infer that John >is a knight and Bill is a knave, which would mean the logician knows the >answer. > >This leaves me with 3 possibilities: > >a) Both John and Bill are knights >b) John is a knave and Bill could be anything Correct. But you forgot to recursively apply the hint. ;) The problem states that after John answers the second question, the Logician knows the solution. How can this be? What answer did John give that allows the Logician to solve the problem? Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ From chad.scherrer at gmail.com Thu Aug 9 17:29:50 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Thu Aug 9 17:21:43 2007 Subject: [Haskell-cafe] where to put handy functions? Message-ID: Is there process for submitting functions for consideration for inclusion into future versions of the standard libraries? For example, I'd like to see this in Data.List: extract :: [Int] -> [a] -> [a] extract = f 0 where f _ _ [] = [] f _ [] _ = [] f k nss@(n:ns) (x:xs) = if n == k then x:f (k+1) ns xs else f (k+1) nss xs This behaves roughly as extract ns xs == map (xs !!) ns except that it's a lot more efficient, and it still works if ns or xs (but not both) are infinite. Oh, and "ns" are required to be ordered and non-negative. I'm guessing there are a lot of similarly simple handy functions, and I'm wondering if there's anything in place to avoid (1) reinventing the wheel, and (2) name clashes. Someone else may have written "extract" as well, meaning one of us wasted our time. And chances are, if they did, it has a different name, leading to forced qualified imports. Finally, even if no one else is using it, it would be good to settle on reasonable names for things more easily. Is there a better name for this function? Is there a reason not to call it "extract"? -- Chad Scherrer "Time flies like an arrow; fruit flies like a banana" -- Groucho Marx From radoslawg at gmail.com Thu Aug 9 17:30:33 2007 From: radoslawg at gmail.com (=?UTF-8?Q?Rados=C5=82aw_Grzanka?=) Date: Thu Aug 9 17:22:33 2007 Subject: [Haskell-cafe] Pure functional GUI In-Reply-To: <000101c7daca$3b01a140$b104e3c0$@be> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> <1186656783.19215.6.camel@localhost> <46BB4F51.4090801@btinternet.com> <004f01c7dab3$37d75ad0$a7861070$@be> <9d55dbaf0708091322m32bdb85axaccf70096e0aae40@mail.gmail.com> <000101c7daca$3b01a140$b104e3c0$@be> Message-ID: <9d55dbaf0708091430v240b456wedafb25e10b3f7d@mail.gmail.com> 2007/8/9, Peter Verswyvelen : > Yeah I tried that one, but only the runtime, because I assumed that glade would be part of it, but I could not find it. I guess I should install the development version. Windows users look differently at these things, they expect all tools to be precompiled ;) I'll try again and dig deeper. Runtime is enough.. But Glade is packaged separetly. http://gladewin32.sourceforge.net/modules/wfdownloads/viewcat.php?cid=2 I just cheked it and it works flawlessly (as far as my 1 minute test goes ;) ) (Oh. I seem to remember that I needed GTK runtime from THIS page. It didn't go nicely with runtime installed with "GIMP for windows" package.) Have fun, Radek -- Codeside: http://codeside.org/ Przedszkole Miejskie nr 86 w Lodzi: http://www.pm86.pl/ From bf3 at telenet.be Thu Aug 9 17:35:07 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Thu Aug 9 17:26:54 2007 Subject: [Haskell-cafe] Problem with question 3 about knights and knaves onw ikipedia In-Reply-To: References: <004701c7dab0$165f92d0$431eb870$@be> Message-ID: <000301c7dacd$2800f250$7802d6f0$@be> Indeed, I missed that. This rules out the first answer is "no" But I still keep the 3 other solutions then :( >("John is a knight","Bill is a knight","Yes","No ") >("John is a knave ","Bill is a knight","Yes","Yes") >("John is a knave ","Bill is a knave ","Yes","No ") Any more help (or just the solution, I give up) is very welcome to help this poor man in logic hell ;-) Oh well, it seems I'm getting too old for this stuff ;) -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Steve Schafer Sent: Thursday, August 09, 2007 8:22 PM To: haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] Problem with question 3 about knights and knaves onw ikipedia On Thu, 9 Aug 2007 20:07:02 +0200, you wrote: >("John is a knight","Bill is a knight","Yes","No ") >("John is a knave ","Bill is a knight","Yes","Yes") >("John is a knave ","Bill is a knave ","Yes","No ") > >Anyone has an idea what I missed here? You're missing a key element of the problem: After John answers the first question, the Logician doesn't have enough information to solve the problem. Think about that for a second, and you will see the light. Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From stefanor at cox.net Thu Aug 9 17:37:04 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 9 17:29:01 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: References: Message-ID: <20070809213704.GA4665@localhost.localdomain> On Thu, Aug 09, 2007 at 02:29:50PM -0700, Chad Scherrer wrote: > Is there process for submitting functions for consideration for > inclusion into future versions of the standard libraries? For example, > I'd like to see this in Data.List: > > extract :: [Int] -> [a] -> [a] > extract = f 0 > where > f _ _ [] = [] > f _ [] _ = [] > f k nss@(n:ns) (x:xs) = if n == k then x:f (k+1) ns xs > else f (k+1) nss xs > > This behaves roughly as > extract ns xs == map (xs !!) ns > > except that it's a lot more efficient, and it still works if ns or xs > (but not both) are infinite. Oh, and "ns" are required to be ordered > and non-negative. > > I'm guessing there are a lot of similarly simple handy functions, and > I'm wondering if there's anything in place to avoid (1) reinventing > the wheel, and (2) name clashes. Someone else may have written > "extract" as well, meaning one of us wasted our time. And chances are, > if they did, it has a different name, leading to forced qualified > imports. > > Finally, even if no one else is using it, it would be good to settle > on reasonable names for things more easily. Is there a better name for > this function? Is there a reason not to call it "extract"? http://www.haskell.org/haskellwiki/Library_submissions Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/0ba62694/attachment.bin From byorgey at gmail.com Thu Aug 9 17:40:15 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Thu Aug 9 17:32:09 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: References: Message-ID: <22fcbd520708091440s61960a76t9cfdd6521453b284@mail.gmail.com> On 8/9/07, Chad Scherrer wrote: > > > extract :: [Int] -> [a] -> [a] > extract = f 0 > where > f _ _ [] = [] > f _ [] _ = [] > f k nss@(n:ns) (x:xs) = if n == k then x:f (k+1) ns xs > else f (k+1) nss xs > > This behaves roughly as > extract ns xs == map (xs !!) ns > > except that it's a lot more efficient, and it still works if ns or xs > (but not both) are infinite. Oh, and "ns" are required to be ordered > and non-negative. Nifty function there. =) And for the record, it works just fine if both lists are infinite -- it just produces an infinite output list, but it's lazy so no problem: *Main> take 10 $ extract [1,3..] [2..] [3,5,7,9,11,13,15,17,19,21] -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/40767bd3/attachment.htm From simonpj at microsoft.com Thu Aug 9 17:44:40 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Thu Aug 9 17:36:37 2007 Subject: [Haskell-cafe] Re: Re: a regressive view of support for imperative programming in Haskell In-Reply-To: References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <20070809185658.GF30903@darcs.net> Message-ID: There's been lots of interesting stuff on this thread. Does anyone feel up to summarizing it on a Wiki page, for others to polish? At least part of that page should comprise a compact specification of what the (<- ) proposal is; but there have been lots of other suggestions. Otherwise it'll all get submerged by next month's excitements. Simon | -----Original Message----- | From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe- | bounces@haskell.org] On Behalf Of Benjamin Franksen | Sent: 09 August 2007 21:31 | To: haskell-cafe@haskell.org | Subject: [Haskell-cafe] Re: Re: a regressive view of support for | imperative programming in Haskell | | David Roundy wrote: | > On Thu, Aug 09, 2007 at 08:45:14PM +0200, Benjamin Franksen wrote: | >> David Roundy wrote: | >> > Several times since reading the beginning of this discussion I've | wished I | >> > had the new syntax so I could write something like: | >> > | >> > do if predicateOnFileContents (<- readFile "foo") then ... | >> > | >> > instead of either | >> > | >> > do contents <- readFile "foo" | >> > if predicateOnFileContents contents then ... | >> > | >> > or (as you'd prefer) | >> > | >> > readFile "foo" >>= \contents -> | >> > if predicateOnFileContents contents then ... | >> | >> Isn't this problem, namely being forced to name intermediate | results, | also | >> solved by some sort of idiom bracket sugar, maybe together with the | lambda | >> case proposal? I would prefer both very much to the proposed (<- | action) | >> syntax for the same reasons that e.g. Jules Bean nicely summarized. | > | > I'm not familiar with the lambda case proposal, | | http://hackage.haskell.org/trac/haskell-prime/wiki/LambdaCase | | or, quoting from a recent post by Stefan O'Rear in this thread: | | > I think the CaseLambda proposal on the Haskell' wiki solves this one | > nicely. | > | > mexpr >>= case of | > p1 -> branch1 | > p2 -> branch2 | > | > You still have to use >>=, but you don't have to name the scrutinee | (and | > names are expensive cognitively). | | i.e. your example would become | | fmap predicateOnFileContents (readFile "foo") >>= case of | True -> ... | False -> ... | | (use liftM instead of fmap, if you prefer) | | > and don't know what you mean by idiom bracket sugar, | | As has been already mentioned in this thread, in | http://www.soi.city.ac.uk/~ross/papers/Applicative.html Conor McBride | and | Ross Paterson invent/explain a new type class that is now part of the | base | package (Control.Applicative). They also use/propose syntactic sugar | for | it, i.e. | | pure f <*> u1 <*> ... <*> un | | ~~> (| f u1 ... un |) | | (I just made up the symbols '(|' and '|)', the concrete syntax would | have to | be fixed by people more knowledgeable than me.) | | As to the pros and cons of (<- action) proposal, I think everything has | been | said. I'd vote for giving IdiomBrackets and/or LambdaCase a chance for | being implemented, too, so we can try and evaluate different ways to | simplify monadic code. | | One reason why I like IdiomBrackets is that they are more generally | applicable (no pun intended ;:) i.e. they would work not just for | Monads | but for anything in Applicative. (Of course, that is also their | weakness.) | Similary, LambdaCase has more applications than just simplifying | monadic | code by avoiding to name an intermediate result. | | Cheers | Ben | | _______________________________________________ | Haskell-Cafe mailing list | Haskell-Cafe@haskell.org | http://www.haskell.org/mailman/listinfo/haskell-cafe From stefanor at cox.net Thu Aug 9 18:09:38 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 9 18:01:33 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <46BB84FF.9020800@btinternet.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> Message-ID: <20070809220938.GB4665@localhost.localdomain> On Thu, Aug 09, 2007 at 10:19:59PM +0100, Andrew Coppin wrote: > Right. So a Bool is a 32 or 64 bit quantity. (Rather like Smalltalk...) > > That presumably means that a (Double,Double) is going to be a thunk that > evaluates to a (,) pointing to two thunks that evaluate to pointers... IOW, > something like 3 pointers' worth of space. I like pretty pictures. : : +--------+ : : /->| D# tag | +-----------+ +---------+ / +--------+ +--------+ | somewhere |--->| (,) tag |-/ | Value | /->| D# tag | +-----------+ +---------+ | | | +--------+ : : | fst | | | | | Value | : : +---------+ +--------+ | | | | snd |-----------------/ | | +---------+ +--------+ That's how much space a (Double,Double) NF uses. > Whereas my Quad object is going > to be a pointer to one of 4 values... so it looks like Quads save space. > (And they're more strict.) OTOH, I'm not sure what the time penalty is > like... Probably none. The STG-machine was designed to make user-defined algebraic types very fast. > It would be nice if there were some general mechanism for turning a bunch > of Bool flags into a single machine word. E.g., if I did a > > data Foo = Foo {flagX, flagY, flagZ :: !Bool} > > and it ends up that a Foo value is just a single machine word, and GHC > picks which bit each flag is... I guess if you want that at present you'd > have to code it all by hand. Hmm, I think this might work out better than > my current Quad thing... I could do something like > > type Quad = Word8 > > foo q = let > x = if testBit 0 q ... > y = if testBit 1 q ... > > That should be quite fast... (?) Probably. I wound up doing something similar with vty, to considerable gain. (I did however use .&. instead of testBit - probably makes no difference, but I'm reminded of the (^2) being much slower than join(*) case...) >>> (Questions, questions, so many questions...) >> >> I like answering them. :) > > Heh. I'll have to pester you more often. :-P :) > PS. Somewhere they should write a page entitled "Optimisations that GHC > does (and doesn't) do"... Good idea! Maybe it could be fit into the GHC Performance Resource somehow? (http://www.haskell.org/haskellwiki/Performance/GHC) > PPS. Hmm. Might be out of date fast? ;-) That's what wikis are for :) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/a396ab8d/attachment.bin From thomas.hartman at db.com Thu Aug 9 18:40:47 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Thu Aug 9 18:32:41 2007 Subject: [Haskell-cafe] can't build haxml under ghc 6.7, says HughesPJ is hidden... but ghc-pkg doesn't say it's hidden... Message-ID: Can I get some help building HaXml (from hackage) under ghc 6.7? I'm hoping to get HAppS running under 6.7, and use the new debugger to better understand what's going on under the hood. Eg, when I'm in the h function, I can take a look at the args and just see what types they are. (I am finding building an intuition from the documentation alone to be overwhelming. Too many types, too many instances... total confusion.) HaXMl is a dependendency for happs, that's why I need it. Anyway building haxml this is what I get. The subject of my message more or less summarizes my confusion. hartthoma@linuxpt:~/installs/HaXml-1.13.2>runghc Setup.hs build Setup.hs: Warning: The field "hs-source-dir" is deprecated, please use hs-source-dirs. Preprocessing library HaXml-1.13.2... Preprocessing executables for HaXml-1.13.2... Building HaXml-1.13.2... src/Text/XML/HaXml.hs:30:7: Could not find module `Text.PrettyPrint.HughesPJ': it is a member of package pretty-1.0, which is hidden hartthoma@linuxpt:~/installs/HaXml-1.13.2>ghc-pkg list /usr/local/lib/ghc-6.7.20070719/package.conf: Cabal-1.1.7, base-2.1, directory-1.0, filepath-1.0, ghc-6.7.20070719, haskell98-1.0, hpc-0.5, old-locale-1.0, old-time-1.0, pretty-1.0, process-1.0, random-1.0, readline-1.0, rts-1.0, template-haskell-0.1, unix-2.0 hartthoma@linuxpt:~/installs/HaXml-1.13.2>ghc-pkg list pretty-1.0 /usr/local/lib/ghc-6.7.20070719/package.conf: pretty-1.0 hartthoma@linuxpt:~/installs/HaXml-1.13.2>ghc --version The Glorious Glasgow Haskell Compilation System, version 6.7.20070719 hartthoma@linuxpt:~/installs/HaXml-1.13.2>ghc-pkg describe pretty-1.0 name: pretty version: 1.0 license: BSD3 copyright: maintainer: libraries@haskell.org stability: homepage: package-url: description: This package contains a pretty-printing library. category: author: exposed: True exposed-modules: Text.PrettyPrint Text.PrettyPrint.HughesPJ hidden-modules: import-dirs: $topdir/lib/pretty-1.0 library-dirs: $topdir/lib/pretty-1.0 hs-libraries: HSpretty-1.0 extra-libraries: extra-ghci-libraries: include-dirs: $topdir/lib/pretty-1.0/include includes: depends: base-2.1 hugs-options: cc-options: ld-options: framework-dirs: frameworks: haddock-interfaces: $topdir/share/ghc/doc/html/pretty/pretty.haddock haddock-html: $topdir/share/ghc/doc/html/pretty hartthoma@linuxpt:~/installs/HaXml-1.13.2> hartthoma@linuxpt:~/ProjectRepos/miscAdmin>ghc-pkg list /usr/local/lib/ghc-6.7.20070719/package.conf: Cabal-1.1.7, base-2.1, directory-1.0, filepath-1.0, ghc-6.7.20070719, haskell98-1.0, hpc-0.5, old-locale-1.0, old-time-1.0, pretty-1.0, process-1.0, random-1.0, readline-1.0, rts-1.0, template-haskell-0.1, unix-2.0 --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/daa44c7a/attachment-0001.htm From stefanor at cox.net Thu Aug 9 19:02:51 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 9 18:54:45 2007 Subject: [Haskell-cafe] can't build haxml under ghc 6.7, says HughesPJ is hidden... but ghc-pkg doesn't say it's hidden... In-Reply-To: References: Message-ID: <20070809230251.GA4834@localhost.localdomain> On Thu, Aug 09, 2007 at 06:40:47PM -0400, Thomas Hartman wrote: > Can I get some help building HaXml (from hackage) under ghc 6.7? > > I'm hoping to get HAppS running under 6.7, and use the new debugger to > better understand what's going on under the hood. Eg, when I'm in the h > function, I can take a look at the args and just see what types they are. > (I am finding building an intuition from the documentation alone to be > overwhelming. Too many types, too many instances... total confusion.) > HaXMl is a dependendency for happs, that's why I need it. > > Anyway building haxml this is what I get. The subject of my message more > or less summarizes my confusion. You're encountering one of my favorite features of Cabal. When you build a package, Cabal passess the -hide-all-packages option to GHC, which prevents the package from using any installed packages other than the ones explicitly listed in the Build-Depends: field. This is a Good Thing, because it means that whether or not a package builds depends *only* on the versions of the Build-Depended packages; other random packages on your system cannot possibly have any effect. Unfortunately, it means that splitting an existing package (base -> base + pretty + directory + old-time, with much more to come) is less than transparent; all packages which use HughesPJ need their Build-Depends field modified to include pretty, etc. Thomas Schilling's "configurations" allows a package to build with split and unsplit bases, but requires the logic to handle this be present in every package that wants to use base, and is only in HEAD cabal. I personally advocate a Debian-style system of Provides and re-exposing, but haven't yet bothered to actually implement it at all. I'm sure other people have other approaches. For now, we just edit .cabal files when transporting code between GHC versions... Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/e5b2d434/attachment.bin From brandon at heave.ugcs.caltech.edu Thu Aug 9 19:05:02 2007 From: brandon at heave.ugcs.caltech.edu (Brandon Michael Moore) Date: Thu Aug 9 18:56:56 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <20070809185217.GE30903@darcs.net> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <46BB11C4.4060107@jellybean.co.uk> <20070809185217.GE30903@darcs.net> Message-ID: <20070809230502.GA18468@heave.ugcs.caltech.edu> On Thu, Aug 09, 2007 at 11:52:17AM -0700, David Roundy wrote: > On Thu, Aug 09, 2007 at 02:08:20PM +0100, Jules Bean wrote: *snip* > > A third example is with nested dos: > > > > do x <- bar y > > baz > > something $ do foo x > > > > is not the same as > > > > do baz > > something $ do foo (<- bar y) > > Again, it all comes down to whether the "find the nearest do" is obvious. > It seems pretty obvious to me. And I like the idea of someone just > implementing this, and then those of us to whom it appeals can try it. > I've longed for something like this (mostly for monadic ifs and cases) for > quite a while now... Funny, I've been longing for the monadic case (and if) for quite a while. A mondic case is simple, it's handy, and you don't have to worry about lots of interactions caseM e of alts ==> e >>= \x -> case x of alts I'm convinced this would be plenty useful on its own, and also that trying to design any more comprehensive syntax quickly gets really tricky. The basic problem seems to be that functions can expect either monadic or pure arguments, and return pure or monadic values, so there are at least three possible conversion you might want at each application (considering pure<->pure and monadic<->monadic the same). Defaulting to "make things work" requires type information, and doesn't seem nearly so simple if you consider that programmers might actually want to pass around actions of the monad they are running in as values (Setting GUI callbacks, using [] for String processing, etc). Actually, deciding which tranformation gets juxtaposition and how to recurse into subterms seems to give a design space that might have reasonable solutions. More on that in a latter message. > > There is also the fact that if : > > foo x = bar x x > > > > then you call foo monadically as in > > > > do foo (<- baz) > > > > You can no longer "replace foo with its definition", because if replace > > that with > > > > do bar (<- baz) (<- baz) > > > > ...that means something rather different :( > > Again, this seems obvious, and it doesn't seem like "replace foo with its > definition" is something I think of. One of the great things about haskell is how completely naive you can be when you "replace foo with its definition", and still do valid equational reasoning. It would be sad if substituting a parenthesized subterm of something that looked like an expression wasn't valid. (expanding a definition can change sharing, but at least it's denotationally equivalent). The only slightly tricky things now are remembering that x <- exp does not define x to be exp, and what to expand a class method to. I think I'd be happier if there was some bracketing around the expression to be transformed, to warn you to again be cautious and fearful about transforming your code. Brandon From ajb at spamcop.net Thu Aug 9 21:05:00 2007 From: ajb at spamcop.net (ajb@spamcop.net) Date: Thu Aug 9 20:56:55 2007 Subject: [Haskell-cafe] Matters of precision In-Reply-To: <46BB5318.7080904@btinternet.com> References: <46BB5318.7080904@btinternet.com> Message-ID: <20070809210500.sm7okwk0c4k84sw8@webmail.spamcop.net> G'day. Quoting Andrew Coppin : > First of all, currently I'm just using Double to represent coordinates. > Can anybody tell me what the smallest value you can represent with one > is? (Not including denormals.) Remember that floating point numbers are stored in three parts. There's a sign, an exponent and a mantissa. Assuming that floatRadix n == 2, normalised numbers can be represented as: s * m * 2^e where s is 1 or -1, m is in the range [1/2,1) and stored using floatDigits n bits of precision, and e is in the range floatRange n. The reason why this is significant is that the precision of a floating point number is relative, not absolute. The relative error is measured by a number called "epsilon": -- The recursion is just so that we don't need -fglasgow-exts; feel -- free to use lexically-scoped type variables instead if you like. epsilon :: (RealFloat a) => a epsilon = let eps = encodeFloat 1 (1 - floatDigits eps) in eps epsilon is the smallest number such that 1.0 + epsilon /= 1.0. It measures the minimum possible relative separation between two adjacent normalised floating-point numbers. That is, if both a and b are normalised floating-point numbers (this also means that they're not zero), and a /= b, then abs (a-b) / a >= epsilon. Similarly, the maximum possible relative separation is epsilon * 2. (In general, epsilon * floatRadix n, but AFAIK no architectures that any Haskell implementation has been ported to has any floatRadix other than 2, so this is a safe assumption.) > (I've built a function that checks for cycles in the orbit - by looking > for previous points that are sufficiently "near" to the current one. But > I want to know how much precision a Double gives me so I can figure out > how near is "near".) While epsilon is the minimum relative separation of RealFloat numbers, it is usually much smaller than the error of any nontrivial bunch of operations. For something as simple as a Mandelbrot iteration, it's usually okay to simply use epsilon multiplied by some factor which represents the accumulated error of a bunch of operations. If you were doing Serious Numeric Analysis(tm), you'd go through each step and work out the possible rounding error, and come up with a tight bound. But something like this will probably do: tolerance :: Double tolerance = 100 * epsilon near :: Double -> Double -> Bool near a b | a == 0 || isDenormalized a = abs (a-b) < tolerance | otherwise = abs (a-b) < tolerance * a Cheers, Andrew Bromage From john at repetae.net Thu Aug 9 21:15:56 2007 From: john at repetae.net (John Meacham) Date: Thu Aug 9 21:07:50 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <46BB50DC.8020404@btinternet.com> References: <46BB50DC.8020404@btinternet.com> Message-ID: <20070810011556.GB1377@momenergy.repetae.net> On Thu, Aug 09, 2007 at 06:37:32PM +0100, Andrew Coppin wrote: > Which of these is likely to go faster? > type Quad = (Bool,Bool) ... > data Quad = BL | BR | TL | TR ... > I'm hoping that the latter one will more more strict / use less space. > But I don't truely know... The second one will be signifigantly better for a couple reasons. A simple counting of values that they can take on will show not only this but that they are not isomorphic even, (Bool,Bool) can be one of _|_ (True,True) (True,False) (False,True) (False,False) (_|_,True) (_|_,False) (_|_,_|_) (True,_|_) (False,_|_) that is a total of 10 different cases, each time a bottom might appear, a thunk evaluation (or indirection) is involved. now, take the second case data Quad = BL | BR | TL | TR the possible values are _|_ BL BR TL TR a whole half of the other representation. under jhc (and probably ghc at some point in the future) there is another very strong advantage to the second one, since it is an enumerated type, internally it can be represented by a simple unboxed byte that takes on a value of 0,1,2,or 3, which is a very enabling optimization, especially in the 'if' case in your code. John -- John Meacham - ?repetae.net?john? From ok at cs.otago.ac.nz Thu Aug 9 21:19:12 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 9 21:12:23 2007 Subject: [Haskell-cafe] a regressive view of support for imperative programming in Haskell In-Reply-To: <20070809184207.GD30903@darcs.net> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <235177FA-A63E-4268-8A94-83C286BA4DD3@cs.otago.ac.nz> <20070809184207.GD30903@darcs.net> Message-ID: <84B8A49F-D131-4E2D-9A8E-9922098FB56B@cs.otago.ac.nz> On 10 Aug 2007, at 6:42 am, David Roundy wrote: > do x1 <- e1 > if x1 then do x2 <- e2 > xx <- if x2 then e3 > else do x4 <- e4 > x5 <- e5 > e6 x4 x5 > e7 xx x1 > else do x8 <- e8 > x9 <- e9 > e10 x8 x9 x1 > x11 Granted. If you desugar nested dos then you need extra parentheses. (Basically, the invisible curly braces turn visible as parentheses.) But then, I don't regard this example as readable, and in true "lots of little functions" style would name the steps. I especially dislike the irregular indentation one gets with do/if/do. Anyone remember when Haskell extended list comprehension syntax to monads? Just as I was about to get my head around it, it went away. > This is the beauty of the do notation, it > allows one to write actual real complicated monadic code in a form > that is actually comprehensible. It seems we are now in complete agreement except for "comprehensible". From zednenem at psualum.com Thu Aug 9 21:36:54 2007 From: zednenem at psualum.com (David Menendez) Date: Thu Aug 9 21:28:47 2007 Subject: [Haskell-cafe] Re: Re: a regressive view of support for imperative programming in Haskell In-Reply-To: References: <46BA0977.2040207@yale.edu> <49a77b7a0708091156l38327aabua7550a1c290d3505@mail.gmail.com> Message-ID: <49a77b7a0708091836k2259453dx7c854e0e159b7b31@mail.gmail.com> On 8/9/07, Benjamin Franksen wrote: > David Menendez wrote: > > There is also RHaskell, which implements an O'Haskell-like system as a > > Haskell library. > > > > > > Thanks for the pointer, I didn't know about this. Will take a look. Perhaps a wiki page is in order. Reactive objects are an appealing way to organize programs, but there isn't much information on-line about people's experience with them. From ok at cs.otago.ac.nz Thu Aug 9 22:36:48 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 9 22:29:02 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: <20070809213704.GA4665@localhost.localdomain> References: <20070809213704.GA4665@localhost.localdomain> Message-ID: On 10 Aug 2007, at 9:37 am, Stefan O'Rear wrote: > http://www.haskell.org/haskellwiki/Library_submissions I'd like to ask if it's possible to add expm1 and log1p to the Floating class: class ... Floating a where ... exp, log, sqrt :: a -> a expm1, lop1p :: a -> a -- new, copied from C99 ... expm1 x = exp x - 1 -- but done more accurately log1p x = log (1 + x) -- but done more accurately However, the Library_submissions page wants an implementation, and adding this sort of function seems to require getting into the guts of an implementation. (Difficult: I am having serious trouble getting GHC 6.6 to install at all, never mind changing it.) From ajb at spamcop.net Thu Aug 9 23:09:36 2007 From: ajb at spamcop.net (ajb@spamcop.net) Date: Thu Aug 9 23:01:32 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070809205445.GA4357@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> Message-ID: <20070809230936.syoockowo0w0w0o0@webmail.spamcop.net> G'day all. Quoting Stefan O'Rear : > In general, GHC doesn't do "unboxing". Instead it has a simpler and > more general approach, [...] I'm not convinced that the phrase "more general" is appropriate here. :-) > As far as actual heap usage goes, GHC creates single static values for > all 0-argument constructors; so all Bool WHNFs are one of two addresses, > one for True and one for False. And, of course, if it's a strict argument, then the values stored are ALWAYS one of two possibilities. So as a matter of curiosity, would there be any advantage at all for "unboxing" enumeration types? (Apart from, I suppose, the possibility of using fewer than 32/64 bits to store a flag.) Cheers, Andrew Bromage From rk at trie.org Thu Aug 9 23:22:40 2007 From: rk at trie.org (Rahul Kapoor) Date: Thu Aug 9 23:14:33 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: References: Message-ID: On 8/9/07, Chad Scherrer wrote: > Is there process for submitting functions for consideration for > inclusion into future versions of the standard libraries? For example, > I'd like to see this in Data.List: I imagine including it in std lib takes a while. Would it be a good idea to include it in MissingH http://software.complete.org/missingh in the mean time? Cheers, Rahul From dons at cse.unsw.edu.au Thu Aug 9 23:25:17 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Thu Aug 9 23:17:14 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: References: Message-ID: <20070810032517.GI3382@cse.unsw.EDU.AU> rk: > On 8/9/07, Chad Scherrer wrote: > > Is there process for submitting functions for consideration for > > inclusion into future versions of the standard libraries? For example, > > I'd like to see this in Data.List: > > I imagine including it in std lib takes a while. Would it be a good > idea to include it in MissingH http://software.complete.org/missingh > in the mean time? It is probably better not to stick everything in MissingH -- its too big to be used easily. Smaller packages (say, Data.List.Extensions) make more sense. However, getting ok for stuff in Data.List isn't too hard. Just follow the libraries submission process: http://haskell.org/haskellwiki/Library_submissions Cheers, Don From hughperkins at gmail.com Thu Aug 9 23:47:03 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 9 23:38:56 2007 Subject: [Haskell-cafe] Pure functional GUI In-Reply-To: <9d55dbaf0708091430v240b456wedafb25e10b3f7d@mail.gmail.com> References: <837db430708081759nc5be730qb363bfe96c52e887@mail.gmail.com> <1186656783.19215.6.camel@localhost> <46BB4F51.4090801@btinternet.com> <004f01c7dab3$37d75ad0$a7861070$@be> <9d55dbaf0708091322m32bdb85axaccf70096e0aae40@mail.gmail.com> <000101c7daca$3b01a140$b104e3c0$@be> <9d55dbaf0708091430v240b456wedafb25e10b3f7d@mail.gmail.com> Message-ID: <837db430708092047v24c54f4cj415088d0eaec7ead@mail.gmail.com> Another way to get glade on Windows is to download mono, which contains both gtk and glade. One advantage of getting it this way is you then have mono at your disposal for benchmarking ghc ;-) (Not that you'd benchmark a gui app, but it seems there are many people who still think that comparing haskell with non-gc'd imperative languages having a corruptable stack/heap, such as C, is meaningfull ;-) ) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/9a4477a7/attachment.htm From hughperkins at gmail.com Fri Aug 10 00:13:57 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 00:05:50 2007 Subject: [Haskell-cafe] Dynamic thread management? Message-ID: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> Haskell/FP seems to have solved the hardest bit of threading, which is making it obvious which bits of a program are parallelizable, and which are not. Remains to actually parallelize out the programs. Am I being naive or is this trivial? There has been a lot of talk about parallelizing out a program statically, at compile time, but this would seem to suffer from the halting problem? The only way to know how long a function, or one of it's sub-functions, will take to run is to actually run it? Is there some reason why we cant just start a function running in a single thread, whilst running profiling, then after a while we check which bits of the function are taking time to run, and are parellizable, and we parallelize those out? This sounds reasonably trivial and workable? Basically, "parallizable" in a Haskell context means, as a first approximation, any map, foldr, foldl or derivatives, and any independent let assignments, then we can always add in extra parallizable cases later. Profiling is already built into Haskell AFAIK? so the profiling information is already available? Thoughts? Is there some reason why such an approach has been disregarded/is harder than it sounds? (By the way, can someone provide me a non-google link to the SPJ video talking about nested data parallism? google video is unavailable from my current location, and although I did watch this video once, it was on my second day of doing Haskell, a few weeks ago, so much of it was incomprehensible to me ;-) ) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/23a09cf5/attachment.htm From dons at cse.unsw.edu.au Fri Aug 10 01:01:39 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Fri Aug 10 00:53:38 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> Message-ID: <20070810050139.GU3382@cse.unsw.EDU.AU> hughperkins: > > Haskell/FP seems to have solved the hardest bit of > threading, which is making it obvious which bits of a > program are parallelizable, and which are not. > Remains to actually parallelize out the programs. Am I > being naive or is this trivial? > Is there some reason why we cant just start a function > running in a single thread, whilst running profiling, then > after a while we check which bits of the function are taking > time to run, and are parellizable, and we parallelize those > out? Perhaps have a look at this new paper: "Feedback directed implicit parallelism in Haskell" http://research.microsoft.com/~tharris/papers/2007-fdip.pdf -- Don From hughperkins at gmail.com Fri Aug 10 01:19:52 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 01:11:47 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <20070810050139.GU3382@cse.unsw.EDU.AU> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> Message-ID: <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> On 8/10/07, Donald Bruce Stewart wrote: > > Perhaps have a look at this new paper: > > "Feedback directed implicit parallelism in Haskell" > http://research.microsoft.com/~tharris/papers/2007-fdip.pdf > > -- Don > Ok interesting. So: it's a viable strategy, it's sortof already being done. A key difference between the approach in the Harris/Singh paper and the proposal above is that the Harris/Singh paper proposes recompiling the program multiple times. The proposal above is taking a more vm approach, something like Java or C#, where the vm adapts continuously to the program's behavior during execution. I suppose this does partly answer my question however about "how hard can this be?", in that a pre-requisite to do this is to make Haskell run as a vm? To what extent is making Haskell run in a vm possible? To what extent does ghci attempt to do this/ meet the requirements for an efficient vm? (off to read the rest of the paper, though everything after the abstract looks scary :-D ) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/82c46135/attachment.htm From hughperkins at gmail.com Fri Aug 10 01:35:48 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 01:27:43 2007 Subject: [Haskell-cafe] In-place modification In-Reply-To: <20070715123013.GB21891@cse.unsw.EDU.AU> References: <3d96ac180707141733r1cc20ac3y346cca59952187b9@mail.gmail.com> <20070715101805.GA19899@cse.unsw.EDU.AU> <837db430707150339x3af08403qfd79d96ebdb58585@mail.gmail.com> <20070715104846.GC19899@cse.unsw.EDU.AU> <3d96ac180707150353q7b7a9af8ue4560f96303913fd@mail.gmail.com> <837db430707150412r317edb42qf4acb1a29613ce0e@mail.gmail.com> <837db430707150422w3bacf5e2he3cbe73c2579b77@mail.gmail.com> <837db430707150436n69004067t75092dc59a9f9bd4@mail.gmail.com> <20070715121959.GA21891@cse.unsw.EDU.AU> <20070715123013.GB21891@cse.unsw.EDU.AU> Message-ID: <837db430708092235w796af26epe72fc18325f59a88@mail.gmail.com> On 7/15/07, Donald Bruce Stewart wrote: > > Oh, and I forgot you count up by two now. Here's the Haskell > transliteration (again). > > > {-# OPTIONS -O2 -optc-O -fbang-patterns #-} > > import Control.Monad.ST > import Data.Array.ST > import Data.Array.Base > import System > import Control.Monad > import Data.Bits > > main = print (pureSieve 10000000) > > pureSieve :: Int -> Int > pureSieve n = runST( sieve n ) > > sieve n = do > a <- newArray (3,n) True :: ST s (STUArray s Int Bool) > let cutoff = truncate (sqrt (fromIntegral n)) + 1 > go a n cutoff 3 1 > > go !a !m cutoff !n !c > | n >= m = return c > | otherwise = do > e <- unsafeRead a n > if e then > if n < cutoff > then let loop !j > | j < m = do > x <- unsafeRead a j > when x $ unsafeWrite a j False > loop (j+n) > > | otherwise = go a m cutoff (n+2) (c+1) > > in loop ( if n < 46340 then n * n else n `shiftL` > 1) > else go a m cutoff (n+2) (c+1) > > else go a m cutoff (n+2) c > > > Marginally faster: > > $ time ./primes > 664579 > ./primes 0.34s user 0.00s system 89% cpu 0.385 total > > Very cache-dependent though, so widely varying runtimes could be > expected. > > -- Don > Hi Donald, quick question. So, one of the things that is very interesting about Haskell is it's potential for automatic threading, ie you write a trivial algorithm that looks like it runs in a single thread, and the runtime splits it across multiple cores automatically. It's fairly safe to say that maps, foldrs, foldls, and their derivatives are safe to parallelize? (For example, hand-waving argument, a foldr of (/) on [1,5,7,435,46,2] can be split into a foldr on [1,5,7] and a foldr on [435,46,2], then their results combined). To what extent is the technology you are using in your algorithm parallizable? (I actually cant tell, it's a genuine question). In the case that it is parallelizable, to what extent is it trivial for a runtime to know this? (Again, I dont have enough information to tell) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/6bd01e41/attachment-0001.htm From ajb at spamcop.net Fri Aug 10 01:45:06 2007 From: ajb at spamcop.net (ajb@spamcop.net) Date: Fri Aug 10 01:36:58 2007 Subject: [Haskell-cafe] Typeclasses and implicit parameters Message-ID: <20070810014506.o87k8k0wckow8o00@webmail.spamcop.net> {-# OPTIONS -fglasgow-exts #-} -- G'day everyone. -- This is okay. f1 :: (?foo :: String) => String f1 = ?foo -- So is this. f2 :: (Show a, ?foo :: a) => a -> String f2 _ = show ?foo -- Hugs allows this. GHC rejects it on the grounds that "a" is unused -- on the right-hand side of the (=>). I think this is arguably a bug -- in GHC. f3 :: (Show a, ?foo :: a) => String f3 = show ?foo -- GHC rejects this. Hugs compiles it, but I can't call it as -- let ?foo = "Hello" in show Foo -- -- Is there a good reason to disallow this? data Foo = Foo instance (?foo :: String) => Show Foo where showsPrec _ Foo = showString ?foo . showString "Foo" -- Cheers, -- Andrew Bromage From bulat.ziganshin at gmail.com Fri Aug 10 01:49:31 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Fri Aug 10 01:42:12 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070810011556.GB1377@momenergy.repetae.net> References: <46BB50DC.8020404@btinternet.com> <20070810011556.GB1377@momenergy.repetae.net> Message-ID: <1757243263.20070810094931@gmail.com> Hello John, Friday, August 10, 2007, 5:15:56 AM, you wrote: > data Quad = BL | BR | TL | TR > under jhc (and probably ghc at some point in the future) there is another > very strong advantage to the second one, since it is an enumerated type, > internally it can be represented by a simple unboxed byte that takes on > a value of 0,1,2,or 3, which is a very enabling optimization, especially > in the 'if' case in your code. it was implemented and merged to ghc HEAD ~1 month ago -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From stefanor at cox.net Fri Aug 10 01:54:35 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 10 01:46:31 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070809230936.syoockowo0w0w0o0@webmail.spamcop.net> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <20070809230936.syoockowo0w0w0o0@webmail.spamcop.net> Message-ID: <20070810055435.GA6335@localhost.localdomain> On Thu, Aug 09, 2007 at 11:09:36PM -0400, ajb@spamcop.net wrote: > Quoting Stefan O'Rear : > > In general, GHC doesn't do "unboxing". Instead it has a simpler and > > more general approach, [...] > > I'm not convinced that the phrase "more general" is appropriate here. :-) Not sure where that came from; my filters are usually better than that :) > > As far as actual heap usage goes, GHC creates single static values for > > all 0-argument constructors; so all Bool WHNFs are one of two addresses, > > one for True and one for False. > > And, of course, if it's a strict argument, then the values stored are > ALWAYS one of two possibilities. So as a matter of curiosity, would > there be any advantage at all for "unboxing" enumeration types? (Apart > from, I suppose, the possibility of using fewer than 32/64 bits to store > a flag.) That was actually described in the first paper on first-class unboxed types. The paper described a general mechanism for declaring user-defined unboxed types and procedures for unboxing any ADT. No idea if it was ever implemented, though. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/18c3a049/attachment.bin From hughperkins at gmail.com Fri Aug 10 02:08:42 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 02:00:36 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070809220938.GB4665@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> Message-ID: <837db430708092308l8b3f52eq3990dab74c6053f@mail.gmail.com> On 8/10/07, Stefan O'Rear wrote: > > Good idea! Maybe it could be fit into the GHC Performance Resource > somehow? (http://www.haskell.org/haskellwiki/Performance/GHC) > >From the wiki: "Since GHC doesn't have any credible competition in the performance department these days it's hard to say what overly-slow means" Whoa, some wiki editor's been smoking a little too many illicit substances recently :-O I guess what is meant is "since GHC doesnt have any credible competion in the performance department these days relative to other Haskell compilers, it's hard to say what overly-slow means"? (but that's not quite how it reads ;-) ) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/44096449/attachment.htm From stefanor at cox.net Fri Aug 10 02:23:30 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 10 02:15:25 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <837db430708092308l8b3f52eq3990dab74c6053f@mail.gmail.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <837db430708092308l8b3f52eq3990dab74c6053f@mail.gmail.com> Message-ID: <20070810062330.GA6402@localhost.localdomain> On Fri, Aug 10, 2007 at 02:08:42PM +0800, Hugh Perkins wrote: > On 8/10/07, Stefan O'Rear wrote: > > > > Good idea! Maybe it could be fit into the GHC Performance Resource > > somehow? (http://www.haskell.org/haskellwiki/Performance/GHC) > > > > >From the wiki: "Since GHC doesn't > have any credible competition in the performance department these days it's > hard to say what overly-slow means" > > Whoa, some wiki editor's been smoking a little too many illicit substances > recently :-O stefan@stefans:/usr/local/src/Agda-1.0.2/src$ gcc Import.hs /usr/bin/ld:Import.hs: file format not recognized; treating as linker script /usr/bin/ld:Import.hs:1: syntax error collect2: ld returned 1 exit status stefan@stefans:/usr/local/src/Agda-1.0.2/src$ > I guess what is meant is "since GHC doesnt have any credible competion in > the performance department these days relative to other Haskell compilers, > it's hard to say what overly-slow means"? (but that's not quite how it > reads ;-) ) Personally, I think of: GHC's purpose: To implement Haskell GHC's competition: Nyhc, Jhc, Hugs, Hbc, Shc, ... a few more maybe ... Haskell's purpose: To be a generally cool language Haskell's competition: C++, SML, ... hundreds of thousands more and I make no assertion of a representative sample ... Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/fd47ffcb/attachment.bin From andrewcoppin at btinternet.com Fri Aug 10 02:26:28 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 10 02:17:47 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070809220938.GB4665@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> Message-ID: <46BC0514.6030806@btinternet.com> Stefan O'Rear wrote: > I like pretty pictures. > ...and have lots of spare time, apparently. ;-) [I actually meant to write (Bool,Bool), but anyway...] >> Whereas my Quad object is going >> to be a pointer to one of 4 values... so it looks like Quads save space. >> (And they're more strict.) OTOH, I'm not sure what the time penalty is >> like... >> > > Probably none. The STG-machine was designed to make user-defined > algebraic types very fast. > My program needs to make decisions based on a pair of boolean values. Encoding both values as a single algebraic data type means I have to keep "taking it apart" so I can work with it. I'm not sure how much time this wastes... >> It would be nice if there were some general mechanism for turning a bunch >> of Bool flags into a single machine word. E.g., if I did a >> >> data Foo = Foo {flagX, flagY, flagZ :: !Bool} >> >> and it ends up that a Foo value is just a single machine word, and GHC >> picks which bit each flag is... I guess if you want that at present you'd >> have to code it all by hand. Hmm, I think this might work out better than >> my current Quad thing... I could do something like >> >> type Quad = Word8 >> >> foo q = let >> x = if testBit 0 q ... >> y = if testBit 1 q ... >> >> That should be quite fast... (?) >> > > Probably. I wound up doing something similar with vty, to considerable > gain. (I did however use .&. instead of testBit - probably makes no > difference, but I'm reminded of the (^2) being much slower than join(*) > case...) > Well, perhaps I could define a pair of constants representing the bit masks? (OTOH, won't GHC optimise "testBit " into something faster anyway?) >> Heh. I'll have to pester you more often. :-P >> > > :) > Like that time yesterday, I compiled from program and got a weird message about GHC about "ignored trigraphs" or something... What the heck is a trigraph? (I compiled the program again later, and it compiled just fine. Weird...) >> PS. Somewhere they should write a page entitled "Optimisations that GHC >> does (and doesn't) do"... >> > > Good idea! Maybe it could be fit into the GHC Performance Resource > somehow? (http://www.haskell.org/haskellwiki/Performance/GHC) > OK. But it'll probably contain a lot of guessing to start with... ;-) From hughperkins at gmail.com Fri Aug 10 02:28:09 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 02:20:01 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070810062330.GA6402@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <837db430708092308l8b3f52eq3990dab74c6053f@mail.gmail.com> <20070810062330.GA6402@localhost.localdomain> Message-ID: <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> On 8/10/07, Stefan O'Rear wrote: > > Haskell's purpose: To be a generally cool language > Haskell's competition: C++, SML, ... hundreds of thousands more and I make > no assertion of a representative sample ... > Well, C++ is not really competitive with Haskell, because C++ does not have a GC, and it's trivial to corrupt the stack/heap. Wrt imperative languages, it probably makes more sense to compare Haskell with imperative languages that do have a GC and for which it's near impossible to accidentally corrupt the stack/heap. You'll find by the way that the imperative GC'd, stack/heap protected languages run *significantly* faster for many (not all I guess?) algorithms and applications. This will change with threading of course, but still if you've got a 1024-core Niagara 2012 machine, and the Haskell algorithm runs 65536 times as slowly as a single-core imperative GC'd language program, you're not going to see a significant speed-up ;-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/b68b17af/attachment.htm From drtomc at gmail.com Fri Aug 10 02:40:10 2007 From: drtomc at gmail.com (Thomas Conway) Date: Fri Aug 10 02:32:02 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <837db430708092308l8b3f52eq3990dab74c6053f@mail.gmail.com> <20070810062330.GA6402@localhost.localdomain> <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> Message-ID: <784a62100708092340hb6751fdk8f7093d10bbd4dfa@mail.gmail.com> On 8/10/07, Hugh Perkins wrote: > On 8/10/07, Stefan O'Rear wrote: > > Haskell's purpose: To be a generally cool language > > Haskell's competition: C++, SML, ... hundreds of thousands more and I make > no assertion of a representative sample ... > > > > Well, C++ is not really competitive with Haskell, because C++ does not have > a GC, and it's trivial to corrupt the stack/heap. Beg to differ. I offer the following proof by contradiction. :-) In my current job, I had a version-1 implementation in Python which had severe performance problems, and was not amenable to concurrency (The Python interpreter has a global lock, so you can only execute python bytecodes from one thread at a time. :-(). The natural alternative implementation language was C++, but I argued successfully that a Haskell implementation would be significantly easier to make concurrent. Saying that it's trivial to corrupt the stack/heap in C++ is a bit like saying it's easy to fall of a bicycle. Sure it is, but there are also well understood techniques for avoiding doing so. :-) In C++ that I write, I almost never use bare pointers. Using auto_ptr, shared_ptr, etc, handle most of the memory management issues. When they don't, one can usually make a analogous class to manage the lifetime for you. cheers, Tom -- Dr Thomas Conway drtomc@gmail.com Silence is the perfectest herald of joy: I were but little happy, if I could say how much. From dons at cse.unsw.edu.au Fri Aug 10 02:46:36 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Fri Aug 10 02:38:39 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <837db430708092308l8b3f52eq3990dab74c6053f@mail.gmail.com> <20070810062330.GA6402@localhost.localdomain> <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> Message-ID: <20070810064636.GC5596@cse.unsw.EDU.AU> hughperkins: > You'll find by the way that the imperative > GC'd, stack/heap protected languages run *significantly* > faster for many (not all I guess?) algorithms and > applications. Wow. Big claims. It must be silly hat day on the Haskell lists. We're trying hard to be friendly, perhaps you don't realise that your inflammatory remarks are out of place here? Now, just looking at just this assertion, for which you provide no references: let's see, only imperative and GC'd eh? Ruby? http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=ghc&lang2=ruby JavaScript? http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=ghc&lang2=javascript Python? http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=ghc&lang2=python Hmm. Not looking so good so for for the imperative, GC'd languages. Java? http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=ghc&lang2=java C#? http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=ghc&lang2=csharp Doesn't look too good for your assertion :( Maybe there really isn't something fundamental about being `imperative' or being garbage collected that matters performance-wise. Rather, having a good optimising native code compiler is more to the point? ------------------------------------------------------------------------ So, what do we do about this? Your unusual advocacy is interesting, but out of place on the Haskell mailing list. Given the community is growing rather rapidly, I'd like to encourage you to contribute more quality material to the list, and to tone down the sniping. Recall that your comments go out to around 2000 people directly, and further via Gmane. So making silly insults simply has the effect of alienating the people whose help you might seek in the future. To help more clearly think about the impact of noise on the mailing list, and how to actively seek to improve (or maintain) quality, I like to refer to this useful article: http://headrush.typepad.com/creating_passionate_users/2006/12/how_to_build_a_.html Give back to those who give you their time, rather than insulting them with silly statements. If we can make this step, there may well be unexpected benefits, in terms of collaboration and participation, that you otherwise miss out. -- Don (Trying to encourage friendly online communities) Unfortunately, I suspect you'll snip out 90% of this mail, and reply with some non sequitor. Please prove me wrong. From stefanor at cox.net Fri Aug 10 02:52:23 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 10 02:44:18 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <837db430708092308l8b3f52eq3990dab74c6053f@mail.gmail.com> <20070810062330.GA6402@localhost.localdomain> <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> Message-ID: <20070810065222.GA6474@localhost.localdomain> On Fri, Aug 10, 2007 at 02:28:09PM +0800, Hugh Perkins wrote: > On 8/10/07, Stefan O'Rear wrote: > > > > Haskell's purpose: To be a generally cool language > > Haskell's competition: C++, SML, ... hundreds of thousands more and I make > > no assertion of a representative sample ... > > > Wrt imperative languages, it probably makes more sense to compare Haskell > with imperative languages that do have a GC and for which it's near > impossible to accidentally corrupt the stack/heap. You'll find by the way > that the imperative GC'd, stack/heap protected languages run *significantly* > faster for many (not all I guess?) algorithms and applications. I don't have any numbers, but I've got a strong suspicion that this is almost entirely an issue of "programmer culture"; IOW, if you wrote a O'Caml to Haskell compiler, and fed idiomatic O'Caml through that and then GHC, the resulting binaries would be about as fast as if you used ocamlopt (INRIA's native code O'Caml compiler); and conversely, Haskell code translated na?vely into O'Caml would be no faster than before. (I do have the case of my Unlambda compiler, which was somewhat faster with ghc -O2 than with ocamlopt, but between CPS-conversion and the complete lack of data types in Unlambda, the resulting code was sufficiently unidiomatic in either language as to render my numbers mostly useless). > This will change with threading of course, but still if you've got a > 1024-core Niagara 2012 machine, and the Haskell algorithm runs 65536 times > as slowly as a single-core imperative GC'd language program, you're not > going to see a significant speed-up ;-) Just wait 12 years, and if the price of processors follows Moore's extrapolation and the Haskell keeps its parallelism, Haskell will win :) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/e5148dc5/attachment.bin From stefanor at cox.net Fri Aug 10 03:05:40 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 10 02:57:36 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <46BC0514.6030806@btinternet.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <46BC0514.6030806@btinternet.com> Message-ID: <20070810070540.GB6474@localhost.localdomain> On Fri, Aug 10, 2007 at 07:26:28AM +0100, Andrew Coppin wrote: > Stefan O'Rear wrote: >> I like pretty pictures. > > ...and have lots of spare time, apparently. ;-) Indeed. :) >> Probably none. The STG-machine was designed to make user-defined >> algebraic types very fast. > > My program needs to make decisions based on a pair of boolean values. > Encoding both values as a single algebraic data type means I have to keep > "taking it apart" so I can work with it. I'm not sure how much time this > wastes... Good point... >> Probably. I wound up doing something similar with vty, to considerable >> gain. (I did however use .&. instead of testBit - probably makes no >> difference, but I'm reminded of the (^2) being much slower than join(*) >> case...) > > Well, perhaps I could define a pair of constants representing the bit > masks? (OTOH, won't GHC optimise "testBit " into something faster > anyway?) Probably not; GHC has few rules for dealing with partial evaluation on numeric arguments. Asking GHC itself: stefan@stefans:/tmp$ ghc -c -ddump-simpl -O2 X.hs ==================== Tidy Core ==================== X.moo [NEVER Nothing] :: forall a_a82. GHC.Base.Int -> a_a82 -> a_a82 -> a_a82 [GlobalId] [Arity 3 NoCafRefs Str: DmdType U(L)LL] X.moo = \ (@ a_a88) (ix_a84 :: GHC.Base.Int) (ift_a85 :: a_a88) (iff_a86 :: a_a88) -> case ix_a84 of wild_acF { GHC.Base.I# x#_acH -> case Data.Bits.$w$s$dmbit 7 of ww1_acN { __DEFAULT -> case GHC.Prim.word2Int# (GHC.Prim.and# (GHC.Prim.int2Word# x#_acH) (GHC.Prim.int2Word# ww1_acN)) of wild1_acO { __DEFAULT -> ift_a85; 0 -> iff_a86 } } } ==================== Tidy Core Rules ==================== stefan@stefans:/tmp$ cat X.hs module X where import Data.Bits {-# NOINLINE moo #-} -- ghc doesn't optimize functions that are deemed small enough for inlining; -- this is a good thing (since when we inline we know more about the context -- and can do a better job if we wait until then), but interferes with small -- experiments like this moo :: Int -> a -> a -> a moo ix ift iff = if testBit ix 7 then ift else iff stefan@stefans:/tmp$ The important bit is the (Data.Bits.$w$s$dmbit 7). Since that function doesn't do IO (no realworld arguments), it could in theory be evaluated at compile time (and judging from context it almost surely evaluates to 128#), but it hasn't been. > Like that time yesterday, I compiled from program and got a weird message > about GHC about "ignored trigraphs" or something... What the heck is a > trigraph? Everyone's favorite obscure feature of the ANSI C99 preprocessor. Probably you had something like "this is odd???" in your source code, and were using -cpp. http://www.vmunix.com/~gabor/c/draft.html#5.2.1.1 > (I compiled the program again later, and it compiled just fine. Weird...) >> Good idea! Maybe it could be fit into the GHC Performance Resource >> somehow? (http://www.haskell.org/haskellwiki/Performance/GHC) > > OK. But it'll probably contain a lot of guessing to start with... ;-) Wiki pages can be fixed. Private misunderstandings can't, at least not anywhere near as easily. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/8f81494a/attachment.bin From hughperkins at gmail.com Fri Aug 10 03:22:33 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 03:14:26 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) Message-ID: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> Haskell vs GC'd imperative languages =========================== On 8/10/07, Thomas Conway wrote: > > > Well, C++ is not really competitive with Haskell, because C++ does not > have > > a GC, and it's trivial to corrupt the stack/heap. > > Beg to differ. I offer the following proof by contradiction. :-) > > In my current job, I had a version-1 implementation in Python which > had severe performance problems, and was not amenable to concurrency > (The Python interpreter has a global lock, so you can only execute > python bytecodes from one thread at a time. :-(). The natural > alternative implementation language was C++, but I argued successfully > that a Haskell implementation would be significantly easier to make > concurrent. > > Well, Python is comparable to Haskell to the extent that it has a GC. OTOH it is interpreted, and, well, slow. It's also got a Big Lock around the core system libraries. Trying to avoid naming it by name, because there's a lot of elitism against using mainstream languages that are used by "stupid people", but the fastest imperative GC'd language that I know of is C#. Even the opensource mono version is wickedly fast. The Microsoft version shaves another 20% off execution speed or so. See, I get the feeling that a lot of people are using Haskell not because they compared it to C# and found it better ,but because they compared it to: - C -> Haskell is easier - C++ -> Haskell is easier - Python -> Haskell is faster C# -> fast and easy ;-) Threading ======= I'm not trolling, despite strong appearances to the contrary ;-) My primary objective/goal is to find a way to make threading easy. Thread management today is like memory management in the early 90s. We kindof had tools (new, delete in C++ for example) to do it. At some point we started to use things like Smart Pointers to make it easier, but none of it really worked. Issues such as circular referential loops caused this not to work very well. At some point, someone came out with the idea of a garbage collector, which is really very simple once you know: all it does is walk the graph of variables, starting with those we know are definitely used, and delete all those objects that didnt get walked on. Simple, easy, magic. We should do the same thing for threads. Threading is going to become a major issue soon, maybe not tomorrow, but there is a GPL'd Niagara 2 out with 64 threads (I think?), so the time is now. Haskell solves a huge issue with threads, which is locking, which is a total PITA in imperative languages, it's of the same order of magnitude of problem as eliminating memory leaks, without deleting something twice etc, used to be in pre-GC C++. Nevertheless, one cannot be interested in threads without being interested in performance. There's no point in running a program in 1024 threads, if the single-core C# version runs faster than that, and often it does! Parallelizeability ============ Now, I did have kindof a shootout thread with Don and Sebastien, calculating prime numbers, where Don managed to get to within an order of magnitude of C# performance (I think he got to about 70-80% of C# performance, cool!) -> BUT, and its a big but ;-), as far as I can tell, he did that by sacrificing the Haskell ability to be easily parallelized; his solution was essentially imperative. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/5021105f/attachment.htm From bf3 at telenet.be Fri Aug 10 03:26:09 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Fri Aug 10 03:18:01 2007 Subject: [Haskell-cafe] Problem with question 3 about knights andknavesonw ikipedia Message-ID: Oh boy, never mind, after a good night sleep the solution is super obvious... Grrr what a waste of time ;-) The solution is in the sentence "the logician has then enough information to solve the problem", which I yesterday read like "the problem can now be solved", which is not the same. So the second answer must have been "Yes" otherwise the logician did not have enough information to solve the problem (because two cases still remain). Gee. But it was good Haskell practice ;-) >>("John is a knave ","Bill is a knight","Yes","Yes") >----- Oorspronkelijk bericht ----- >Van: Peter Verswyvelen [mailto:bf3@telenet.be] >Verzonden: donderdag, augustus 9, 2007 11:35 PM >Aan: steve@fenestra.com, haskell-cafe@haskell.org >Onderwerp: RE: [Haskell-cafe] Problem with question 3 about knights and knaves onw ikipedia > >Indeed, I missed that. This rules out the first answer is "no" > >But I still keep the 3 other solutions then :( > >>("John is a knight","Bill is a knight","Yes","No ") >>("John is a knave ","Bill is a knight","Yes","Yes") >>("John is a knave ","Bill is a knave ","Yes","No ") > >Any more help (or just the solution, I give up) is very welcome to help this >poor man in logic hell ;-) > >Oh well, it seems I'm getting too old for this stuff ;) > >-----Original Message----- >From: haskell-cafe-bounces@haskell.org >[mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Steve Schafer >Sent: Thursday, August 09, 2007 8:22 PM >To: haskell-cafe@haskell.org >Subject: Re: [Haskell-cafe] Problem with question 3 about knights and knaves >onw ikipedia > >On Thu, 9 Aug 2007 20:07:02 +0200, you wrote: > >>("John is a knight","Bill is a knight","Yes","No ") >>("John is a knave ","Bill is a knight","Yes","Yes") >>("John is a knave ","Bill is a knave ","Yes","No ") >> >>Anyone has an idea what I missed here? > >You're missing a key element of the problem: After John answers the >first question, the Logician doesn't have enough information to solve >the problem. Think about that for a second, and you will see the light. > >Steve Schafer >Fenestra Technologies Corp. >http://www.fenestra.com/ >_______________________________________________ >Haskell-Cafe mailing list >Haskell-Cafe@haskell.org >http://www.haskell.org/mailman/listinfo/haskell-cafe > >_______________________________________________ >Haskell-Cafe mailing list >Haskell-Cafe@haskell.org >http://www.haskell.org/mailman/listinfo/haskell-cafe > > From dons at cse.unsw.edu.au Fri Aug 10 03:38:14 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Fri Aug 10 03:30:11 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> Message-ID: <20070810073813.GD5596@cse.unsw.EDU.AU> hughperkins: > Now, I did have kindof a shootout thread with Don and > Sebastien, calculating prime numbers, where Don managed to > get to within an order of magnitude of C# performance (I > think he got to about 70-80% of C# performance, cool!) -> Despite my better judgement, I'll just point out that you stopped measuring the programs midway through. However, the shootout guys didn't, and they publish the results here: http://shootout.alioth.debian.org/gp4/benchmark.php?test=nsievebits&lang=all The GHC-compiled entry comes in at 1.2x C++, which I'm quite happy with. Strangely, despite your assertions, the C# entry lags well down the list. -- Don From simonpj at microsoft.com Fri Aug 10 03:39:16 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Fri Aug 10 03:31:09 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070809230936.syoockowo0w0w0o0@webmail.spamcop.net> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <20070809230936.syoockowo0w0w0o0@webmail.spamcop.net> Message-ID: | And, of course, if it's a strict argument, then the values stored are | ALWAYS one of two possibilities. So as a matter of curiosity, would | there be any advantage at all for "unboxing" enumeration types? (Apart | from, I suppose, the possibility of using fewer than 32/64 bits to store | a flag.) Possibly some, but less now because of pointer tagging (see paper on my home page) http://research.microsoft.com/~simonpj/papers/ptr-tag/index.htm. We've never gotten around to unboxing enumeration types because we couldn't convince ourselves that the win was big enough. My nose tells me there is probably a small win, but whether it's worth the additional complexity I'm not sure. S From hughperkins at gmail.com Fri Aug 10 03:57:14 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 03:49:06 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <20070810073813.GD5596@cse.unsw.EDU.AU> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> Message-ID: <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> On 8/10/07, Donald Bruce Stewart wrote: > > > http://shootout.alioth.debian.org/gp4/benchmark.php?test=nsievebits&lang=all > > The GHC-compiled entry comes in at 1.2x C++, which I'm quite happy with. > Strangely, despite your assertions, the C# entry lags well down the list. Yeah, you somehow managed to slip around their rules without them noticing ;-) They specify to use a bit array, but you dont ;-) Bit arrays are optimal for space, but can be really slow. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/502e07bb/attachment.htm From dons at cse.unsw.edu.au Fri Aug 10 03:58:02 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Fri Aug 10 03:49:58 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> Message-ID: <20070810075802.GE5596@cse.unsw.EDU.AU> hughperkins: > > On 8/10/07, Donald Bruce Stewart <[1]dons@cse.unsw.edu.au> > wrote: > > > [2]http://shootout.alioth.debian.org/gp4/benchmark.php?te > st=nsievebits&lang=all > The GHC-compiled entry comes in at 1.2x C++, which I'm > quite happy with. > Strangely, despite your assertions, the C# entry lags > well down the list. > > Yeah, you somehow managed to slip around their rules without > them noticing ;-) They specify to use a bit array, but you > dont ;-) Bit arrays are optimal for space, but can be really > slow. It's using bit arrays. -- Don From hughperkins at gmail.com Fri Aug 10 04:00:01 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 03:51:54 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <20070810075802.GE5596@cse.unsw.EDU.AU> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> <20070810075802.GE5596@cse.unsw.EDU.AU> Message-ID: <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> On 8/10/07, Donald Bruce Stewart wrote: > > It's using bit arrays. > Well I'm a total Haskell newbie, and you're using Haskell to write imperative code, so it's really hard for me to read, but looking at your code, you have: (IOUArray Int Bool) -- an array of Bool Bool is a 32-bit value in Haskell AFAIK? (or possibly a machine-dependent sized value, but certainly not a bit?) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/95f0bc83/attachment.htm From dons at cse.unsw.edu.au Fri Aug 10 04:03:56 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Fri Aug 10 03:55:51 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> <20070810075802.GE5596@cse.unsw.EDU.AU> <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> Message-ID: <20070810080356.GF5596@cse.unsw.EDU.AU> hughperkins: > > On 8/10/07, Donald Bruce Stewart <[1]dons@cse.unsw.edu.au> > wrote: > > It's using bit arrays. > > Well I'm a total Haskell newbie, and you're using Haskell to > write imperative code, so it's really hard for me to read, > but looking at your code, you have: > > (IOUArray Int Bool) -- an array of Bool > > Bool is a 32-bit value in Haskell AFAIK? (or possibly a > machine-dependent sized value, but certainly not a bit?) No, STUArray s Int Bool is a bit array. Look at the space use. Or try replacing Bool with Word32, and see what happens. -- Don From stefanor at cox.net Fri Aug 10 04:05:41 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 10 03:57:38 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> <20070810075802.GE5596@cse.unsw.EDU.AU> <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> Message-ID: <20070810080541.GA6778@localhost.localdomain> On Fri, Aug 10, 2007 at 04:00:01PM +0800, Hugh Perkins wrote: > On 8/10/07, Donald Bruce Stewart wrote: > > > > It's using bit arrays. > > > > Well I'm a total Haskell newbie, and you're using Haskell to write > imperative code, so it's really hard for me to read, but looking at your > code, you have: > > (IOUArray Int Bool) -- an array of Bool > > Bool is a 32-bit value in Haskell AFAIK? (or possibly a machine-dependent > sized value, but certainly not a bit?) Bool is 32 bits, but Don is using UArray. UArray is not parametric in the element type, which means it's less generally useful (no UArray of Complex Double, for instance), but conversely it is able to use more efficient representations depending on the type. from Data.Array.Base: instance MArray (STUArray s) Bool (ST s) where ... unsafeRead (STUArray _ _ marr#) (I# i#) = ST $ \s1# -> case readWordArray# marr# (bOOL_INDEX i#) s1# of { (# s2#, e# #) -> (# s2#, (e# `and#` bOOL_BIT i#) `neWord#` int2Word# 0# #) } ... Okay, you probably can't read that (it's too ugly for me to *want* to read it), but the use of and# should stand out. bOOL_BIT computes a bitmask, bOOL_INDEX divides by 8. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/a3af22b9/attachment.bin From a.biurvOir4 at asuhan.com Fri Aug 10 04:07:38 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Fri Aug 10 03:59:30 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> Message-ID: <12087081.post@talk.nabble.com> Brian Brunswick-5 wrote: > > g f ??? g ??? f > > application a a->b flip ($) b > monad bind m a a->m b >>= m b > comonad cobind w a w a->b =>> w b > arrow arr a b arr b c >>> arr a c > Fmap's missing: m a, a->b, flip fmap, m b. You might want to throw in Applicative there too: m a, m (a->b), flip (<*>), m b. Snipped: Arguments for monads being the best of the M-C-A trinity. While I can share your enthusiasm over certain insights you've discovered about monads, I think you'll find that each of those structures have their privileged place in your code. You say "monads are somehow the /simplest/ way of adding general control structure on top of single values." Well sure, for specific implicit parameters of ?simplest, ?general, and ?controlStructure. It's like saying lists are better than arrays and tuples. Monads are undoubtedly more pervasive, and that could be because there aren't as many arrow and comonad tutorials, atomic ones or otherwise. Brian Brunswick-5 wrote: > > Pity the poor comonad, only really suitable for infinite sequences! > Comonads are no more (exclusively) about infinite structures than monads are (exclusively) about sequencing/imperative programming. What's so infinite about this (specialization of the so-called Product) comonad: instance Comonad ((,) Bool) where -- coreturn :: (Bool, r) -> r coreturn (b, r) = r -- cobind :: (Bool, r) -> ((Bool, r) -> s) -> (Bool, s) coextend u@(b,r) g = (b, g u) -- View this message in context: http://www.nabble.com/Explaining-monads-tf4244948.html#a12087081 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From hughperkins at gmail.com Fri Aug 10 04:09:21 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 04:01:12 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <20070810080541.GA6778@localhost.localdomain> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> <20070810075802.GE5596@cse.unsw.EDU.AU> <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> <20070810080541.GA6778@localhost.localdomain> Message-ID: <837db430708100109h216a957etf119605949ef539c@mail.gmail.com> On 8/10/07, Stefan O'Rear wrote: > > Bool is 32 bits, but Don is using UArray. UArray is not parametric in > the element type, which means it's less generally useful (no UArray of > Complex Double, for instance), but conversely it is able to use more > efficient representations depending on the type. > Ok, interesting :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/4a763712/attachment.htm From simonpj at microsoft.com Fri Aug 10 04:17:09 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Fri Aug 10 04:09:02 2007 Subject: [Haskell-cafe] Derivation of Eq given Ord In-Reply-To: <2d3641330708090857x25e082c1q89763f2335b5f6e0@mail.gmail.com> References: <2d3641330708090857x25e082c1q89763f2335b5f6e0@mail.gmail.com> Message-ID: It may not be a bug, because you do get an error, but it's certainly an infelicity because the error comes out much too late. I'll Trac this and fix in due course. Thanks for raising it. Simon | -----Original Message----- | From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Dougal | Stanton | Sent: 09 August 2007 16:57 | To: haskell-cafe | Subject: [Haskell-cafe] Derivation of Eq given Ord | | Is there a reason why automatic derivation of Ord without Eq doesn't | do "the sensible thing" and just derive Eq anyway? | | > newtype Id a = Id { a :: String } | > deriving (Read, Show, Eq, Ord) | > newtype Ego a = Ego { b :: String } | > deriving (Read, Show, Ord) | | Both will type check, but if you try any (in)equality operators on the | second they'll be spat back at you. | | > *Main> let e1 = Ego "" | > *Main> let e2 = Ego "" | > *Main> e1 < e2 | > | > :1:0: | > No instance for (Eq (Ego a)) | > arising from use of `<' at :1:0-6 | > Possible fix: add an instance declaration for (Eq (Ego a)) | > In the expression: e1 < e2 | > In the definition of `it': it = e1 < e2 | | It doesn't seem *much* of a hardship, but it wasn't what I expected. | I'm not used to GHC accepting input and silently dropping stuff it | doesn't like... | | Cheers, | | D. | _______________________________________________ | Haskell-Cafe mailing list | Haskell-Cafe@haskell.org | http://www.haskell.org/mailman/listinfo/haskell-cafe From jon at ffconsultancy.com Fri Aug 10 04:16:54 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Fri Aug 10 04:17:31 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070810064636.GC5596@cse.unsw.EDU.AU> References: <46BB50DC.8020404@btinternet.com> <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> <20070810064636.GC5596@cse.unsw.EDU.AU> Message-ID: <200708100916.54638.jon@ffconsultancy.com> On Friday 10 August 2007 07:46:36 Donald Bruce Stewart wrote: > Doesn't look too good for your assertion :( Poor benchmark design forces the authors of the shootout to subjectively reject or cripple submissions. In fact, counting primes and printing pi are among the worst possible benchmark tasks imaginable. Regardless, of the more objective tests (spectral-norm, fasta, k-nucleotide), Haskell is slower in all cases than all of the following languages: C, C++, D, Pascal, Clean, OCaml, Java, CAL, Scala, MLton and C# (Mono). I don't know what you're counting as an imperative language but I am sure you can find some in that list. The ray tracer is a much more objective measure because it is a practically irreducible task. Haskell remains something like 3x slower than OCaml, Scheme and C++: http://www.ffconsultancy.com/languages/ray_tracer/results.html You might also like to finish the Minim interpreter or compare the performance of some other suitably small interpreters perhaps running some larger programs. A Haskell implementation of the "n"th nearest neighbours example from my book would be interesting. The program is small, computationally intensive and of practical interest. The symbolic simplifier would be a good benchmark if it were run on non-trivial input. A term rewriter to evaluate some simple Mathematica programs would be interesting. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/?e From mvanier at cs.caltech.edu Fri Aug 10 04:50:43 2007 From: mvanier at cs.caltech.edu (Michael Vanier) Date: Fri Aug 10 04:42:49 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> Message-ID: <46BC26E3.1030902@cs.caltech.edu> Hugh Perkins wrote: > > I'm not trolling, despite strong appearances to the contrary ;-) My > primary objective/goal is to find a way to make threading easy. Thread > management today is like memory management in the early 90s. We kindof > had tools (new, delete in C++ for example) to do it. At some point we > started to use things like Smart Pointers to make it easier, but none of > it really worked. Issues such as circular referential loops caused this > not to work very well. > > At some point, someone came out with the idea of a garbage collector, > which is really very simple once you know: all it does is walk the graph > of variables, starting with those we know are definitely used, and > delete all those objects that didnt get walked on. Simple, easy, magic. > > We should do the same thing for threads. Threading is going to become a > major issue soon, maybe not tomorrow, but there is a GPL'd Niagara 2 out > with 64 threads (I think?), so the time is now. > > Haskell solves a huge issue with threads, which is locking, which is a > total PITA in imperative languages, it's of the same order of magnitude > of problem as eliminating memory leaks, without deleting something twice > etc, used to be in pre-GC C++. > Just to get the history right: garbage collectors have been around a _long_ time, since the '60s in Lisp systems. They only became known to most programmers through Java (which is one unarguable good thing that Java did). As for threading, in addition to Haskell's approach you might also look at Erlang, which has a quite different (and quite interesting) approach to the whole problem. I wonder if anyone has tried to implement a message-passing style of concurrency in Haskell. Mike From hughperkins at gmail.com Fri Aug 10 04:51:49 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 04:43:45 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708100109h216a957etf119605949ef539c@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> <20070810075802.GE5596@cse.unsw.EDU.AU> <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> <20070810080541.GA6778@localhost.localdomain> <837db430708100109h216a957etf119605949ef539c@mail.gmail.com> Message-ID: <837db430708100151k151ccbf2w9e3670d44f87fa6d@mail.gmail.com> Well, managed to shave 25% of C# execution time by writing my own bit array. For now, I will concede that, under the conditions of the shoot, bitarrays in c# are slower than bitarrays in Haskell. I'll let you know if I get any new ideas on this. Getting back to the original problem, which is: threading. Donald, one of the things that is very interesting about Haskell is it's potential for automatic threading, ie you write a trivial algorithm that looks like it runs in a single thread, and the runtime splits it across multiple cores automatically. It's fairly safe to say that maps, foldrs, foldls, and their derivatives are safe to parallelize? (For example, hand-waving argument, a foldr of (/) on [1,5,7,435,46,2] can be split into a foldr on [1,5,7] and a foldr on [435,46,2], then their results combined). To what extent is the technology you are using in your algorithm parallizable? (I actually cant tell, it's a genuine question). In the case that it is parallelizable, to what extent is it trivial for a runtime to know this? (Again, I dont have enough information to tell) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/6d8143de/attachment.htm From hughperkins at gmail.com Fri Aug 10 04:58:36 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 04:50:28 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <46BC26E3.1030902@cs.caltech.edu> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <46BC26E3.1030902@cs.caltech.edu> Message-ID: <837db430708100158m3f2f42e3k91712350933e7e5c@mail.gmail.com> On 8/10/07, Michael Vanier wrote: > > Just to get the history right: garbage collectors have been around a > _long_ time, since the '60s in > Lisp systems. They only became known to most programmers through Java > (which is one unarguable good > thing that Java did). Ah interesting :-) > As for threading, in addition to Haskell's approach you might also look at > Erlang, which has a quite > different (and quite interesting) approach to the whole problem. I wonder > if anyone has tried to > implement a message-passing style of concurrency in Haskell. > Erlang message passing rocks :-) I'd love to see this working in Haskell. Note that Erlang's message passing is not perfect. Specifically, there is zero type or parameter checking. It will quite happily let the following compile: % initialization routines etc go here % ... % ping thread. this sends messages to pong ping() -> pong ! hello, pong ! hello, pong ! {hello}, % this does not throw a compile error pong ! hello, io:format("ping done~n" ). % pong thread, this listens for messages from pong pong() -> receive hello -> io:format("pong received hello~n"), pong() end. You can see that sending the tuple {hello} does not cause a compile time error (or even a runtime error for that matter), even though pong does not have a valid pattern for receiving it. Now, arguably the fact that we are pattern matching on the receiver at least means we dont do anything with the invalid data sent, but this is not rocket science: the standard technique to ensure decent compile time validation in rpc-type things is to use an interface. The interface defines the method names and parameters that you can send across. Both the receiver and the sender have access to the interface definition, and it is trivial to check it at compile time. (Caveat: havent looked enough into Erlang to know if there is a good reason for not using an interface?) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/080ae960/attachment.htm From stefanor at cox.net Fri Aug 10 05:06:28 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 10 04:58:24 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708100151k151ccbf2w9e3670d44f87fa6d@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> <20070810075802.GE5596@cse.unsw.EDU.AU> <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> <20070810080541.GA6778@localhost.localdomain> <837db430708100109h216a957etf119605949ef539c@mail.gmail.com> <837db430708100151k151ccbf2w9e3670d44f87fa6d@mail.gmail.com> Message-ID: <20070810090628.GA7141@localhost.localdomain> On Fri, Aug 10, 2007 at 04:51:49PM +0800, Hugh Perkins wrote: > Well, managed to shave 25% of C# execution time by writing my own bit > array. For now, I will concede that, under the conditions of the shoot, > bitarrays in c# are slower than bitarrays in Haskell. I'll let you know if > I get any new ideas on this. > > Getting back to the original problem, which is: threading. Donald, one of > the things that is very interesting about Haskell is it's potential for > automatic threading, ie you write a trivial algorithm that looks like it > runs in a single thread, and the runtime splits it across multiple cores > automatically. > > It's fairly safe to say that maps, foldrs, foldls, and their derivatives are > safe to parallelize? (For example, hand-waving argument, a foldr of (/) on > [1,5,7,435,46,2] can be split into a foldr on [1,5,7] and a foldr on > [435,46,2], then their results combined). Not really, because Haskell isn't powerful enough to express the fact that (/) is associative. (It isn't, but I'm ignoring that fact since I'm pretty sure it's beside the point). It is possible to do it using an explicit foldb, however, and to a 1st approximation this is what lies behind NDP. On the other hand, division is *much* faster than sparking threads, especially once factors invisible in the code (eg, cache-line ping-pong on scheduler data structures) is taken into account. In the past, optimistic researchers have developed automatic parallelisation algorithms. The best of these were several times slower than decent sequential algorithms. The explicit case, using `par` or equivalent, is more interesting. `par` gives you enough control to implement efficient threading, but is semantically extremely lightweight - you can ignore par using the rule x `par` y === y. Adding or removing par following that rule cannot possibly introduce bugs, far better than the equivalent situation with global mutable data and forkIO! > To what extent is the technology you are using in your algorithm > parallizable? (I actually cant tell, it's a genuine question). In the case > that it is parallelizable, to what extent is it trivial for a runtime to > know this? (Again, I dont have enough information to tell) Something tells me the To: field of your message doesn't correspond with the person you're actually addressing :) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/63f20d8e/attachment.bin From josef.svenningsson at gmail.com Fri Aug 10 06:57:31 2007 From: josef.svenningsson at gmail.com (Josef Svenningsson) Date: Fri Aug 10 06:49:23 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070810011556.GB1377@momenergy.repetae.net> References: <46BB50DC.8020404@btinternet.com> <20070810011556.GB1377@momenergy.repetae.net> Message-ID: <8dde104f0708100357r7f2be279ha44a1a4bb5b53fc7@mail.gmail.com> On 8/10/07, John Meacham wrote: > On Thu, Aug 09, 2007 at 06:37:32PM +0100, Andrew Coppin wrote: > > Which of these is likely to go faster? > > type Quad = (Bool,Bool) > ... > > data Quad = BL | BR | TL | TR > ... > > I'm hoping that the latter one will more more strict / use less space. > > But I don't truely know... > > The second one will be signifigantly better for a couple reasons. A > simple counting of values that they can take on will show not only this > but that they are not isomorphic even, > > (Bool,Bool) can be one of > > _|_ > (True,True) > (True,False) > (False,True) > (False,False) > (_|_,True) > (_|_,False) > (_|_,_|_) > (True,_|_) > (False,_|_) > > that is a total of 10 different cases, each time a bottom might appear, > a thunk evaluation (or indirection) is involved. > > > now, take the second case > > data Quad = BL | BR | TL | TR > > the possible values are > > _|_ > BL > BR > TL > TR > > a whole half of the other representation. > > Well, there are ways to improve the situation. If you want to remove all the bottoms in your type you can define Quad as: type Quad = Data.Strict.Tuple.Pair Bool Bool I'm not sure how much speed this will gain in practice and whether it will beat the four constructor data type though. If anyone does some measurements it'd be interesting to know. Cheers, Josef PS. Data.Strict.Tuple lives in the strict package which can be found here: http://www.cse.unsw.edu.au/~rl/code/strict.html From byorgey at gmail.com Fri Aug 10 07:28:51 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Fri Aug 10 07:20:44 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: References: Message-ID: <22fcbd520708100428r50d71947jdf6b4703ec3377eb@mail.gmail.com> On 8/9/07, Chad Scherrer wrote: > > extract :: [Int] -> [a] -> [a] > extract = f 0 > where > f _ _ [] = [] > f _ [] _ = [] > f k nss@(n:ns) (x:xs) = if n == k then x:f (k+1) ns xs > else f (k+1) nss xs Finally, even if no one else is using it, it would be good to settle > on reasonable names for things more easily. Is there a better name for > this function? Is there a reason not to call it "extract"? Other possible names which occur to me include select, slice, mask. I think I like 'select' best myself, but 'extract' works too. Amusingly, extract is intimately related to function composition. Suppose we have listify :: (Int -> Int) -> [Int] listify = flip map [0..] Then if f, g :: Int -> Int, and f is monotonically increasing, we have the identity (listify f) `extract` (listify g) = listify (g . f) This randomly occurred to me as I was falling asleep last night and I thought I would share. =) -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/c4a4b902/attachment-0001.htm From bulat.ziganshin at gmail.com Fri Aug 10 07:27:58 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Fri Aug 10 07:21:56 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <46BC26E3.1030902@cs.caltech.edu> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <46BC26E3.1030902@cs.caltech.edu> Message-ID: <489779795.20070810152758@gmail.com> Hello Michael, Friday, August 10, 2007, 12:50:43 PM, you wrote: > As for threading, in addition to Haskell's approach you might also > look at Erlang, which has a quite > different (and quite interesting) approach to the whole problem. I wonder if anyone has tried to > implement a message-passing style of concurrency in Haskell. if you mean Erlang's sophisticated rules of which messages in queue to process first - this may be not yet implemented for Haskell. if you mean that program is just many threads which pass messages through channels to each other - it's easily accomplished in Haskell through Chan constructor. you can look at chameneos shootout entry, for example in my program (http://www.haskell.org/bz/FreeArc-sources.tar.gz) i run ~10 threads that process data sequentially - i.e. results of first thread are consumed by second one and so on. i glue them together with my own tiny threads library which somewhat mimics unix pipes: runP$ thread1 |> thread2 |> thread3 ... you can find this lib in Process.hs module. overall, i think that key to Haskell's simplicity of developing multithreaded programs is its immutable data, plus type inference which significantly improves gluing things together and using higher-order funcs -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From hjgtuyl at chello.nl Fri Aug 10 07:38:46 2007 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Fri Aug 10 07:30:31 2007 Subject: [Haskell-cafe] Haskell DB tutorial link is broken. In-Reply-To: <8f66da400708091251m1621a497q15d231c8b03f10eb@mail.gmail.com> References: <8f66da400708091251m1621a497q15d231c8b03f10eb@mail.gmail.com> Message-ID: I suppose you mean the link at http://haskelldb.sourceforge.net/#documentation you can find the tutorial at the Wayback Machine: http://web.archive.org/web/20070514141711/http://www.haskell.org/hawiki/HaskellDbTutorial Regards, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- On Thu, 09 Aug 2007 21:51:06 +0200, Edward Ing wrote: > Hi, > The following link is broken. > http://www.haskell.org/hawiki/HaskellDbTutorial > > Edward Ing > _______________________________________________ -- Met vriendelijke groet, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- From bulat.ziganshin at gmail.com Fri Aug 10 07:38:40 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Fri Aug 10 07:54:23 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070810064636.GC5596@cse.unsw.EDU.AU> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <837db430708092308l8b3f52eq3990dab74c6053f@mail.gmail.com> <20070810062330.GA6402@localhost.localdomain> <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> <20070810064636.GC5596@cse.unsw.EDU.AU> Message-ID: <1226354610.20070810153840@gmail.com> Hello Donald, Friday, August 10, 2007, 10:46:36 AM, you wrote: > Hmm. Not looking so good so for for the imperative, GC'd languages. > > Java? > > http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=ghc&lang2=java > C#? Donald, i have written (an not once) that most of shooutout entries doesn't check speed of compiled code. for example, in one test TCL was the fastest language, because in most cases they measure speed of shipped libs or RTS so Hugh is right. making Haskell as fast as Java/C# will *significantly* increase its userbase. in particular, i'm now interested in development of large systems using Haskell and main problem in doing this its low performance so please don't consider this as words against Haskell, better look at your own highly-optimized code in FPS/shootout and decide whether it's written in high-level FP style? -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From Malcolm.Wallace at cs.york.ac.uk Fri Aug 10 08:31:27 2007 From: Malcolm.Wallace at cs.york.ac.uk (Malcolm Wallace) Date: Fri Aug 10 08:42:48 2007 Subject: [Haskell-cafe] can't build haxml under ghc 6.7, says HughesPJ is hidden... but ghc-pkg doesn't say it's hidden... In-Reply-To: <20070809230251.GA4834@localhost.localdomain> References: <20070809230251.GA4834@localhost.localdomain> Message-ID: <20070810133127.28ee0d30.Malcolm.Wallace@cs.york.ac.uk> Stefan O'Rear wrote: > When you build a package, Cabal passess the -hide-all-packages option > to GHC, which prevents the package from using any installed packages > other than the ones explicitly listed in the Build-Depends: field. > > For now, we just edit .cabal files when transporting code between GHC > versions... Just for information, the HaXml darcs repo has recently adopted the solution of containing two .cabal files, one for ghc-6.6.x, and the other for the split-base packages (>=ghc-6.7). The only difference is the build-depends line, which is now as follows: build-depends: base, haskell98, polyparse, pretty, fps But if you have collected the earlier release HaXml-1.13.2 from hackage, then you can omit both 'polyparse' and 'fps' dependencies. ('fps' will shortly be changing to 'bytestring' in any case...) Regards, Malcolm From hughperkins at gmail.com Fri Aug 10 09:24:39 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 09:16:31 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <20070810080356.GF5596@cse.unsw.EDU.AU> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> <20070810075802.GE5596@cse.unsw.EDU.AU> <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> <20070810080356.GF5596@cse.unsw.EDU.AU> Message-ID: <837db430708100624q7a08303btec12b54efda77643@mail.gmail.com> On 8/10/07, Donald Bruce Stewart wrote: > > No, STUArray s Int Bool is a bit array. > Look at the space use. Or try replacing Bool with Word32, and see what > happens. > Fair enough. Well, the mono example in the shootout is lacking quite a few optimizations, eg its using the builtin BitArray (slowww....), and it's not checking for the value of the bits before writing them. I dont quite get as fast as your ghc version (yet ;-) ), but its within 10% on my machine, using Microsoft C#, and staying within the rules of the shootout. G:\dev\haskell>primeshootoutmono3 Primes up to 10240000 679461 elapsed time: 0.921875 G:\dev\haskell>primeshootoutghc Primes up to 10240000 679461 0.8280000000000001 class NSieveBits { public int nsieve(int m) { int[] isNotPrime = new int[((m+1) >> 5) + 1]; int count = 0; int wordindex = 0; int bitmask = 4; for (int i=2; i <= m; i++) { //Console.WriteLine( i + " " + wordindex + " " + bitmask ); if ( ( isNotPrime[wordindex] & bitmask ) == 0 ) { //Console.WriteLine("prime: " + i ); for (int k = (i << 1); k <= m; k+=i) { int _wordindex = k >> 5; int _bitmask = 1 << ( k & 31 ); int _thisword = isNotPrime[_wordindex]; if( ( _thisword & _bitmask ) == 0 ) { isNotPrime[ _wordindex ] = _thisword | _bitmask; } } count++; } if( bitmask == ( 1 << 31 ) ) { wordindex++; bitmask = 1; } else { bitmask <<= 1; } } return count; } } It'd be more interesting to run these things in a multicore environment (16 cores would be ok, 64 would be better). Are there any utilities out there to do this? (vmware???) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/2d2f04ee/attachment.htm From hughperkins at gmail.com Fri Aug 10 09:31:13 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 09:23:05 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> Message-ID: <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> Not many replies on this thread? Am I so wrong that no-one's even telling me? I find it hard to believe that if there were obvious errors in the proposition that anyone would resist pointing them out to me ;-) So, that leaves a couple of possibilites: some people are agreeing, but see no point in saying; or noone cares, because we all only have 1 or 2 core machines. I'm going to kindof run with the second possibility for now. However, I do believe it's the right time to solve this, what with 64-core Niagara's around the corner and so on. What would be neat would be a way to test solutions on simulated 1024-core machines, using a single-core machine. Are there any utilities or virtual environments around that might make this kind of testing feasible? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/5656a906/attachment.htm From dry.green.tea at gmail.com Fri Aug 10 09:31:43 2007 From: dry.green.tea at gmail.com (Alexis Hazell) Date: Fri Aug 10 09:23:40 2007 Subject: [Haskell-cafe] Monad Description For Imperative Programmer In-Reply-To: <46BA0544.3050500@ropine.com> References: <8aa524530708010002n3a91f9dds6582d45cb5924556@mail.gmail.com> <12055086.post@talk.nabble.com> <46BA0544.3050500@ropine.com> Message-ID: <200708102331.45027.dry.green.tea@gmail.com> On Thursday 09 August 2007 04:02, Seth Gordon wrote: > I feel like I still don't understand comonads. If you haven't done so already, you might like to check out: "(Co)Monads for Grad Students" http://www.cas.mcmaster.ca/~carette/CAS706/F2006/presentations/comonads.pdf "Codata and Comonads in Haskell" http://www.cse.ogi.edu/PacSoft/publications/phaseiiiq10papers/codata.pdf Aelxis. From jmaessen at alum.mit.edu Fri Aug 10 10:38:31 2007 From: jmaessen at alum.mit.edu (Jan-Willem Maessen) Date: Fri Aug 10 10:30:03 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> Message-ID: <2C404654-E8E1-4F40-96CA-EEAB53E9C7EE@alum.mit.edu> On Aug 10, 2007, at 9:31 AM, Hugh Perkins wrote: > Not many replies on this thread? Am I so wrong that no-one's even > telling me? I find it hard to believe that if there were obvious > errors in the proposition that anyone would resist pointing them > out to me ;-) > > So, that leaves a couple of possibilites: some people are agreeing, > but see no point in saying; or noone cares, because we all only > have 1 or 2 core machines. > > I'm going to kindof run with the second possibility for now. > However, I do believe it's the right time to solve this, what with > 64-core Niagara's around the corner and so on. > > What would be neat would be a way to test solutions on simulated > 1024-core machines, using a single-core machine. Are there any > utilities or virtual environments around that might make this kind > of testing feasible? It's actually difficult to do realistic simulations of large machines like this; most of the performance effects you'll see depend on the behavior of the cache and memory subsystems, and it's difficult and expensive to simulate those well. So, for example, you could use something like Simics to simulate a 1024-core machine, but it'd be expensive (Simics costs money), slow (100x? slower than ordinary execution) and non-parallel (so you wouldn't be able to run it on a currently-extant multiprocessor box in the hopes of speeding up the simulation). Between the simulator slowdown and the fact that you're simulating 1024 cores using only 1 thread, you can expect to wait a long time for simulation results. Also, these things tend to require an awful lot of care and feeding. [Full disclosure: I don't personally work with Simics or its ilk, but my colleagues do.] -Jan-Willem Maessen From Alistair_Bayley at invescoperpetual.co.uk Fri Aug 10 10:43:52 2007 From: Alistair_Bayley at invescoperpetual.co.uk (Bayley, Alistair) Date: Fri Aug 10 10:35:43 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com><20070810050139.GU3382@cse.unsw.EDU.AU><837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> Message-ID: <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> > From: haskell-cafe-bounces@haskell.org > [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Hugh Perkins > > Not many replies on this thread? Am I so wrong that no-one's > even telling me? I find it hard to believe that if there > were obvious errors in the proposition that anyone would > resist pointing them out to me ;-) Well, I vaguely recall a study which analysed a number of programs and determined that there was not a lot of inherent parallelism in them, so the effort to automate parallelism wouldn't have much payoff. Wait a sec... This isn't it, but seems relevant: http://www.detreville.org/papers/Limits.pdf Here you go: http://citeseer.ist.psu.edu/tremblay95impact.html > So, that leaves a couple of possibilites: some people are > agreeing, but see no point in saying; or noone cares, because > we all only have 1 or 2 core machines. Well, the Harris/Singh paper summarises the common problems: - not many programs are inherently parallel - parallelism must be quite coarse to offset overheads (which I think is the problem with expecting things like map and fold to parallelised automagically; they're just too small grained for it to be worthwhile) - lazy evaluation makes it harder Basically, it's harder than it sounds. This is where NDP looks good. Although you have to explicitly label parallel operations, you get to use your functional tools like map and fold, etc. Alistair ***************************************************************** Confidentiality Note: The information contained in this message, and any attachments, may contain confidential and/or privileged material. It is intended solely for the person(s) or entity to which it is addressed. Any review, retransmission, dissemination, or taking of any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you received this in error, please contact the sender and delete the material from any computer. ***************************************************************** From afalloon at synopsys.com Fri Aug 10 10:59:25 2007 From: afalloon at synopsys.com (Al Falloon) Date: Fri Aug 10 10:51:38 2007 Subject: [Haskell-cafe] Re: Polymorphic variants In-Reply-To: <200708021418.40858.dan.doel@gmail.com> References: <200707252304.17136.jon@ffconsultancy.com> <8dde104f0707251607i14400bc7y338e4dc20796387@mail.gmail.com> <200708021832.33331.jon@ffconsultancy.com> <200708021418.40858.dan.doel@gmail.com> Message-ID: <46BC7D4D.4070006@synopsys.com> The proposal that I like the most is this one: "Open Data Types and Open Functions" http://lambda-the-ultimate.org/node/1453 However, it doesn't readily admit using the variants as overlapping enumerations like John suggested in a previous thread: http://article.gmane.org/gmane.comp.lang.haskell.cafe/23362 In fact it doesn't really support structural sub-typing at all (the way that polymorphic variants in Ocaml do), but it does support independent extension (which PV's don't do). Dan Doel wrote: > P.S.: Some papers: > > http://www.cse.ogi.edu/PacSoft/publications/2000/extensiblerecords.pdf > > http://research.microsoft.com/users/daan/download/papers/scopedlabels.pdf > > The second actually discusses all the operations on variants and whatnot. The > first just mentions that it's a related topic. From claus.reinke at talk21.com Fri Aug 10 11:06:21 2007 From: claus.reinke at talk21.com (Claus Reinke) Date: Fri Aug 10 10:58:17 2007 Subject: [Haskell-cafe] can't build haxml under ghc 6.7, says HughesPJis hidden... but ghc-pkg doesn't say it's hidden... References: <20070809230251.GA4834@localhost.localdomain> <20070810133127.28ee0d30.Malcolm.Wallace@cs.york.ac.uk> Message-ID: <022701c7db60$043d2d50$8c077ad5@cr3lt> >> For now, we just edit .cabal files when transporting code between GHC >> versions... > > Just for information, the HaXml darcs repo has recently adopted the > solution of containing two .cabal files, one for ghc-6.6.x, and the > other for the split-base packages (>=ghc-6.7). The only difference is > the build-depends line, which is now as follows: > > build-depends: base, haskell98, polyparse, pretty, fps > > But if you have collected the earlier release HaXml-1.13.2 from hackage, > then you can omit both 'polyparse' and 'fps' dependencies. ('fps' will > shortly be changing to 'bytestring' in any case...) would it be possible to put more emphasis on continuity in haskell (just as there should be an emphasis on portability;-)? when changing language, tools, or libraries in a way that breaks existing programs, deprecating the old api for one version before removing it is rarely sufficient, and leads to breakage rather than hackage.. it would be nice if anyone thinking of breaking a public api would spend some thought on code transitions. be it by providing compatibility adapters, or code transformations, or whatever. users should not be so accepting of breaking changes, either. yes, you may be able to work around the issues, but what good are package managers if they only work with workarounds? in this particular case, the rest-base simply doesn't do what base did, so it shouldn't be named base. instead, perhaps there should be a virtual base package that only tracks the dependencies needed to support the old base? similarly for the now-its-in-now-it-isnt fps/bytestring. :-) claus From rendel at rbg.informatik.tu-darmstadt.de Fri Aug 10 11:26:20 2007 From: rendel at rbg.informatik.tu-darmstadt.de (Tillmann Rendel) Date: Fri Aug 10 11:18:32 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: References: Message-ID: <46BC839C.40003@rbg.informatik.tu-darmstadt.de> Chad Scherrer wrote: > extract :: [Int] -> [a] -> [a] > > [...] > > This behaves roughly as > extract ns xs == map (xs !!) ns extract sounds like removing the elements to be extracted from the original list. I would therefore expect it's type signature to be extract :: [Int] -> [a] -> ([a], [a]) with extract [0, 2] "abcde" == ("ac", "bde"). For your extract I would prefer "select" as name, in analogy to relational algebra, viewing a list as a one-column table. > Oh, and "ns" are required to be ordered and non-negative. Non-negative is obvious for a list of indexes. Ordered makes sense implementation-wise, and should be easy to match for many applications. But is it a sensible constraint on a standard library function? For Data.List, I would prefer a multi-pass select function like this: select :: Integral n => [n] -> [a] -> [a] select ns xs = select' 0 ns xs where select' k [] _ = [] select' k (n:ns) [] = select' k ns [] select' k nns@(n:ns) yys@(y:ys) = case k `compare` n of LT -> select' (succ k) nns ys EQ -> y : select' k ns yys GT -> select nns xs *Main> select [0, 2, 2, 1] "abcde" "accb" There could be selectAsc for the special case of ordered indexes, to avoid keeping the whole input list in memory. Tillmann From chad.scherrer at gmail.com Fri Aug 10 11:38:31 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Fri Aug 10 11:30:23 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: <22fcbd520708100428r50d71947jdf6b4703ec3377eb@mail.gmail.com> References: <22fcbd520708100428r50d71947jdf6b4703ec3377eb@mail.gmail.com> Message-ID: Hmm, this would make a good QuickCheck property. I wonder, is listify a contravariant functor? Fun to work through the details of that some time, I think. Chad On 8/10/07, Brent Yorgey wrote: > > Amusingly, extract is intimately related to function composition. Suppose we > have > > listify :: (Int -> Int) -> [Int] > listify = flip map [0..] > > Then if f, g :: Int -> Int, and f is monotonically increasing, we have the > identity > > (listify f) `extract` (listify g) = listify (g . f) > > This randomly occurred to me as I was falling asleep last night and I > thought I would share. =) > > -Brent From chad.scherrer at gmail.com Fri Aug 10 11:41:09 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Fri Aug 10 11:33:00 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: <46BC839C.40003@rbg.informatik.tu-darmstadt.de> References: <46BC839C.40003@rbg.informatik.tu-darmstadt.de> Message-ID: Agreed. I like "select" better too, and the regular vs "Asc" version is a nice parallel with fromList and fromAscList. Chad On 8/10/07, Tillmann Rendel wrote: > Non-negative is obvious for a list of indexes. Ordered makes sense > implementation-wise, and should be easy to match for many applications. > But is it a sensible constraint on a standard library function? > > For Data.List, I would prefer a multi-pass select function like this: > > select :: Integral n => [n] -> [a] -> [a] > select ns xs = select' 0 ns xs where > select' k [] _ = [] > select' k (n:ns) [] = select' k ns [] > select' k nns@(n:ns) yys@(y:ys) = case k `compare` n of > LT -> select' (succ k) nns ys > EQ -> y : select' k ns yys > GT -> select nns xs > > *Main> select [0, 2, 2, 1] "abcde" > "accb" > > There could be selectAsc for the special case of ordered indexes, to > avoid keeping the whole input list in memory. > > Tillmann From afalloon at synopsys.com Fri Aug 10 11:45:08 2007 From: afalloon at synopsys.com (Al Falloon) Date: Fri Aug 10 11:37:26 2007 Subject: [Haskell-cafe] Re: Interval Arithmetics In-Reply-To: References: Message-ID: <46BC8804.4060407@synopsys.com> Mitar wrote: > Hi! > > First, disclaimer: everything I know about interval arithmetics comes > from this video: > > http://video.google.com/videoplay?docid=-2285617608766742834 The discussion in the implementation of the Boost Interval Arithmetic Library is also useful. http://www.boost.org/libs/numeric/interval/doc/interval.htm > > I would like to know if there is any implementation of interval > arithmetics in Haskell? I would like to play a little with that. I > checked the web and the straightforward approach I found: > > http://cs.guc.edu.eg/faculty/sabdennadher/Publikationen/paper-wflp99.ps.gz > > has from my point of view invalid implementation. For example, lower > bound in the sum should not be just calculated as the sum of lower > bounds of summands. It should return the greatest representable number > which is smaller or equal to the exact value of the sum. With just > boldly making a sum we ignore any errors we could introduce and this > is somehow against the idea of interval arithmetics. Correct. > > And as it is said at the end of the talk, a system behind interval > arithmetics should do a lot of work to make those intervals as small > as possible while still correct and counting in all the errors we > accumulated. > > I think a strict-typed and lazy language like Haskell would be a good > place to implement this. But I would like to know if this would be > possible to do from the language itself, without making changes to the > compiler and/or runtime itself? Because, for example, a good > implementation should reformulate equations at the runtime accordingly > to exact values it wants to compute them on. For intervals of floating point numbers you will need to gain access to the FPU rounding modes for the machine (see some discussion here http://www.boost.org/libs/numeric/interval/doc/rounding.htm). I don't think that that is provided in the basic libraries so you would need to use the FFI to get it from C. And proper rounding isn't available on all platforms. For unbounded values defined in Haskell (like Integer and Rational) you need to provide round-down and round-up versions of operations that won't produce exact answers (like division on Integer and sqrt on Rational). Probably some sort of clever type-class setup could be used to provide rounding functions for intervals (the same way Ix does clever indexing for Array). > Has it been done already? Sorry, not that I know of. From consalus at gmail.com Fri Aug 10 12:10:55 2007 From: consalus at gmail.com (Kyle Consalus) Date: Fri Aug 10 12:02:46 2007 Subject: [Haskell-cafe] Erlang-style concurrency Message-ID: <9cc3782b0708100910l3e291ba7u8ebe54b56c9e6dab@mail.gmail.com> In digest #69, Hugh Perkins mentioned the coolness of Erlang-style message passing concurrency. It just so happened that I was playing with that yesterday, so I figured I'd post a link to a 'ping-pong' thing that I based on an example in the erlang tutorial. I figured "Haskell has lightweight threads, higher order functions, and pattern matching. No reason that with a little bit of STM and some monadic convenience we can't do message passing." It's really simplistic and doesn't parameterize message type (well, not this version; that version is still in the works), but I thought someone might find it amusing just the same. http://hpaste.org/2174 From droundy at darcs.net Fri Aug 10 12:29:37 2007 From: droundy at darcs.net (David Roundy) Date: Fri Aug 10 12:21:33 2007 Subject: [Haskell-cafe] Matters of precision In-Reply-To: <46BB5318.7080904@btinternet.com> References: <46BB5318.7080904@btinternet.com> Message-ID: <20070810162937.GE30654@darcs.net> On Thu, Aug 09, 2007 at 06:47:04PM +0100, Andrew Coppin wrote: > First of all, currently I'm just using Double to represent coordinates. > Can anybody tell me what the smallest value you can represent with one > is? (Not including denormals.) The smallest number is around 1e-300, but the smallest fractional difference (which is probably what's biting you) is around 1e-15. > Next up, at some point I'm going to need more precision than a Double > can give me. (But, obviously, I still want the thing to go as fast as > humanly possible.) In particular, I do NOT want to go into "infinite" > precision. (E.g., exact arithmetic with arbitrary fractions.) I want to > be able to make the precision arbitrarily high, but still finite and > fixed. (The idea being that the further you zoom in, the more the > computer turns up the precision.) Is there anything useful for this in > the standard libraries? Or will I have to write something? I suspect you can acheive this by changing your algorithm and data structures, rather than your floating point type. If you store relative positions rather than absolute positions, then as your fractal gets smaller and smaller, your precision should continue to be good. Danger only arises when you try to compare (or subtract) two doubles whose difference is much smaller than their magnitude. By definition, fractal geometries don't require you to do this. -- David Roundy Department of Physics Oregon State University From andrewcoppin at btinternet.com Fri Aug 10 13:06:07 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 10 12:57:24 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070810065222.GA6474@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <837db430708092308l8b3f52eq3990dab74c6053f@mail.gmail.com> <20070810062330.GA6402@localhost.localdomain> <837db430708092328k129309f7ob9e929a1371a68c0@mail.gmail.com> <20070810065222.GA6474@localhost.localdomain> Message-ID: <46BC9AFF.7030201@btinternet.com> Stefan O'Rear wrote: > > Just wait 12 years, and if the price of processors follows Moore's > extrapolation and the Haskell keeps its parallelism, Haskell will win :) > Nice idea. Unfortunately, writing code in Haskell does not [yet] magically cause it to become "parallel". It's just that writing [pure] code in Haskell is inherently thread-safe. ;-) I'm very excited about things like fusion and data-parallel Haskell and so forth that seem to be "out there on the horizon", but in the "right now" I'm not sure how easy it is to write parallel Haskell code. (So far I haven't even tried. Unless you count standard "server that spawns processes when clients connect" type stuff...) From andrewcoppin at btinternet.com Fri Aug 10 13:12:03 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 10 13:03:20 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070810070540.GB6474@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <46BC0514.6030806@btinternet.com> <20070810070540.GB6474@localhost.localdomain> Message-ID: <46BC9C63.1030504@btinternet.com> Stefan O'Rear wrote: > On Fri, Aug 10, 2007 at 07:26:28AM +0100, Andrew Coppin wrote: > >> My program needs to make decisions based on a pair of boolean values. >> Encoding both values as a single algebraic data type means I have to keep >> "taking it apart" so I can work with it. I'm not sure how much time this >> wastes... >> > > Good point... > I suppose the only sure way to find out is to test. (IIRC, doesn't GHC have a tendance to "take apart" tuples anyway?) >>> Probably. I wound up doing something similar with vty, to considerable >>> gain. (I did however use .&. instead of testBit - probably makes no >>> difference, but I'm reminded of the (^2) being much slower than join(*) >>> case...) >>> >> Well, perhaps I could define a pair of constants representing the bit >> masks? (OTOH, won't GHC optimise "testBit " into something faster >> anyway?) >> > > Probably not; GHC has few rules for dealing with partial evaluation on > numeric arguments. Asking GHC itself: > > stefan@stefans:/tmp$ ghc -c -ddump-simpl -O2 X.hs > > ==================== Tidy Core ==================== > X.moo [NEVER Nothing] :: forall a_a82. GHC.Base.Int -> a_a82 -> a_a82 -> a_a82 > [GlobalId] > [Arity 3 > NoCafRefs > Str: DmdType U(L)LL] > X.moo = > \ (@ a_a88) (ix_a84 :: GHC.Base.Int) (ift_a85 :: a_a88) (iff_a86 :: a_a88) -> > case ix_a84 of wild_acF { GHC.Base.I# x#_acH -> > case Data.Bits.$w$s$dmbit 7 of ww1_acN { __DEFAULT -> > case GHC.Prim.word2Int# > (GHC.Prim.and# (GHC.Prim.int2Word# x#_acH) (GHC.Prim.int2Word# ww1_acN)) > of wild1_acO { > __DEFAULT -> ift_a85; 0 -> iff_a86 > } > } > } > > > > > ==================== Tidy Core Rules ==================== > > > stefan@stefans:/tmp$ cat X.hs > module X where > > import Data.Bits > > {-# NOINLINE moo #-} > -- ghc doesn't optimize functions that are deemed small enough for inlining; > -- this is a good thing (since when we inline we know more about the context > -- and can do a better job if we wait until then), but interferes with small > -- experiments like this > > moo :: Int -> a -> a -> a > moo ix ift iff = if testBit ix 7 then ift else iff > stefan@stefans:/tmp$ > > > The important bit is the (Data.Bits.$w$s$dmbit 7). Since that function > doesn't do IO (no realworld arguments), it could in theory be evaluated > at compile time (and judging from context it almost surely evaluates to > 128#), but it hasn't been. > Mmm. See, now, I have *no idea* what GHC is saying. But I would have expected that if I do something like x = if testBit 3 q ... then the definition of testBit would get inlined, and then hopfully the optimiser would do something. But then, IANAGD. (I am not a GHC developer.) >> Like that time yesterday, I compiled from program and got a weird message >> about GHC about "ignored trigraphs" or something... What the heck is a >> trigraph? >> > > Everyone's favorite obscure feature of the ANSI C99 preprocessor. > Probably you had something like "this is odd???" in your source code, > and were using -cpp. > > http://www.vmunix.com/~gabor/c/draft.html#5.2.1.1 > Er... wow. OK, well I have no idea what happened there... (I'm not using -cpp. I don't even know what it is.) I had presumed GHC was upset because it got killed on the previous run... (I was running something else and it locked up the PC.) >>> Good idea! Maybe it could be fit into the GHC Performance Resource >>> somehow? (http://www.haskell.org/haskellwiki/Performance/GHC) >>> >> OK. But it'll probably contain a lot of guessing to start with... ;-) >> > > Wiki pages can be fixed. Private misunderstandings can't, at least not > anywhere near as easily. > Point taken... ;-) From stefanor at cox.net Fri Aug 10 13:20:33 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 10 13:12:25 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <46BC9C63.1030504@btinternet.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <46BC0514.6030806@btinternet.com> <20070810070540.GB6474@localhost.localdomain> <46BC9C63.1030504@btinternet.com> Message-ID: <20070810172033.GA3724@localhost.localdomain> On Fri, Aug 10, 2007 at 06:12:03PM +0100, Andrew Coppin wrote: > > [big blob of simplifier output] > > Mmm. See, now, I have *no idea* what GHC is saying. But I would have > expected that if I do something like > > x = if testBit 3 q ... > > then the definition of testBit would get inlined, and then hopfully the > optimiser would do something. But then, IANAGD. (I am not a GHC developer.) Sure, it gets inlined, and you wind up with something like: x = case 3 .&. (1 `shiftL` q) of 0 -> ... _ -> ... or, if you used the (correct and unintuitive) argument order to testBit: x = case q .&. (1 `shiftL` 3) of 0 -> ... _ -> ... We *want* (1 `shiftL` 3) to be reduced to 8 at compile time, but that doesn't seem to be happening. (And I'm not a GHC developer either. I should probably start at some point...) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/54dd41b3/attachment.bin From hughperkins at gmail.com Fri Aug 10 13:27:39 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 13:19:31 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> Message-ID: <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> On 8/10/07, Bayley, Alistair wrote: > > Well, the Harris/Singh paper summarises the common problems: > - not many programs are inherently parallel If thats the case, then multicores are not going to be very useful. Where there's a will there's a way. What I think is: if maps etc will be parallelized out where necessary by the runtime, then people will adapt their programs to use them. Right now, many people use imperative loops in Haskell to get the highest performance (see the shootout examples for example). In the future, this will be shunned in preference of standard map and foldb operations. - parallelism must be quite coarse to offset overheads > (which I think is the problem with expecting things like map and fold > to parallelised automagically; they're just too small grained for it to > be worthwhile) Someone else said that. I dont understand what you mean. Imagine I have a map like this: map f [1..100000] ... and I have 64 cores.. So I divide the 100000 elements in my list by 64, and give each chunk of 1000-ish elements to each thread. Easy I think? Note that NDP is doing this too, *but NDP is trying to do this for assymetric elements at compile-time, which is generally impossible*. I propose doing it at runtime, inside the VM, which is trivial and optimal. More details/examples: It's trivial to improve on NDP at runtime. For example: - we split our map into 64 pieces, give each one to a thread - one piece finishes earlier than the others -> we split one of the other pieces in two, and give one piece to the finished thread - and so on... -> reasonably optimal Another example: - we have a map of 64 elements, so we give one element to each thread - all of the pieces but one finishes really quickly (say, within 1 second) - so, we start to look at what is happening within the remaining piece -> turns out it contains another map, so we split that map amongst our idle threads -> and so on Easy, flexible. - lazy evaluation makes it harder Not at runtime ;-) Basically, it's harder than it sounds. No ;-) The more I talk about this the more confident I feel that this is an easy, optimal solution. The bits that stand out as being hard: - people making their programs use map, foldb etc -> but I dont have to do that, it will happen automatically. Its sortof like distributing bread automatically to people in London, via the free market. Do you know that the Russians once asked the Western world who was responsible for distributing bread to people in London? Answer: noone is, it happens automatically ;-) - migrate Haskell/GHC/Erlang/some-other-FP to have a bytecode/VM layer - create a 1024-ish-core simulator. In fact this is the only bit that I dont have a clear vision for. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/fb721f2f/attachment.htm From andrewcoppin at btinternet.com Fri Aug 10 13:35:10 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 10 13:26:27 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <20070810172033.GA3724@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <46BC0514.6030806@btinternet.com> <20070810070540.GB6474@localhost.localdomain> <46BC9C63.1030504@btinternet.com> <20070810172033.GA3724@localhost.localdomain> Message-ID: <46BCA1CE.7040509@btinternet.com> Stefan O'Rear wrote: > or, if you used the (correct and unintuitive) argument order to testBit: > GAH! >_< Do you have ANY IDEA how many times I've got that wrong so far?? All I can say is thank God that Haskell is a statically-typed language! The type checker has saved my life here more times than I can count... [I seem to recall tripping over the order that the various array functions are expecting too...] > x = case q .&. (1 `shiftL` 3) of > 0 -> ... > _ -> ... > > We *want* (1 `shiftL` 3) to be reduced to 8 at compile time, but that > doesn't seem to be happening. > > (And I'm not a GHC developer either. I should probably start at some > point...) > Heh. There seems to be a lot of people floating around here who are. And whereas people often have to say "I am not a lawyer", round here it seems to be frequenctly necessary to say "...but I'm not a GHC developer". ;-) From andrewcoppin at btinternet.com Fri Aug 10 13:37:31 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 10 13:28:47 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <20070810080541.GA6778@localhost.localdomain> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> <20070810075802.GE5596@cse.unsw.EDU.AU> <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> <20070810080541.GA6778@localhost.localdomain> Message-ID: <46BCA25B.4030600@btinternet.com> Stefan O'Rear wrote: > Bool is 32 bits, but Don is using UArray. UArray is not parametric in > the element type, which means it's less generally useful (no UArray of > Complex Double, for instance), but conversely it is able to use more > efficient representations depending on the type. > Would be nice if it *could* somehow be parametric... but I have absolutely no idea how you'd do that. The transformation is self-evident enough to a human, but how do you explain it to a machine? (I somewhat suspect you'd have to bake this into the compiler itself it you wanted *arbitrary* types. Otherwise you'd have to write some special class that knows how to pack and unpack the data from the array, perhaps as a bundle of Word8s or something? Doesn't sound hugely fast...) From hughperkins at gmail.com Fri Aug 10 13:47:23 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 13:39:19 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <489779795.20070810152758@gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <46BC26E3.1030902@cs.caltech.edu> <489779795.20070810152758@gmail.com> Message-ID: <837db430708101047p634dc743hbf1a081af7c42ab8@mail.gmail.com> On 8/10/07, Bulat Ziganshin wrote: > > if you mean Erlang's sophisticated rules of which messages in queue to > process first - this may be not yet implemented for Haskell. if you > mean that program is just many threads which pass messages through > channels to each other - it's easily accomplished in Haskell through > Chan constructor. you can look at chameneos shootout entry, for > example > Forgot to mention, a really cool thing about Erlang message-passing is that the other thread doesnt have to be on the same machine ;-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/38d42c88/attachment-0001.htm From andrewcoppin at btinternet.com Fri Aug 10 13:49:58 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 10 13:41:15 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> Message-ID: <46BCA546.3030507@btinternet.com> Hugh Perkins wrote: > > - parallelism must be quite coarse to offset overheads > (which I think is the problem with expecting things like map > and fold > to parallelised automagically; they're just too small grained for > it to > be worthwhile) > > > Someone else said that. I dont understand what you mean. If you do 1+2+3+4, it's not very efficient to spawn a new thread, have that compute 1+2, compute 3+4 in the current thread, synchronise, and do the final addition. You waste more time starting and stopping threads than doing useful work. If you're going to spawn a new thread, it needs to do "lots" of work for it to be worth it. And this is kinda what makes this stuff so tricky - between lazyness and the Halting Problem, it's hard to work out what is "worth" sparking a thread for... > Imagine I have a map like this: > > map f [1..100000] > > ... and I have 64 cores.. > > So I divide the 100000 elements in my list by 64, and give each chunk > of 1000-ish elements to each thread. Easy I think? ...you realise that that's a linked-list you have there, right? ;-) Now, if you had an *array*, and you know that "f" does a constant amount of work for all elements, and that all array elements will eventually be "needed"... > Note that NDP is doing this too, *but NDP is trying to do this for > assymetric elements at compile-time, which is generally impossible*. > I propose doing it at runtime, inside the VM, which is trivial and > optimal. Parallel and trivial in the same sentence? Hmm, I wonder... how did this problem not get solved 20 years ago? Oh, wait, maybe because it's harder than it looks. ;-) It certainly looks *easier* to partition the work at run-time than compile-time. But trivial? I doubt it. (For a start, and autosensing magic you add mustn't slow the program down more than the parallelism it's supposed to be generating!) > It's trivial to improve on NDP at runtime. For example: > > - we have a map of 64 elements, so we give one element to each thread > - all of the pieces but one finishes really quickly (say, within 1 > second) > - so, we start to look at what is happening within the remaining piece > -> turns out it contains another map, so we split that map amongst our > idle threads > -> and so on > > Easy, flexible. Seems to require running some sort of "monitor" process which can somehow "see" what operation(s) a thread is trying to do so it can split up the work and share it around. That's going to add overhead. Now that's OK so long as the gains outweight the overhead... > - lazy evaluation makes it harder > > > Not at runtime ;-) O RLY? The problem with things being lazy is that you don't know whether some data is "needed" until the moment you actually come to need it. OTOH, ideally you'd want to know way in advance so that you can compute it in parallel and it will already be "ready" when you come to use it. But with lazyness, you can't [easily] do that. Doing the resting at run-time isn't helping you here... > Basically, it's harder than it sounds. > > > No ;-) The more I talk about this the more confident I feel that > this is an easy, optimal solution. How does the saying go? "Anything is easy for the man who does not have to implement it..." From brian.sniffen at gmail.com Fri Aug 10 15:01:18 2007 From: brian.sniffen at gmail.com (Brian Sniffen) Date: Fri Aug 10 14:53:11 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: References: <46BC839C.40003@rbg.informatik.tu-darmstadt.de> Message-ID: Posix has pretty well taken the name "select." It probably isn't a good idea to use that name in a commonly imported library like Data.List, since users will have to mask and qualify it if they also import Posix libraries. -- Brian T. Sniffen bts@alum.mit.edu or brian.sniffen@gmail.com http://www.evenmere.org/~bts From lgreg.meredith at biosimilarity.com Fri Aug 10 15:18:38 2007 From: lgreg.meredith at biosimilarity.com (Greg Meredith) Date: Fri Aug 10 15:10:32 2007 Subject: [Haskell-cafe] towards a new foundation for set theory with atoms Message-ID: <5de3f5ca0708101218j56a7b84fj50acef000dfb8433@mail.gmail.com> Haskellians, i have a particular interest in FM-set theory in that it simplifies a host of otherwise non-trivial aspects of programming language semantics, especially, fresh names. You can provide semantics without sets with atoms, but the functor category machinery is more than a little on the heavy side. The down side of FM-set theory is that it posits an infinite collection of atomic entities -- atomic in the sense that they have no observable internal structure. This poses a real problem for computational accounts. No where do we have an infinite supply of atomic entities. All our infinite collections need some finite presentation -- some basic starting structure and then a finite set of rules that say how to generate the rest. This is particularly important since the atoms have to come with a equality predicate. If the predicate cannot inspect internal structure, then the equality predicate is too big to hold in any finitely presentable computation. Thus, there's a little conundrum: how do you get all the conveniences of a set theory with atoms and still have a finite presentation? Here's one approach. The issue is that atoms cannot have internal structure observable by the set-theoretic operators, \in : Set -> Atom + Set -> Bool, and { - } : [Atom + Set] -> Set. That doesn't mean they can't have structure. Where would this structure come from? Well, it's related to another observation about sets: they're really collections of pointers. More specifically, the axiom of extensionality says that two sets are equal iff they have exactly the same members. Thus, wherever we see the set { } it's the same. Therefore, in { { }, { { } } } we see the very same set occurring in two locations. This is not very physical. These notions of location or identity must be more logical notions. And, one obvious way to resolve this is that what's "inside" the braces are references or pointers. We can start to formalize this naively using a simple grammar-nee type formulation. Ordinary sets can be specified like this Set ::= { Set* } for some appropriately infinite version of Kleene-star. (Note, this grammar is really sugar for a domain equation.) Now, if we want sets over references, we could modify the grammar, like this RSet ::= { Ref* } Ref ::= `Set*' R-sets only contain references and references point to (collections of) sets. Then, you can add a dereference operation to you theory to get back the sets being referenced. But, while under the quotes, the internal structure is not observable by the element-of and brace operators. Thus, from the point of view of these operators, they look like atoms. Note that as written, the quotes are serving a role isomorphic to the role of the braces. They are essentially two different collection operators that have been intertwined in an alternating manner. This alternation is in perfect correspondence with games semantics. We interpret { as opponent question, } as opponent answer, ` as player question, ' as player answer. This means that winning strategies for opponent yield sets while winning strategies for player yield references. The observation leads to a further generalization. Nothing restricts us to two kinds of collection operators. We could posit n different "colored" braces and element-of operators, written {i - i}, \in_i, for color i. Then we have the following specification for these sets Set(i) ::= {i Set(0 <= j < n : j <> i)* i} i have coded up (in my pidgin Haskell) a version for 3 colors and then shown how to do the von Neumann encoding of the naturals in this setting. The code can be found here: http://svn.biosimilarity.com/src/open/mirrororrim/rsets/trunk/MPSet.hs Best wishes, --greg -- L.G. Meredith Managing Partner Biosimilarity LLC 505 N 72nd St Seattle, WA 98103 +1 206.650.3740 http://biosimilarity.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/1a3a4b7f/attachment.htm From andrewcoppin at btinternet.com Fri Aug 10 16:00:05 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 10 15:51:22 2007 Subject: [Haskell-cafe] where to put handy functions? In-Reply-To: References: <22fcbd520708100428r50d71947jdf6b4703ec3377eb@mail.gmail.com> Message-ID: <46BCC3C5.4050207@btinternet.com> Chad Scherrer wrote: > I wonder, is listify a contravariant functor? I wonder - will I ever reach the stage where I too make off-hand remarks like this? :-} Now I know how all the "normal" people feel when I tell them that a relation is simply a subset of the extended Cartesian product of the respective domains of its attributes... From conal at conal.net Fri Aug 10 16:31:28 2007 From: conal at conal.net (Conal Elliott) Date: Fri Aug 10 16:23:23 2007 Subject: [Haskell-cafe] Pure functional GUI (was "a regressive view of support for imperativeprogramming in Haskell") In-Reply-To: <1418427027.20070809093004@gmail.com> References: <1418427027.20070809093004@gmail.com> Message-ID: > On 8/8/07, Bulat Ziganshin wrote: > Hello Peter, > Wednesday, August 8, 2007, 11:14:37 PM, you wrote: > > [...] So could you please tell me more about the problem with pure > > functional GUIs > seems that such program will have no effects :) Not necessarily. Just design the UI & IO aspects orthogonally. For instance, in the applicative functor version of Phooey ( http://haskell.org/haskellwiki/Phooey#Applicative_Functor), you can define a value of type UI (a -> IO ()). Similarly for TV ( http://haskell.org/haskellwiki/TV). - Conal -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/73706ef0/attachment.htm From rodrigo.bonifacio at uol.com.br Fri Aug 10 16:50:43 2007 From: rodrigo.bonifacio at uol.com.br (rodrigo.bonifacio) Date: Fri Aug 10 16:42:35 2007 Subject: [Haskell-cafe] Defining new operators Message-ID: Hi all, Given the follwing function: > owner :: Step -> Scenario > owner (Step id scenario action state response) = scenario Is it possible to define the owner function in such way that I can write x.owner (returning the scenario related with the Step x)? Thanks in advance, Rodrigo. From sjanssen at cse.unl.edu Fri Aug 10 16:51:24 2007 From: sjanssen at cse.unl.edu (Spencer Janssen) Date: Fri Aug 10 16:43:25 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708100151k151ccbf2w9e3670d44f87fa6d@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <837db430708100109h216a957etf119605949ef539c@mail.gmail.com> <837db430708100151k151ccbf2w9e3670d44f87fa6d@mail.gmail.com> Message-ID: <200708101551.24760.sjanssen@cse.unl.edu> On Friday 10 August 2007 03:51:49 Hugh Perkins wrote: > Well, managed to shave 25% of C# execution time by writing my own bit > array. For now, I will concede that, under the conditions of the shoot, > bitarrays in c# are slower than bitarrays in Haskell. I'll let you know if > I get any new ideas on this. > > > Getting back to the original problem, which is: threading. Donald, one of > the things that is very interesting about Haskell is it's potential for > automatic threading, ie you write a trivial algorithm that looks like it > runs in a single thread, and the runtime splits it across multiple cores > automatically. > > It's fairly safe to say that maps, foldrs, foldls, and their derivatives > are safe to parallelize? (For example, hand-waving argument, a foldr of > (/) on [1,5,7,435,46,2] can be split into a foldr on [1,5,7] and a foldr on > [435,46,2], then their results combined). Yes, the semantics of Haskell allow us to run pretty much any operation in parallel. However, the major problem is that lists are a fundamentally sequential data structure. It's quite expensive to chop up parts of a list to eg. send them to a parallel map function. I think the upcoming NDP arrays have a much better chance here. > To what extent is the technology you are using in your algorithm > parallizable? (I actually cant tell, it's a genuine question). In the > case that it is parallelizable, to what extent is it trivial for a runtime > to know this? (Again, I dont have enough information to tell) The program doesn't have much chance for parallelism as written. It uses the imperative ST monad and destructive update extensively. Spencer Janssen From sjanssen at cse.unl.edu Fri Aug 10 16:55:17 2007 From: sjanssen at cse.unl.edu (Spencer Janssen) Date: Fri Aug 10 16:47:23 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, =?iso-8859-1?q?=09threading?=, parallelizeability (is that a word? :-D ) In-Reply-To: <46BCA25B.4030600@btinternet.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810080541.GA6778@localhost.localdomain> <46BCA25B.4030600@btinternet.com> Message-ID: <200708101555.17249.sjanssen@cse.unl.edu> On Friday 10 August 2007 12:37:31 Andrew Coppin wrote: > Stefan O'Rear wrote: > > Bool is 32 bits, but Don is using UArray. UArray is not parametric in > > the element type, which means it's less generally useful (no UArray of > > Complex Double, for instance), but conversely it is able to use more > > efficient representations depending on the type. > > Would be nice if it *could* somehow be parametric... but I have > absolutely no idea how you'd do that. The transformation is self-evident > enough to a human, but how do you explain it to a machine? Check out the various papers, slides, and talks on NDP/parrallel arrays. There's much discussion on schemes to efficiently pack data types into unboxed arrays. Cheers, Spencer Janssen > (I somewhat suspect you'd have to bake this into the compiler itself it > you wanted *arbitrary* types. Otherwise you'd have to write some special > class that knows how to pack and unpack the data from the array, perhaps > as a bundle of Word8s or something? Doesn't sound hugely fast...) From westondan at imageworks.com Fri Aug 10 16:56:17 2007 From: westondan at imageworks.com (Dan Weston) Date: Fri Aug 10 16:48:10 2007 Subject: [Haskell-cafe] Defining new operators In-Reply-To: References: Message-ID: <46BCD0F1.1060503@imageworks.com> Prelude> let (.) = flip ($) in 5 . odd True But please don't, the (.) operator is a sacred artifact in my religion, and I'd hate to see it desecrated... :( Dan rodrigo.bonifacio wrote: > Hi all, > > Given the follwing function: > >> owner :: Step -> Scenario >> owner (Step id scenario action state response) = scenario > > Is it possible to define the owner function in such way that I can write x.owner (returning the scenario related with the Step x)? > > Thanks in advance, > > Rodrigo. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From benjamin.franksen at bessy.de Fri Aug 10 16:59:50 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Fri Aug 10 16:52:05 2007 Subject: [Haskell-cafe] Re: Small question References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <46BC0514.6030806@btinternet.com> <20070810070540.GB6474@localhost.localdomain> <46BC9C63.1030504@btinternet.com> Message-ID: Andrew Coppin wrote: >>> Like that time yesterday, I compiled from program and got a weird message >>> about GHC about "ignored trigraphs" or something... What the heck is a >>> trigraph? >>> ? ? >> >> Everyone's favorite obscure feature of the ANSI C99 preprocessor. >> Probably you had something like "this is odd???" in your source code, >> and were using -cpp. >> >> http://www.vmunix.com/~gabor/c/draft.html#5.2.1.1 >> ? > > Er... wow. OK, well I have no idea what happened there... (I'm not using > -cpp. I don't even know what it is.) I had presumed GHC was upset > because it got killed on the previous run... (I was running something > else and it locked up the PC.) Since you are after increasing your program's performance, maybe you are using -fvia-c or chose an optimization level high enough that GHC decides for itself to go via C. The message is very most probably from the C compiler. You could try passing the C compiler an appropriate flag (see gcc manual) via a ghc command line option (which I am too lazy to look up). Cheers Ben From trebla at vex.net Fri Aug 10 17:02:37 2007 From: trebla at vex.net (Albert Y. C. Lai) Date: Fri Aug 10 16:54:32 2007 Subject: [Haskell-cafe] Defining new operators In-Reply-To: References: Message-ID: <46BCD26D.1090307@vex.net> rodrigo.bonifacio wrote: >> owner :: Step -> Scenario >> owner (Step id scenario action state response) = scenario > > Is it possible to define the owner function in such way that I can write x.owner (returning the scenario related with the Step x)? The . is already taken. Choose some other symbol, say & x & f = f x Now you can use x&owner. P.S. What's wrong with plain and simple "owner x"? From chad.scherrer at gmail.com Fri Aug 10 17:17:01 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Fri Aug 10 17:08:51 2007 Subject: [Haskell-cafe] listify Message-ID: Don't be too impressed, I think I was way off base. Looks like just a homomorphism: http://en.wikipedia.org/wiki/Homomorphism Chad > > I wonder, is listify a contravariant functor? > I wonder - will I ever reach the stage where I too make off-hand remarks > like this? :-} > Now I know how all the "normal" people feel when I tell them that a > relation is simply a subset of the extended Cartesian product of the > respective domains of its attributes... From shachaf at gmail.com Fri Aug 10 17:31:59 2007 From: shachaf at gmail.com (Shachaf Ben-Kiki) Date: Fri Aug 10 17:23:50 2007 Subject: [Haskell-cafe] Defining new operators In-Reply-To: References: Message-ID: <20594c670708101431r1fef26c3k21a02682acc7f0a7@mail.gmail.com> > Hi all, > > Given the follwing function: > > > owner :: Step -> Scenario > > owner (Step id scenario action state response) = scenario > > Is it possible to define the owner function in such way that I can write x.owner (returning the scenario related with the Step x)? Some people use (|>), which looks like an arrow: > (|>) :: a -> (a -> b) -> b > x |> f = f x Then you can use "step |> owner". Also consider using: > data Step = Step { ..., scenario :: Scenario, ... } Shachaf From lgreg.meredith at biosimilarity.com Fri Aug 10 18:54:23 2007 From: lgreg.meredith at biosimilarity.com (Greg Meredith) Date: Fri Aug 10 18:46:16 2007 Subject: [Haskell-cafe] Re: towards a new foundation for set theory with atoms In-Reply-To: <5de3f5ca0708101218j56a7b84fj50acef000dfb8433@mail.gmail.com> References: <5de3f5ca0708101218j56a7b84fj50acef000dfb8433@mail.gmail.com> Message-ID: <5de3f5ca0708101554w471314c4ydd272d71081ca4e8@mail.gmail.com> Haskellians, A quick follow up. If you look at the code that i have written there is a great deal of repeated structure. Each of these different kinds of sets and atoms are isomorphic copies of each other. Because, however, of the alternation discipline, i could see no way to abstract the structure and simplify the code. Perhaps someone better versed in the Haskellian mysteries could enlighten me. Best wishes, --greg On 8/10/07, Greg Meredith wrote: > > Haskellians, > > i have a particular interest in FM-set theory in that it simplifies a host > of otherwise non-trivial aspects of programming language semantics, > especially, fresh names. You can provide semantics without sets with atoms, > but the functor category machinery is more than a little on the heavy side. > The down side of FM-set theory is that it posits an infinite collection of > atomic entities -- atomic in the sense that they have no observable internal > structure. This poses a real problem for computational accounts. No where do > we have an infinite supply of atomic entities. All our infinite collections > need some finite presentation -- some basic starting structure and then a > finite set of rules that say how to generate the rest. This is particularly > important since the atoms have to come with a equality predicate. If the > predicate cannot inspect internal structure, then the equality predicate is > too big to hold in any finitely presentable computation. Thus, there's a > little conundrum: how do you get all the conveniences of a set theory with > atoms and still have a finite presentation? > > Here's one approach. The issue is that atoms cannot have internal > structure observable by the set-theoretic operators, \in : Set -> Atom + > Set -> Bool, and { - } : [Atom + Set] -> Set. That doesn't mean they can't > have structure. Where would this structure come from? Well, it's related to > another observation about sets: they're really collections of pointers. More > specifically, the axiom of extensionality says that two sets are equal iff > they have exactly the same members. Thus, wherever we see the set { } it's > the same. Therefore, in { { }, { { } } } we see the very same set occurring > in two locations. This is not very physical. These notions of location or > identity must be more logical notions. And, one obvious way to resolve this > is that what's "inside" the braces are references or pointers. We can start > to formalize this naively using a simple grammar-nee type formulation. > Ordinary sets can be specified like this > > Set ::= { Set* } > > for some appropriately infinite version of Kleene-star. (Note, this > grammar is really sugar for a domain equation.) Now, if we want sets over > references, we could modify the grammar, like this > > RSet ::= { Ref* } > Ref ::= `Set*' > > R-sets only contain references and references point to (collections of) > sets. Then, you can add a dereference operation to you theory to get back > the sets being referenced. But, while under the quotes, the internal > structure is not observable by the element-of and brace operators. Thus, > from the point of view of these operators, they look like atoms. > > Note that as written, the quotes are serving a role isomorphic to the role > of the braces. They are essentially two different collection operators that > have been intertwined in an alternating manner. This alternation is in > perfect correspondence with games semantics. We interpret { as opponent > question, } as opponent answer, ` as player question, ' as player answer. > This means that winning strategies for opponent yield sets while winning > strategies for player yield references. The observation leads to a further > generalization. Nothing restricts us to two kinds of collection operators. > We could posit n different "colored" braces and element-of operators, > written {i - i}, \in_i, for color i. Then we have the following > specification for these sets > > Set(i) ::= {i Set(0 <= j < n : j <> i)* i} > > i have coded up (in my pidgin Haskell) a version for 3 colors and then > shown how to do the von Neumann encoding of the naturals in this setting. > The code can be found here: > http://svn.biosimilarity.com/src/open/mirrororrim/rsets/trunk/MPSet.hs > > Best wishes, > > --greg > > -- > L.G. Meredith > Managing Partner > Biosimilarity LLC > 505 N 72nd St > Seattle, WA 98103 > > +1 206.650.3740 > > http://biosimilarity.blogspot.com -- L.G. Meredith Managing Partner Biosimilarity LLC 505 N 72nd St Seattle, WA 98103 +1 206.650.3740 http://biosimilarity.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/8e42d658/attachment-0001.htm From benjamin.franksen at bessy.de Fri Aug 10 19:14:57 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Fri Aug 10 19:07:03 2007 Subject: [Haskell-cafe] Re: Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <46BC26E3.1030902@cs.caltech.edu> <837db430708100158m3f2f42e3k91712350933e7e5c@mail.gmail.com> Message-ID: Hugh Perkins wrote: > Now, arguably the fact that we are pattern matching on the receiver at least > means we dont do anything with the invalid data sent, but this is not rocket > science: the standard technique to ensure decent compile time validation in > rpc-type things is to use an interface. > > The interface defines the method names and parameters that you can send > across. Both the receiver and the sender have access to the interface > definition, and it is trivial to check it at compile time. > > (Caveat: havent looked enough into Erlang to know if there is a good reason > for not using an interface?) Remember that Erlang is an untyped language and that you are allowed to send any kind of data. However, there is more to consider here: A certain amount of dynamism wrt the message content (high level protocol) is necessary for systems for which Erlang was designed, namely large distributed control systems with minimum down-times. For large distributed installations it is a matter of practicality to be able to upgrade one component w/o needing to recompile (and then re-start) all the other components that it communicates with -- for systems with expected down-times of 3 Minutes per year it is a matter of being able to meet the specifications. You'll have a hard time finding high-availability or large control systems which use an IDL approach for communication. Cheers Ben From dpiponi at gmail.com Fri Aug 10 20:26:29 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Fri Aug 10 20:18:20 2007 Subject: [Haskell-cafe] Problem with question 3 about knights and knaves on wikipedia In-Reply-To: <004701c7dab0$165f92d0$431eb870$@be> References: <004701c7dab0$165f92d0$431eb870$@be> Message-ID: <625b74080708101726q3fde4ae9lfc5550a95dd7d1d2@mail.gmail.com> On 8/9/07, Peter Verswyvelen wrote: > I was writing some haskell code for fun to solve some "knights and knaves" > . . . > John: answers either Yes or No, and you can now solve the problem. We can write a Haskell *program* to solve this problem. But is there a nice way to make the Haskell *compiler* itself solve this problem? In particular, can we write equations for the values of john and bill and somehow have the type inferencer figure out whether the Haskell types of john and bill are Knight or Knave? -- Dan From drtomc at gmail.com Fri Aug 10 22:14:32 2007 From: drtomc at gmail.com (Thomas Conway) Date: Fri Aug 10 22:06:21 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> Message-ID: <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> On 8/11/07, Hugh Perkins wrote: > > - parallelism must be quite coarse to offset overheads > > (which I think is the problem with expecting things like map and fold > > to parallelised automagically; they're just too small grained for it to > > be worthwhile) > > Someone else said that. I dont understand what you mean. There are many papers about this in the Parallel Logic Programming area. It is commonly called "Embarrassing Parallelism". Creating a thread, or even just scheduling a chunk of work for evaluation has packaging-up costs, synchronization costs, and so on. It is all too easy for these costs to outweigh the work to be done, so by parallelizing your code, you make it run slower. So, if you want to parallelize "map f xs", unless f is *really* expensive, you'll only get a benefit if you can break xs into chunks of e.g. 10^3 elements or more, and more like 10^5 or more for more usual 'f's. Some tasks, like Monte Carlo integration are very amenable to such, but most tasks are not. cheers, T. -- Dr Thomas Conway drtomc@gmail.com Silence is the perfectest herald of joy: I were but little happy, if I could say how much. From drtomc at gmail.com Fri Aug 10 22:21:20 2007 From: drtomc at gmail.com (Thomas Conway) Date: Fri Aug 10 22:13:10 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <200708101551.24760.sjanssen@cse.unl.edu> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <837db430708100109h216a957etf119605949ef539c@mail.gmail.com> <837db430708100151k151ccbf2w9e3670d44f87fa6d@mail.gmail.com> <200708101551.24760.sjanssen@cse.unl.edu> Message-ID: <784a62100708101921g400360cfsf482cf40c93a7281@mail.gmail.com> On Friday 10 August 2007 03:51:49 Hugh Perkins wrote: > Getting back to the original problem, which is: threading. Donald, one of > the things that is very interesting about Haskell is it's potential for > automatic threading, ie you write a trivial algorithm that looks like it > runs in a single thread, and the runtime splits it across multiple cores > automatically. In the interests of clarity, it is useful and important to distinguish between threading (i.e. concurrency) and parallelism. The former relates to the programmer's view of the world, and the latter relates to the computer's model of execution. As nomenclature, it is not universal, but is very common, and helps avoid conflating two quite different things. cheers, Tom -- Dr Thomas Conway drtomc@gmail.com Silence is the perfectest herald of joy: I were but little happy, if I could say how much. From hughperkins at gmail.com Fri Aug 10 23:32:30 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Fri Aug 10 23:24:20 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> Message-ID: <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> On 8/11/07, Thomas Conway wrote: > There are many papers about this in the Parallel Logic Programming > area. It is commonly called "Embarrassing Parallelism". Ah, I wasnt very precise ;-) I didnt mean I dont understand the problem; I meant I dont understand why people think it is difficult to solve ;-) (And then I tried to explain by examples why it is easy, but it is true that my communication sucks ;-) ) > you'll only get a benefit if you can break xs into chunks of e.g. 10^3 elements or more, and more like 10^5 or more for more usual 'f's. Actually, the number of elements is irrelevant. The only measure that is important is how long the function is taking to execute, and whether it is parellizable. Example, the following only has 3 elements but will take a while to run: strPrtLn $ sum $ map getNumberPrimes [10240000, 20480000, 40960000 ] The following has 10 million elements but runs quickly: strPrtLn $ sum $ map (+1) [1..10000000 ] In the second, we start the function running, in a single thread, and after a second, the function has already finished, so great! Were done! In the first, we start the function running, in a single thread. After a second the function is still running, so we look at what is taking the time and whether it is parallelizable. Turns out the vm has been chugging away on the map for the last second, and that that maps are parallelizeable, so we split the map into Math.Min( , ) pieces, which on a 1024-core machine, given we have 3 elements, is Math.Min( 1024, 3 ), which is 3. So, we assign each of the 3 elements of the map to a thread. So, now we're using 3 of our 64 cores. A second later, each thread is still chugging away at its element, so we think, ok, maybe we can parallelize more, because we still have 61 threads/cores available, so now we look at the getNumberOfPrimes function itself, and continue the above type of analysis. This continues until all 64 cores have been assigned some work to do. Whenever a thread finishes, we look around for some work for it to do. If there is some, we assign it. If there isnt, we look around for an existing thread that is doing something parallelizeable, and split it into two pieces, giving one to the old thread, and one to the available thread. Not sure why this is perceived as difficult (added the word "perceived" this time ;-) ). I think the main barrier to understanding why it is easy is understanding that this needs to be done from a VM, at runtime. It is not possible to do it statically at compilation, but I really need to finish watching SPJ's video before declaring that SPJ's proposal is doomed to fail ;-) Not least, probably not good to make an enemy of SPJ ;-) From ronguida at mindspring.com Fri Aug 10 23:34:35 2007 From: ronguida at mindspring.com (Ronald Guida) Date: Fri Aug 10 23:25:31 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <12087081.post@talk.nabble.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> Message-ID: <46BD2E4B.3010202@mindspring.com> Brian Brunswick wrote: > g f ??? g ??? f > > application a a->b flip ($) b > monad bind m a a->m b >>= m b > comonad cobind w a w a->b =>> w b > arrow arr a b arr b c >>> arr a c Kim-Ee Yeoh wrote: > Fmap's missing: m a, a->b, flip fmap, m b. You might want to throw in > Applicative there too: m a, m (a->b), flip (<*>), m b. Here's my interpretation of the table: ---------------------------------------------------------------------- Structure | Subject | Action | Verb | Result ------------+----------+------------+------------+---------- function | a | a->b | flip ($) | b Functor | f a | a->b | <$> | f b Applicative | f a | f (a->b) | flip <*> | f b Monad | m a | a->m b | >>= | m b Comonad | w a | w a->b | =>> | w b Arrow | a b c | a c d | >>> | a b d ---------------------------------------------------------------------- Kim-Ee Yeoh wrote: > ... I think you'll find that each of those structures have their > privileged place in your code. Agreed. I'm still a beginner; I'm not sure how to choose one structure over another, at least not yet. But that's because ... > Monads are undoubtedly more pervasive, and that could be because there > aren't as many arrow and comonad tutorials, atomic ones or otherwise. Moreover, Comonad isn't even in the standard libraries (Hoogle returns no results for it). When I searched for tutorials on monads, I found lots of them. In fact, I have heard that writing (yet another) monad tutorial is part of standard Haskell initiation. In my case, I have started to formulate my own idea for what a monad tutorial should be; I might attempt to write one, too. I read several monad tutorials, but I could not understand them at first. Monad transformers are even worse. I had to sit, *think*, draw diagrams, *think* some more, review several advanced tutorials, and *think* even more. I also looked up comonads, arrows, and category theory. Finally, monads (and monad transformers) started to make sense for me. I still don't understand monads just yet; but that's because my self-test for understanding something is whether I feel I could explain it to someone else and have it make sense. I suppose that in order to understand monads, I need to actually *use* some monads, and see them in action on something real (like an actual algorithm) that I can relate to. Learning feels like climbing a mountain; much time and hard work is spent on the ascent, but new understanding is achieved in the process. Once I reach the top of the mountain, the question is how to make the mountain easier to climb for the next person. My thinking is that the ultimate goal is to /invert/ the mountain, such that the people can /ride/ the mountain (which still requires some work) and gain new understanding in the process. What I obtain on the way up the mountain, future people would obtain, far more efficiently, on the way /down/ the (inverted) mountain. What I would like to see in a monad tutorial are some good real-use examples that demonstrate /just/ monads. I found it extremely helpful to see an example of monads being used to compute probabilities and drug test false-alarm rates. This application seemed to used /just/ monads, without a lot of extra programming complexity on top, and it provided a "real" example. This is the sort of thing, combined with the background of "what is a monad", that I think would make a really good tutorial. The "monadic lovers" story, in my opinion, provides an example that's too contrived and simplistic. On the other extreme, I found an example of arrows being used in a digital circuit simulator. As a tutorial on arrows, I would find this too complex because there is too much "stuff" built up on top of the arrows. The concept of an arrow is lost in the complexity of "special" classes like the ArrowCircuit class that was actually used to simulate a circuit. (Note: The circuit used in the example was trivial, moreover my background is electrical engineering with a focus on digital circuits.) I found an example of a comonad being used to simulate a cellular automaton; I found this example helpful, although it might be a little too complex. I think that what would make a truly great tutorial would be a tutorial (or a series of tutorials) that starts with a "real" area of exploration and proceeds to incrementally develop programs. Each increment would incorporate a new "bite" from the area of exploration, which would cause an increase in complexity. As the programs get complicated, the monad (or comonad, or arrow) is introduced by factoring the appropriate pattern out the code and then simplifying. The tutorial might (1) state the monad laws and say "this is what defines a monad", (2) say something like "let's look for this pattern in the code" and find the pattern very easily because the example would be designed to make the pattern fairly obvious, and (3) define a special monad and use it to simplify the code. If I think of something, I'll attempt to write it up and see what happens. Brian Brunswick wrote: > The full title of this is really 'Explaining monads by comparison > with comonads and arrows' ... Also, arrows are supposed to be more general than both monads and comonads. If I could just figure out what each structure (functor, monad, comonad, arrow) is doing, and compare and contrast them, then I probably will have made leaps of understanding. I have a sense that tells me that the table above and the data structures below probably start to scratch the surface of understanding. ---------------------------------------------------------------------- Foo a = Foo { runFoo :: a } -- Functor State s a = State { runState :: s -> (a, s) } -- Monad Context c a = Context { runContext :: (a, c) -> a } -- Comonad Thing s a b = Thing { runThing :: (a, s) -> (b, s) } -- Arrow??? ---------------------------------------------------------------------- An exceptional tutorial (it would probably have to be a series) would use a "real" area of exploration and introduce all four structures by incrementally developing programs (in the area of exploration) at just the right level of program complexity for each structure to make sense and fit into its surroundings without being either too simple or too complicated. If (or when) I ever make that leap of understanding, I might make an attempt to write that tutorial. Until then, I guess I'm still climbing the mountain now, hoping I'll get to ride the mountain later. -- Ron From zednenem at psualum.com Sat Aug 11 00:06:23 2007 From: zednenem at psualum.com (David Menendez) Date: Fri Aug 10 23:58:12 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <46BC0514.6030806@btinternet.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <46BC0514.6030806@btinternet.com> Message-ID: <49a77b7a0708102106o4789c40cj66426e3cc95dfb82@mail.gmail.com> On 8/10/07, Andrew Coppin wrote: > > My program needs to make decisions based on a pair of boolean values. > Encoding both values as a single algebraic data type means I have to > keep "taking it apart" so I can work with it. I'm not sure how much time > this wastes... Incidentally, there is an argument that many (perhaps most) use of Bool should instead be custom datatypes. That is, instead of: type FooBar = (Bool, Bool) one should instead do something like data Foo = Foo | AntiFoo data Bar = Baz | Bo type FooBar = (Foo, Bar) which makes it clearer what's going on and harder to confuse the two booleans. Of course, now you have to replace \(foo, bar) -> if foo then ... else ... with \(foo, bar) -> if foo == Foo then ... else ... or \(foo, bar) -> case foo of { Foo -> ...; Bar -> ... } ---- Actually, that raises an interesting question. Is there a performance difference between "if foo == Foo ..." and "case Foo of ..."? I think JHC's case-hoisting should be able to transform the former into the latter, but does it? From bulat.ziganshin at gmail.com Sat Aug 11 01:26:17 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 11 01:20:16 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <46BCA25B.4030600@btinternet.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810073813.GD5596@cse.unsw.EDU.AU> <837db430708100057m6c43aff0x351205d3da72a496@mail.gmail.com> <20070810075802.GE5596@cse.unsw.EDU.AU> <837db430708100100g2f54ba81l8c1272d6e9f4aeef@mail.gmail.com> <20070810080541.GA6778@localhost.localdomain> <46BCA25B.4030600@btinternet.com> Message-ID: <1847543400.20070811092617@gmail.com> Hello Andrew, Friday, August 10, 2007, 9:37:31 PM, you wrote: > Would be nice if it *could* somehow be parametric... ForeignArray may hold any Storable values. look at http://haskell.org/haskellwiki/Modern_array_libraries - we have no less than 10 array constructors :)) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From stefanor at cox.net Sat Aug 11 02:12:10 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sat Aug 11 02:04:02 2007 Subject: [Haskell-cafe] Small question In-Reply-To: <49a77b7a0708102106o4789c40cj66426e3cc95dfb82@mail.gmail.com> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <46BC0514.6030806@btinternet.com> <49a77b7a0708102106o4789c40cj66426e3cc95dfb82@mail.gmail.com> Message-ID: <20070811061210.GA6412@localhost.localdomain> On Sat, Aug 11, 2007 at 12:06:23AM -0400, David Menendez wrote: > On 8/10/07, Andrew Coppin wrote: > > > > My program needs to make decisions based on a pair of boolean values. > > Encoding both values as a single algebraic data type means I have to > > keep "taking it apart" so I can work with it. I'm not sure how much time > > this wastes... > > Incidentally, there is an argument that many (perhaps most) use of > Bool should instead be custom datatypes. That is, instead of: > > type FooBar = (Bool, Bool) > > one should instead do something like > > data Foo = Foo | AntiFoo > data Bar = Baz | Bo > type FooBar = (Foo, Bar) > > which makes it clearer what's going on and harder to confuse the two booleans. > > Of course, now you have to replace > > \(foo, bar) -> if foo then ... else ... > with > \(foo, bar) -> if foo == Foo then ... else ... > or > \(foo, bar) -> case foo of { Foo -> ...; Bar -> ... } > > Actually, that raises an interesting question. Is there a performance > difference between "if foo == Foo ..." and "case Foo of ..."? I think > JHC's case-hoisting should be able to transform the former into the > latter, but does it? You don't need to go all the way to JHC[1] for this; GHC's case-of-case transformation is perfectly adequate, as GHC itself will tell you: stefan@stefans:/tmp$ ghc -c -ddump-simpl -O2 X.hs ... X.moo :: X.Ay -> GHC.Base.Int ... X.moo = \ (x_a6D :: X.Ay) -> case x_a6D of wild_Xq { X.Be -> X.lit; X.Ce -> X.lvl } stefan@stefans:/tmp$ cat X.hs module X where data Ay = Be | Ce deriving(Eq) moo x = if x == Be then 2 else (3::Int) stefan@stefans:/tmp$ ghc -c -ddump-simpl-stats -O2 X.hs ==================== FloatOut stats: ==================== 1 Lets floated to top level; 0 Lets floated elsewhere; from 4 Lambda groups ==================== FloatOut stats: ==================== 0 Lets floated to top level; 0 Lets floated elsewhere; from 3 Lambda groups ==================== Grand total simplifier statistics ==================== Total ticks: 46 9 PreInlineUnconditionally 11 PostInlineUnconditionally 6 UnfoldingDone 1 RuleFired 1 ==#->case 9 BetaReduction 2 CaseOfCase <------- 7 KnownBranch 1 CaseMerge 11 SimplifierDone stefan@stefans:/tmp$ Stefan [1] GHC takes 2 hours to run a full two-stage bootstrap complete with the entire standard library. Jhc takes[2] at least 4 hours (I didn't let it finish) to compile just the Prelude. [2] 700MB working set, 384MiB primary store. This makes a difference. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070810/9a7853f6/attachment.bin From zednenem at psualum.com Sat Aug 11 03:32:30 2007 From: zednenem at psualum.com (David Menendez) Date: Sat Aug 11 03:24:20 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46BD2E4B.3010202@mindspring.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> Message-ID: <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> On 8/10/07, Ronald Guida wrote: > > Kim-Ee Yeoh wrote: > > Monads are undoubtedly more pervasive, and that could be because there > > aren't as many arrow and comonad tutorials, atomic ones or otherwise. > > Moreover, Comonad isn't even in the standard libraries (Hoogle returns > no results for it). This is probably because no one has found a compelling use case for comonadic-style programming in Haskell. There have been some interesting papers, such as "Comonadic functional attribute evaluation" by Uustalu and Vene, but nothing as compelling as Wadler's "Monads for functional programming". > In my case, I have started to formulate my own idea for what a monad > tutorial should be; I might attempt to write one, too. Be sure to read sigpfe's "You could have invented monads!" and the Wadler paper. Most tutorials try to explain what a monad *is*, but these focus more on why they're a useful way to organize code. In my experience, being able to use a monad is more important than understanding the theory. > Also, arrows are supposed to be more general than both monads and > comonads. If I could just figure out what each structure (functor, > monad, comonad, arrow) is doing, and compare and contrast them, then I > probably will have made leaps of understanding. Arrows are more general than monads and comonads in the sense that you can create an arrow corresponding to any particular monad and comonad, but there are also arrows which correspond to neither. Functors are more general than monads and comonads simply because every monad and comonad is a functor with additional operations. (This can be obscured by the fact that the Haskell Prelude doesn't define Monad as a subclass of Functor.) From dons at cse.unsw.edu.au Sat Aug 11 03:51:44 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Sat Aug 11 03:43:39 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46BD2E4B.3010202@mindspring.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> Message-ID: <20070811075144.GA3389@cse.unsw.EDU.AU> ronguida: > > > Monads are undoubtedly more pervasive, and that could be because there > > aren't as many arrow and comonad tutorials, atomic ones or otherwise. > > Moreover, Comonad isn't even in the standard libraries (Hoogle returns > no results for it). > > When I searched for tutorials on monads, I found lots of them. In > fact, I have heard that writing (yet another) monad tutorial is part > of standard Haskell initiation. > Regarding the available tutorials, I've collected them under each flavour here: haskell.org/haskellwiki/Blog_articles/Monads Including 42 monad tutorials, 6 arrow tutorials, and 3 comonad tutorials, and 0 on applicative functors. The source for the `standard' (only) comonad library is available from one of the sigfpe tutorials, but really should be on hackage. -- Don From fb at frank-buss.de Sat Aug 11 03:58:05 2007 From: fb at frank-buss.de (Frank Buss) Date: Sat Aug 11 03:49:59 2007 Subject: [Haskell-cafe] zip3, zip4 ... -> zipn? Message-ID: <0e3d01c7dbed$59676970$64c5a8c0@galilei> Is it possible to write a function like this: zipn n list_1 list_2 list_3 ... list_n which implements zip3 for n=3, zip4 for n=4 etc.? Looks like variable number of arguments are possible, like printf shows, so a general zipn should be possible, too. If it is possible, why there are functions like zip5 and not just zipn? -- Frank Buss, fb@frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From a.biurvOir4 at asuhan.com Sat Aug 11 04:19:39 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Sat Aug 11 04:11:28 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46BD2E4B.3010202@mindspring.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> Message-ID: <12103564.post@talk.nabble.com> Ronald Guida wrote: > > Here's my interpretation of the table: > > ---------------------------------------------------------------------- > Structure | Subject | Action | Verb | Result > ------------+----------+------------+------------+---------- > function | a | a->b | flip ($) | b > Functor | f a | a->b | <$> | f b > Applicative | f a | f (a->b) | flip <*> | f b > Monad | m a | a->m b | >>= | m b > Comonad | w a | w a->b | =>> | w b > Arrow | a b c | a c d | >>> | a b d > ---------------------------------------------------------------------- > This is the first time I've seen <$>. What a pleasing synonym for fmap. To maintain a similar order of parameters, I think you'd want "flip <$>" up there. Ronald Guida wrote: > > ---------------------------------------------------------------------- > Foo a = Foo { runFoo :: a } -- Functor > State s a = State { runState :: s -> (a, s) } -- Monad > Context c a = Context { runContext :: (a, c) -> a } -- Comonad > Thing s a b = Thing { runThing :: (a, s) -> (b, s) } -- Arrow??? > ---------------------------------------------------------------------- > I believe there is a way to see all of the above as forms of "generalized application" although not in the way presented here. (I thank Brian for pointing to the possibility of a unified treatment in the first place.) A point in common among your run* functions is that you can always observe the instance of type (a) in (m a :: Monad a). But monads are equipped with (return :: a -> m a), not (coreturn :: m a -> a). Your 2nd table is more about comonads, at least the coreturn aspect, than about whatever unity you're hoping to achieve. There's more about coreturn here: http://www.haskell.org/pipermail/haskell-cafe/2007-August/030153.html So we need to explore "generalized application" without being too explicit about "unwrapping" monads nor "wrapping" comonads. Why? Because being too explicit invariably locks us into one particular instantiation and the generalization goes poof! Think of all the otherwise rich and creative papers written on the IO monad and its innards. The instances of monads I've seen are in themselves too sexy (probabilistic modelling! digital circuit simulation! IO! concurrency!) that they end up overwhelming the essence of monadism pregnant within. Better to start with something boring. Like the Maybe monad. Feck heh, "The essence of monadism pregnant within." Another fine title for another monad tutorial. -- View this message in context: http://www.nabble.com/Explaining-monads-tf4244948.html#a12103564 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From andrewcoppin at btinternet.com Sat Aug 11 04:23:32 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 11 04:14:46 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <200708101555.17249.sjanssen@cse.unl.edu> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <20070810080541.GA6778@localhost.localdomain> <46BCA25B.4030600@btinternet.com> <200708101555.17249.sjanssen@cse.unl.edu> Message-ID: <46BD7204.50808@btinternet.com> Spencer Janssen wrote: > On Friday 10 August 2007 12:37:31 Andrew Coppin wrote: > >> Stefan O'Rear wrote: >> >>> Bool is 32 bits, but Don is using UArray. UArray is not parametric in >>> the element type. >>> >> Would be nice if it *could* somehow be parametric... but I have >> absolutely no idea how you'd do that. The transformation is self-evident >> enough to a human, but how do you explain it to a machine? >> > > > Check out the various papers, slides, and talks on NDP/parrallel arrays. > There's much discussion on schemes to efficiently pack data types into > unboxed arrays. > NDP is like Christmas! So many boxes of goodies to open... but it takes so long to come around... :-( From joelkoerwer at gmail.com Sat Aug 11 04:52:37 2007 From: joelkoerwer at gmail.com (Joel Koerwer) Date: Sat Aug 11 04:44:26 2007 Subject: [Haskell-cafe] zip3, zip4 ... -> zipn? In-Reply-To: <0e3d01c7dbed$59676970$64c5a8c0@galilei> References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> Message-ID: <34e5cfb80708110152k18d789b4jdbba48d2e6aabbc2@mail.gmail.com> Frank, The return type of zipn would have to depend on the number of arguments. If you are satisfied with all arguments having the same type, then you can use transpose: zipn list1 list2 .. listn => transpose [list1, list2, .. listn] Can we make a polyvariadic zipn that returns a [HList]? Seems like a neat challenge, but I'm a bit pressed for time right now. I'm afraid it would be pretty unwieldy. I'm looking forward to seeing solutions though. :-) -- Joel From hughperkins at gmail.com Sat Aug 11 05:27:19 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Sat Aug 11 05:19:08 2007 Subject: [Haskell-cafe] zip3, zip4 ... -> zipn? In-Reply-To: <34e5cfb80708110152k18d789b4jdbba48d2e6aabbc2@mail.gmail.com> References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> <34e5cfb80708110152k18d789b4jdbba48d2e6aabbc2@mail.gmail.com> Message-ID: <837db430708110227j6e401e78n783f228388e7e05a@mail.gmail.com> I was looking for something like this too. Note that Erlang can do this ;-) but Erlang is probably not so strongly typed, so it's easier to do? From coeus at gmx.de Sat Aug 11 05:44:17 2007 From: coeus at gmx.de (Marc A. Ziegert) Date: Sat Aug 11 05:36:40 2007 Subject: [Haskell-cafe] howto install ghc-6.7.* ? Message-ID: <200708111144.23249.coeus@gmx.de> i just don't get it. please, can anybody explaim me how to do that? i tried it the last few days with ghc-6.7.20070807, ghc-6.7.20070809, and ghc-6.7.20070810. it always results in a broken library (without Prelude): # ghc-pkg list /usr/local/lib/ghc-6.7.20070810/package.conf: {ghc-6.7.20070810}, rts-1.0 i did this on my gentoo-i386-box (pretty old, takes 1h for quick build, 3.5h without mk/build.mk): T=20070810 tar xjf ghc-6.7.$T-src.tar.bz2 tar xjf ghc-6.7.$T-src-extralibs.tar.bz2 cd ghc-6.7.$T ( #echo BuildFlavour = quick #cat mk/build.mk.sample echo HADDOCK_DOCS = YES ) > mk/build.mk ./configure && ( time nice -n 19 make all install ) those extralibs seem to be installed in /usr/local/lib/ghc-6.7.20070810/lib/ but registered in ghc-6.7.20070810/driver/package.conf.inplace instead of /usr/local/lib/ghc-6.7.20070810/package.conf . - marc -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/e3412e13/attachment.bin From mailing_list at istitutocolli.org Sat Aug 11 05:50:19 2007 From: mailing_list at istitutocolli.org (Andrea Rossato) Date: Sat Aug 11 05:43:39 2007 Subject: [Haskell-cafe] arrow question HXT related Message-ID: <20070811095018.GR17103@laptop.nowhere.net> Hi, I think this is just a stupid arrow question. Still I cannot find where my mistake is located. Suppose I have a simple xml document I want to process with HXT: text After extracting I want to duplicate the children trees with the arrow operator (&&&) and process them to get each sub element, like I try in treMe2. Below the example code. While I can get each sub element with tryMe and tryMe1, tryMe2 will produce a []. Instead I want something like tryMe3. I think I'm missing something stupid but right now I just feel stupidly blind. Thanks for your help, Andrea import Text.XML.HXT.Arrow xml = "text" tryMe = runLA arrow [] where arrow = constA xml >>> xread >>> deep (hasName "elem") >>> getChildren >>> (hasName "risub" >>> getChildren >>> getText) tryMe1 = runLA arrow [] where arrow = constA xml >>> xread >>> deep (hasName "elem") >>> getChildren >>> (hasName "sub" >>> withDefault (getChildren >>> getText) "ciao") tryMe2 = runLA arrow [] where arrow = constA xml >>> xread >>> deep (hasName "elem") >>> getChildren >>> (hasName "sub" >>> withDefault (getChildren >>> getText) "ciao") &&& (hasName "risub" >>> getChildren >>> getText) tryMe3 = runLA arrow [] where arrow = constA xml >>> xread >>> constA "first" &&& constA "second" The output: *test> tryMe ["text"] *test> tryMe1 ["ciao"] *test> tryMe2 [] *test> tryMe3 [("first","second")] *test> From andrewcoppin at btinternet.com Sat Aug 11 07:24:28 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 11 07:15:41 2007 Subject: [Haskell-cafe] Re: Small question [new Wiki page up] In-Reply-To: <20070810070540.GB6474@localhost.localdomain> References: <46BB50DC.8020404@btinternet.com> <3d96ac180708091112s228c0c45g8cbcbe188deb3563@mail.gmail.com> <20070809181637.GA3716@localhost.localdomain> <46BB78AB.3050802@btinternet.com> <20070809205445.GA4357@localhost.localdomain> <46BB84FF.9020800@btinternet.com> <20070809220938.GB4665@localhost.localdomain> <46BC0514.6030806@btinternet.com> <20070810070540.GB6474@localhost.localdomain> Message-ID: <46BD9C6C.7040709@btinternet.com> Stefan O'Rear wrote: > >>> Good idea! Maybe it could be fit into the GHC Performance Resource >>> somehow? (http://www.haskell.org/haskellwiki/Performance/GHC) >>> >> OK. But it'll probably contain a lot of guessing to start with... ;-) >> > > Wiki pages can be fixed. Private misunderstandings can't, at least not > anywhere near as easily. > A page now exists: http://www.haskell.org/haskellwiki/GHC_optimisations Everybody feel free to point and laugh. (Or, more helpfully, expand and correct!) From mailing_list at istitutocolli.org Sat Aug 11 07:30:56 2007 From: mailing_list at istitutocolli.org (Andrea Rossato) Date: Sat Aug 11 07:41:05 2007 Subject: [Haskell-cafe] arrow question HXT related In-Reply-To: <20070811095018.GR17103@laptop.nowhere.net> References: <20070811095018.GR17103@laptop.nowhere.net> Message-ID: <20070811113056.GA11356@laptop.nowhere.net> On Sat, Aug 11, 2007 at 11:50:19AM +0200, Andrea Rossato wrote: > Hi, > > I think this is just a stupid arrow question. Still I cannot find > where my mistake is located. > well, it was not an arrow problem but a HXT problem. This new version of tryMe2 does work as expected: tryMe2 = runLA arrow [] where arrow = constA xml >>> xread >>> listA ( deep (hasName "elem") >>> (deep (hasName "sub") >>> withDefault (getChildren >>> getText) "ciao") &&& (deep (hasName "risub") >>> getChildren >>> getText) ) Sorry for the noise. Andrea From apfelmus at quantentunnel.de Sat Aug 11 10:22:00 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Sat Aug 11 10:14:01 2007 Subject: [Haskell-cafe] Re: Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46B9DAA7.4070006@metamilk.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> Message-ID: Brian Hulley schrieb: > apfelmus wrote: >> However, most "genuinely imperative" things are often just a building >> block for a higher level functional model. The ByteString library is a >> good example: the interface is purely functional, the internals are >> explicit memory control. It's a bad idea to let the internal memory >> control leak out and pollute an otherwise purely functional program with >> IO-types. > > Regarding the quote above, if the API must hide explicit memory control > from the user the only way I can see of doing this would be to use > (unsafePerformIO), which really is unsafe since Haskell relies on the > fact that mutable operations can't escape from the IO monad in order to > get away with not having to impose a value restriction as in ML. Indeed, Data.ByteString makes heavy use of unsafePerformIO and inlinePerformIO. This is safe since it's just used for efficient memory access and (de-)allocation, the ByteStrings themselves are immutable. > If you don't use (unsafePerformIO), then the slightest need for mutable > data structures pollutes the entire interface. Well, any code that wants to mutate or read this data structure has to announce so in the type signature. However, it's debatable whether certain forms of "mutation" count as pollution. In fact, the simplest "mutation" is just a function s -> s . Haskell is throughly "polluted" by such "mutations": (3+) :: Int -> Int ([1,2]++) :: [Int] -> [Int] insert "x" 3 :: Map String Int -> Map String Int Of course, from the purely functional point of view, this is hardly perceived as mutation since the original value is not changed at all and still available. In other words, the need to "change" a value doesn't imply the need to discard (and thus mutate) the old one. Mutable data structures in the sense of ephemeral (= not persistent = update in-place) data structure indeed do introduce the need to work in ST since the old version is - by definition - not available anymore. This may be the right thing to do when the data structure is inherently used in a single-threaded fashion. However, most used-to-be ephemeral data structures have very good persistent counterparts in Haskell. In the end, the type just reflects the inherent difficulty of reasoning about ephemeral data structures. And that's what the quoted paper illustrates: persistent data structures are much easier to deal with. > For example in the excellent paper you quoted > > N. Ramsey and J. Dias. > An Applicative Control-Flow Graph Based on Huet's Zipper > http://www.eecs.harvard.edu/~nr/pubs/zipcfg-abstract.html > > > the authors are pleased to have found an "Applicative" solution, and > indeed their solution has many useful and instructive aspects. However > on page 111, hidden away in the definition of their API function to > create a label, is a call to (ref 0) !!!! ;-) The equivalent > implementation in Haskell would completely destroy all hope of using > this in a pure context and force all use of the API into the IO monad. I don't know enough ML or have the background to judge whether this ref is really necessary, but I doubt that it can't be designed away. > Haskell is designed so that any attempt at abstracting mutable > local state will infect the entire program Depends on "local". In general, I think is a good thing. The type reflects how difficult your program really is, nothing more, nothing less. That's how it is: persistent data and prue functions are sooo much easier to reason about. Implicit side effects just sweep the difficulty under the carpet. (I imagine a tool that makes implicit side effects explicitly visible in the types of say C or ML programs. I guess that people would scream whole nights when seeing the output of this tool on their programs and thus discovering how complicated the code really is ... Well, maybe not since they're used to it during debugging anyway.) But if the state is really local, no infection of the entire program takes place! The best example is probably indeed the Haskell Graphics library. The are pure functions for constructing graphics over :: Graphic -> Graphic -> Graphic polygon :: [Point] -> Graphic and some IO-infected functions to draw those onto the screen drawInWindow :: Window -> Graphic -> IO () Now, Graphic may be implemented as an abstract data type and drawInWindow does the workload of interpreting it. Or, and that's how HGL currently implementes it, it can be an IO-action that encodes how to draw it type Graphics = Draw () ~= (Brush,Font,Pen) -> IO () That is, every graphic is "infested" with IO but that doesn't spread to the API. (It does a bit with selectBrush but that can be corrected.) > (modulo use of a highly dangerous function whose > semantics is entirely unclear, depending on the vagaries of evaluation > strategy of the particular compiler) (yes, unsafePerformIO clearly isn't for ephemeral data structures.) > For example consider a simple GUI Ah, the dreaded functional GUI problem. Yes, I agree that a good purely functional way of declaring a GUI has not been discovered yet, the signals and streams somehow miss something important. > I've wasted at > least a whole year of sleepless nights trying to work out how to > represent an efficient GUI without using mutable data, and the feeling > that there should be a pure solution made me abandon a perfectly > workable imperative GUI that I started 18 months ago, that if I'd > written it in any other language without this pure/impure conundrum, > would have made me very happy with it. It indeed seems that the "mathematics" behind GUIs are inherently difficult and the easiest framework to declare GUIs _for now_ is an imperative one. That doesn't mean that a simpler one doesn't exist. Note that word _declare_: you don't want to mutate state a priori, you want to say what is displayed when and somehow describe the data dependencies. Once a domain specific language to declare GUIs is found, I'm sure that it can naturally be embedded in Haskell. > For example consider a simple GUI with 2 edit widgets, a splitter, > and a single buffer that contains the text being edited. The idea > is that you should be able to use either edit widget to interact > with the same buffer eg to edit at different locations in the > buffer. A simple imperative solution might be something like: > > main = do > buffer <- createBuffer > edit1 <- createEdit buffer > edit2 <- createEdit buffer > splitter <- createSplitter (wrapWidget edit1) (wrapWidget edit2) > runMessageLoopWith splitter > > Here it's really clear what's happening, and different objects in the > program correspond exactly to how I think about what I'm trying to do ie > I want to create individual objects with identity and then plug them > together. I don't want to have to bother about passing state around, or > having to define a new data type every time I want a different > configuration of widgets. Thus the ability to abstract mutable state > gives to my mind by far the best solution. I'm not sure whether mutable state is the real goodie here. I think it's the ability to indpendently access parts of a compound state. In other words, the IORef created by buffer is a part of the total program state but you can access it independently. There is a functional idiom for that, see also Sander Evers, Peter Achten, and Jan Kuper. "A Functional Programming Technique for Forms in Graphical User Interfaces". http://www.st.cs.ru.nl/papers/2005/eves2005-FFormsIFL04.pdf > apfelmus wrote: >> However, most "genuinely imperative" things are often just a building >> block for a higher level functional model. Thanks to your response, I think I can better articulate what I mean: with "purely functional", I mean "declarative", i.e. the ability to write down equations of how different things interact with each other and thus to abstract away their implementation. For example, - For Graphics, I want to build a graphic from smaller ones and then draw it. I don't want to know how drawing is implemented and what mutable state might be involved. - For a GUI, I want to write down the data dependencies and a library converts this to a mesh of mutable state. That's what I mean with "higher level functional model". Syntactic sugar for applying monadic actions doesn't help with that. In fact, it intends to make it easier to write examples and miss the pattern/model behind. Likewise, allowing impure functions -> doesn't help with formulating or finding a model at all. Rather, it makes describing the model more error-prone. Of course, I want to implement the imperative machinery too. But most often, deriving it from the underlying model is straightforward. Regards, apfelmus From carette at mcmaster.ca Sat Aug 11 10:21:15 2007 From: carette at mcmaster.ca (Jacques Carette) Date: Sat Aug 11 10:19:36 2007 Subject: [Haskell-cafe] How odd... In-Reply-To: <625b74080708041406h94d8ce8hbe798315cf30e85e@mail.gmail.com> References: <46B468B3.7000704@btinternet.com> <46B4CC9B.6090003@vex.net> <625b74080708041247p541e4b4etd931f5d827a91f6c@mail.gmail.com> <2ea1ace50708041335t5ba11d22o19bcf8561eaeee55@mail.gmail.com> <625b74080708041406h94d8ce8hbe798315cf30e85e@mail.gmail.com> Message-ID: <46BDC5DB.3060302@mcmaster.ca> [Sorry for the long quote, but context is important] Dan Piponi wrote: > It's fairly standard practice, when documenting functions of a complex > variable, to specify precisely which 'branch cuts' are being used. > Here's a quote from the Mathematica documentation describing their Log > function: "Log[z] has a branch cut discontinuity in the complex z > plane running from -infinity to 0". > > >> With this interpretation, (-1)^(1/3) = 0.5 + sqrt(3)/2 * i. If you go with >> the real solution (-1) you might need to do so carefully in order to >> preserve other useful properties of ^, like continuity. >> > > You can guarantee this by making sure you make the right 'cuts'. > If only it were that simple. Up until rather recently, it was not even known if there was a set of "right cuts" for ln and all the arc-trig functions that would work "together" properly. See `"According to Abramowitz and Stegun" or arccoth needn't be uncouth', by Corless, Jeffrey, Watt and Davenport, available from http://citeseer.ist.psu.edu/corless00according.html or http://www.apmaths.uwo.ca/~djeffrey/Offprints/couth.pdf This is by no means a solved problem. For example, there is still no consensus as to where the branch cuts for the various versions of the LegendreQ function should go. Jacques From apfelmus at quantentunnel.de Sat Aug 11 10:54:10 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Sat Aug 11 10:46:06 2007 Subject: [Haskell-cafe] Re: zip3, zip4 ... -> zipn? In-Reply-To: <0e3d01c7dbed$59676970$64c5a8c0@galilei> References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> Message-ID: Frank Buss schrieb: > Is it possible to write a function like this: > > zipn n list_1 list_2 list_3 ... list_n > > which implements zip3 for n=3, zip4 for n=4 etc.? Looks like variable number > of arguments are possible, like printf shows, so a general zipn should be > possible, too. If it is possible, why there are functions like zip5 and not > just zipn? What type would this function have? It's not possible to formulate this type in Haskell98. The problem is that the number of arguments cannot be determined statically, i.e. it depends on the value of n at run-time. There are languages more freaky than Haskell (like Agda or Epigram ) that can do that (without dynamic typing, that is!), they are called "dependently typed". However, type-class hackery (or type synonym families once they're available in GHC) can be used to do something like that if you give the value of n at compile-time. I won't dwell into that, though. Also, applicative functors can help GHCi> :m +Control.Applicative GHCi> (\x y z -> x*(y+z)) <$> ZipList [1,2,3] <*> ZipList [-1,0,1] <*> ZipList [1,1,1] ZipList [0,2,6] GHCi> (the second command is a single line.) Regards, apfelmus From byorgey at gmail.com Sat Aug 11 11:02:17 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Sat Aug 11 10:54:05 2007 Subject: [Haskell-cafe] zip3, zip4 ... -> zipn? In-Reply-To: <0e3d01c7dbed$59676970$64c5a8c0@galilei> References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> Message-ID: <22fcbd520708110802n4ac030c4s424d5470c4b168b3@mail.gmail.com> On 8/11/07, Frank Buss wrote: > > Is it possible to write a function like this: > > zipn n list_1 list_2 list_3 ... list_n > > which implements zip3 for n=3, zip4 for n=4 etc.? Looks like variable > number > of arguments are possible, like printf shows, so a general zipn should be > possible, too. If it is possible, why there are functions like zip5 and > not > just zipn? Template Haskell can also be used to generate appropriate code for zipn (in fact, the original paper on TH even uses this as an example [1]). But again, this approach only works if the value of n is known at compile time. -Brent [1] http://www.haskell.org/th/papers/meta-haskell.ps -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/0f2ae86b/attachment.htm From byorgey at gmail.com Sat Aug 11 11:09:08 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Sat Aug 11 11:00:57 2007 Subject: [Haskell-cafe] Defining new operators In-Reply-To: <20594c670708101431r1fef26c3k21a02682acc7f0a7@mail.gmail.com> References: <20594c670708101431r1fef26c3k21a02682acc7f0a7@mail.gmail.com> Message-ID: <22fcbd520708110809n112e272dp31b7cd06905a0397@mail.gmail.com> On 8/10/07, Shachaf Ben-Kiki wrote: > > > Also consider using: > > > data Step = Step { ..., scenario :: Scenario, ... } Just to expand on Shachaf's answer, when defining a data type you can use a special record syntax to give names to each of the components, like this: data Monkey = M { species :: Species, color :: Color } This automatically gives you functions called 'species' and 'color' which you can apply to values of type Monkey to extract the relevant components. So in your case, you could write something like data Step = Step { ..., owner :: Scenario, ... } ...which would give you the 'owner' function you defined above for free, without having to type it out. To expand on Dan and Albert's answers, the 'functional idiom' would be to just write 'owner x' -- introducing something like a different definition of . to do 'record selection' might make things easier in the short term (i.e. if you are used to programming in an OO paradigm) but seems quite detrimental in the long term. Trying to force Haskell to look and feel like other languages you are used to is like taking two of the wheels off your Porsche because you are used to riding a bicycle. =) -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/b218682d/attachment.htm From njbartlett at gmail.com Sat Aug 11 11:30:35 2007 From: njbartlett at gmail.com (Neil Bartlett) Date: Sat Aug 11 11:22:24 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> Message-ID: Hugh, I certainly think it would be wrong to declare that NDP is doomed to failure... not because you would be making an enemy of SPJ (I'm pretty sure you wouldn't!) but because it actually aims to solves a less ambitious problem: the problem of parallelising the SAME task applied to different data, rather than a collection of arbitrary tasks. Because the task does not change, we know that e.g. taking half the data cuts the amount of work in half. Therefore an up-front scheduling approach can work. If you fast forward to about 42 minutes into the London HUG video, you see that Simon talks about the problem of parallelizing (f x) + (g y), and says that he spent "quite a lot of time in the eighties trying to make this game go fast [..] and the result was pretty much abject failure". You're absolutely right that a dynamic/adaptive approach is the only one that will work when the tasks are of unknown size. Whether this approach is as easy as you think is open for you to prove. I look forward to testing your VM implementation, or at the very least reading your paper on the subject ;-) Regards, Neil On 8/11/07, Hugh Perkins wrote: > On 8/11/07, Thomas Conway wrote: > > There are many papers about this in the Parallel Logic Programming > > area. It is commonly called "Embarrassing Parallelism". > > Ah, I wasnt very precise ;-) I didnt mean I dont understand the > problem; I meant I dont understand why people think it is difficult to > solve ;-) (And then I tried to explain by examples why it is easy, > but it is true that my communication sucks ;-) ) > > > you'll only get a benefit if you can break xs into chunks > of e.g. 10^3 elements or more, and more like 10^5 or more for more > usual 'f's. > > Actually, the number of elements is irrelevant. The only measure that > is important is how long the function is taking to execute, and > whether it is parellizable. > > Example, the following only has 3 elements but will take a while to run: > > strPrtLn $ sum $ map getNumberPrimes [10240000, 20480000, 40960000 ] > > The following has 10 million elements but runs quickly: > > strPrtLn $ sum $ map (+1) [1..10000000 ] > > In the second, we start the function running, in a single thread, and > after a second, the function has already finished, so great! Were > done! > > In the first, we start the function running, in a single thread. > After a second the function is still running, so we look at what is > taking the time and whether it is parallelizable. > > Turns out the vm has been chugging away on the map for the last > second, and that that maps are parallelizeable, so we split the map > into Math.Min( , ) pieces, which on a > 1024-core machine, given we have 3 elements, is Math.Min( 1024, 3 ), > which is 3. > > So, we assign each of the 3 elements of the map to a thread. So, now > we're using 3 of our 64 cores. > > A second later, each thread is still chugging away at its element, so > we think, ok, maybe we can parallelize more, because we still have 61 > threads/cores available, so now we look at the getNumberOfPrimes > function itself, and continue the above type of analysis. > > This continues until all 64 cores have been assigned some work to do. > > Whenever a thread finishes, we look around for some work for it to do. > If there is some, we assign it. If there isnt, we look around for an > existing thread that is doing something parallelizeable, and split it > into two pieces, giving one to the old thread, and one to the > available thread. > > Not sure why this is perceived as difficult (added the word > "perceived" this time ;-) ). I think the main barrier to > understanding why it is easy is understanding that this needs to be > done from a VM, at runtime. It is not possible to do it statically at > compilation, but I really need to finish watching SPJ's video before > declaring that SPJ's proposal is doomed to fail ;-) Not least, > probably not good to make an enemy of SPJ ;-) > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From per.vognsen at gmail.com Sat Aug 11 11:51:35 2007 From: per.vognsen at gmail.com (Per Vognsen) Date: Sat Aug 11 11:43:24 2007 Subject: [Haskell-cafe] Re: zip3, zip4 ... -> zipn? In-Reply-To: References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> Message-ID: On 8/11/07, apfelmus wrote: > Frank Buss schrieb: > > Is it possible to write a function like this: > > > > zipn n list_1 list_2 list_3 ... list_n > > > > which implements zip3 for n=3, zip4 for n=4 etc.? Looks like variable number > > of arguments are possible, like printf shows, so a general zipn should be > > possible, too. If it is possible, why there are functions like zip5 and not > > just zipn? > > What type would this function have? It's not possible to formulate this > type in Haskell98. The problem is that the number of arguments cannot be > determined statically, i.e. it depends on the value of n at run-time. > There are languages more freaky than Haskell (like Agda or Epigram ) > that can do that (without dynamic typing, that is!), they are called > "dependently typed". > > However, type-class hackery (or type synonym families once they're > available in GHC) can be used to do something like that if you give the > value of n at compile-time. I won't dwell into that, though. > > Also, applicative functors can help > > GHCi> :m +Control.Applicative > GHCi> (\x y z -> x*(y+z)) <$> ZipList [1,2,3] > <*> ZipList [-1,0,1] <*> ZipList [1,1,1] > ZipList [0,2,6] > GHCi> > > (the second command is a single line.) Applicative functors can indeed help: (,,,) <$> [1,2,3] <*> [-1,0,1] <*> [1,1,1] <*> [0,2,6] You just use n-1 commas when you want the effect of zipn. -Per From bhurt at spnz.org Sat Aug 11 12:35:49 2007 From: bhurt at spnz.org (Brian Hurt) Date: Sat Aug 11 12:16:14 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> Message-ID: You guys might also want to take a look at the Cilk programming language, and how it managed threads. If you know C, learning Cilk is about 2 hours of work, as it's C with half a dozen extra keywords and a few new concepts. I'd love to see Cilk - C + Haskell as a programming language. The key idea of Cilk is that it's easier to deparallelize than it is to parallelize, especially automatically. So the idea is that the program is written incredibly parallel, with huge numbers of microthreads, which are (on average) very cheap to spawn. The runtime then deparallelizes the microthreads, running multiple microthreads sequentially within a single real thread (a worker thread). Microthreads that live their entire life within a single real thread are cheap to spawn (as in "not much more expensive than a normal function call" cheap). The problem that Cilk runs into is that it's, well, C. It doesn't deal with contention at well at all- a single microthread blocking blocks the whole worker thread- meaning, among other things, that you can have "false deadlocks", where one microthread blocks on another microthread in the same real thread, and thus acts like it's deadlocked even though it really isn't. You have greatly increased the likelyhood of raceconditions as well (mutable data and multithreading just don't mix). Plus you have all the normal fun you have with C bugs- wild pointers, buffer over runs, etc. All of which you avoid if you replace the C aspects of Cilk with Haskell. With STM you avoid the deadlock problem entirely, and with immutable data (except for carefully coded monads) you avoid the whole race condition problem. Plus all the normal advantages Haskell has over C. Just my $0.02. Brian On Sat, 11 Aug 2007, Neil Bartlett wrote: > Hugh, > > I certainly think it would be wrong to declare that NDP is doomed to > failure... not because you would be making an enemy of SPJ (I'm pretty > sure you wouldn't!) but because it actually aims to solves a less > ambitious problem: the problem of parallelising the SAME task applied > to different data, rather than a collection of arbitrary tasks. > Because the task does not change, we know that e.g. taking half the > data cuts the amount of work in half. Therefore an up-front scheduling > approach can work. > > If you fast forward to about 42 minutes into the London HUG video, you > see that Simon talks about the problem of parallelizing (f x) + (g y), > and says that he spent "quite a lot of time in the eighties trying to > make this game go fast [..] and the result was pretty much abject > failure". > > You're absolutely right that a dynamic/adaptive approach is the only > one that will work when the tasks are of unknown size. Whether this > approach is as easy as you think is open for you to prove. I look > forward to testing your VM implementation, or at the very least > reading your paper on the subject ;-) > > Regards, > Neil > > > On 8/11/07, Hugh Perkins wrote: >> On 8/11/07, Thomas Conway wrote: >>> There are many papers about this in the Parallel Logic Programming >>> area. It is commonly called "Embarrassing Parallelism". >> >> Ah, I wasnt very precise ;-) I didnt mean I dont understand the >> problem; I meant I dont understand why people think it is difficult to >> solve ;-) (And then I tried to explain by examples why it is easy, >> but it is true that my communication sucks ;-) ) >> >>> you'll only get a benefit if you can break xs into chunks >> of e.g. 10^3 elements or more, and more like 10^5 or more for more >> usual 'f's. >> >> Actually, the number of elements is irrelevant. The only measure that >> is important is how long the function is taking to execute, and >> whether it is parellizable. >> >> Example, the following only has 3 elements but will take a while to run: >> >> strPrtLn $ sum $ map getNumberPrimes [10240000, 20480000, 40960000 ] >> >> The following has 10 million elements but runs quickly: >> >> strPrtLn $ sum $ map (+1) [1..10000000 ] >> >> In the second, we start the function running, in a single thread, and >> after a second, the function has already finished, so great! Were >> done! >> >> In the first, we start the function running, in a single thread. >> After a second the function is still running, so we look at what is >> taking the time and whether it is parallelizable. >> >> Turns out the vm has been chugging away on the map for the last >> second, and that that maps are parallelizeable, so we split the map >> into Math.Min( , ) pieces, which on a >> 1024-core machine, given we have 3 elements, is Math.Min( 1024, 3 ), >> which is 3. >> >> So, we assign each of the 3 elements of the map to a thread. So, now >> we're using 3 of our 64 cores. >> >> A second later, each thread is still chugging away at its element, so >> we think, ok, maybe we can parallelize more, because we still have 61 >> threads/cores available, so now we look at the getNumberOfPrimes >> function itself, and continue the above type of analysis. >> >> This continues until all 64 cores have been assigned some work to do. >> >> Whenever a thread finishes, we look around for some work for it to do. >> If there is some, we assign it. If there isnt, we look around for an >> existing thread that is doing something parallelizeable, and split it >> into two pieces, giving one to the old thread, and one to the >> available thread. >> >> Not sure why this is perceived as difficult (added the word >> "perceived" this time ;-) ). I think the main barrier to >> understanding why it is easy is understanding that this needs to be >> done from a VM, at runtime. It is not possible to do it statically at >> compilation, but I really need to finish watching SPJ's video before >> declaring that SPJ's proposal is doomed to fail ;-) Not least, >> probably not good to make an enemy of SPJ ;-) >> _______________________________________________ >> Haskell-Cafe mailing list >> Haskell-Cafe@haskell.org >> http://www.haskell.org/mailman/listinfo/haskell-cafe >> > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From andrewcoppin at btinternet.com Sat Aug 11 12:34:40 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 11 12:25:54 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> Message-ID: <46BDE520.3020905@btinternet.com> Brian Hurt wrote: > The key idea of Cilk is that it's easier to deparallelize than it is > to parallelize, especially automatically. So the idea is that the > program is written incredibly parallel, with huge numbers of > microthreads, which are (on average) very cheap to spawn. The runtime > then deparallelizes the microthreads, running multiple microthreads > sequentially within a single real thread (a worker thread). > Microthreads that live their entire life within a single real thread > are cheap to spawn (as in "not much more expensive than a normal > function call" cheap). That's so absurd, it might even work! I quite like the concept though - rather than asking "what can we make parallel?", you say "what should we do serially?" That sounds like an easier question to answer... From sebastian.sylvan at gmail.com Sat Aug 11 12:48:46 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Sat Aug 11 12:40:34 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> Message-ID: <3d96ac180708110948tdbb4d51q30d2eef9a9e69012@mail.gmail.com> On 11/08/07, Brian Hurt wrote: > > You guys might also want to take a look at the Cilk programming language, > and how it managed threads. If you know C, learning Cilk is about 2 hours > of work, as it's C with half a dozen extra keywords and a few new > concepts. I'd love to see Cilk - C + Haskell as a programming language. > > The key idea of Cilk is that it's easier to deparallelize than it is to > parallelize, especially automatically. So the idea is that the program is > written incredibly parallel, with huge numbers of microthreads, which are > (on average) very cheap to spawn. The runtime then deparallelizes the > microthreads, running multiple microthreads sequentially within a single > real thread (a worker thread). Microthreads that live their entire life > within a single real thread are cheap to spawn (as in "not much more > expensive than a normal function call" cheap). > > The problem that Cilk runs into is that it's, well, C. It doesn't deal > with contention at well at all- a single microthread blocking blocks the > whole worker thread- meaning, among other things, that you can have "false > deadlocks", where one microthread blocks on another microthread in the > same real thread, and thus acts like it's deadlocked even though it really > isn't. You have greatly increased the likelyhood of raceconditions as > well (mutable data and multithreading just don't mix). Plus you have all > the normal fun you have with C bugs- wild pointers, buffer over runs, etc. > > All of which you avoid if you replace the C aspects of Cilk with Haskell. > With STM you avoid the deadlock problem entirely, and with immutable data > (except for carefully coded monads) you avoid the whole race condition > problem. Plus all the normal advantages Haskell has over C. > How is this any better than using "par" in Haskell? -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From lemming at henning-thielemann.de Sat Aug 11 14:28:25 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sat Aug 11 14:20:53 2007 Subject: [Haskell-cafe] Haddock: documenting parameters of functional arguments Message-ID: I like to write documentation comments like fix :: ( a {- ^ local argument -} -> a {- ^ local output -} ) -> a {- ^ global output -} but Haddock doesn't allow it. Or is there a trick to get it work? From bulat.ziganshin at gmail.com Sat Aug 11 14:48:22 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sat Aug 11 14:40:57 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> Message-ID: <141060182.20070811224822@gmail.com> Hello Brian, Saturday, August 11, 2007, 8:35:49 PM, you wrote: > The key idea of Cilk is that it's easier to deparallelize than it is to > parallelize, especially automatically. So the idea is that the program is > written incredibly parallel, with huge numbers of microthreads, which are > (on average) very cheap to spawn. The runtime then deparallelizes the > microthreads, running multiple microthreads sequentially within a single > real thread (a worker thread). this idea is in wide use now: it's how ghc, erlang, ruby and virtually any other interpreting languages work :)) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From ronguida at mindspring.com Sat Aug 11 15:00:04 2007 From: ronguida at mindspring.com (Ronald Guida) Date: Sat Aug 11 14:49:50 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> Message-ID: <46BE0734.3040308@mindspring.com> David Menendez wrote: > Be sure to read sigpfe's "You could have invented monads!" and the > Wadler paper. > > > > > Most tutorials try to explain what a monad *is*, but these focus > more on why they're a useful way to organize code. In my experience, > being able to use a monad is more important than understanding the > theory. Hey, now I know what a monad is! What I missed in all those tutorials is that a monad is an *abstract base class*. With this realization, which I had after reading the sigfpe tutorial, everything makes sense for me. To review a basic OOP example, I can't illustrate what a Vehicle *is* in general terms. I can illustrate a Bicycle, a Car, a Boat, a Plane, a Submarine, a Hovercraft, a LARC-V, and many other examples of instances of /subclasses/ of Vehicle, but I can't find anything that's /just/ a Vehicle. In OOP, Vehicle is an abstract base class. The same thing applies for a Monad. I can look at lots and lots of instances, like Maybe, Either, List, State, Reader, Writer, IO, and lots of others, but I can't produce an example that's /just/ a Monad. Monad is an abstract base class, too. Now if I had to explain "What is a Vehicle", I would have to say "A Vehicle is a device that provides transportation." When asked for more details, I can specify the interface and provide examples of instances. Interface for Vehicle: load, unload, goto Instances of Vehicle: Bicycle, Car, Plane, Boat, etc. Given the question "What is a Monad", I would have to say "A Monad is a device for sequencing side-effects." When asked for more details, I can specify the interface and provide examples of instances. Interface for Monad: return, bind Instances of Monad: Maybe, Either, List, State, etc. What is particularly stupefying for me is that I missed the fact that Monad is "obviously" an abstract base class: Monad is declared as a type-class! Now the hard part. As far I currently know - and I could be wrong: (1) Monad, Comonad and Arrow are all abstract base classes. (2) Monad, Comonad and Arrow are all devices for sequencing side-effects. (3) Monad and Comonad are both specializations of Arrow. Given the question "What is an Arrow", I would have to say "An Arrow is a device for sequencing side-effects." When asked for more details, I can specify the interface and provide examples of instances. This leads directly to the question "What makes a Monad special, compared to an Arrow?" Right now, the clues I have are: (1) Every monad is equivalent to a Kleisli arrow. (2) The ArrowApply class is equivalent to the Monad class. I can restate the question: "What is special about ArrowApply, compared to Arrow?" I see that an arrow accepts some inputs, performs a computation, possibly with side-effects, and generates some outputs. In particular, suppose I create instances of Arrow that accept two inputs (as a pair) and produce one output. Some of these instances (i.e. ArrowApply) are special: I can provide, as the two inputs, (1) an Arrow that accepts one input and one output, and (2) an input suitable for that Arrow. The output that I get is the result of feeding input (2) to input (1) to get a result, *and* somehow combining the side-effects of both arrows. The only way an ArrowApply can combine the side effects of two arrows and still obey the Arrow laws is through an operation that takes an (arrow nested inside an arrow) and collapses it into a sigle arrow. That's exactly what "join" does for monads. So, ArrowApply is special, compared to Arrow, because ArrowApply has a join operation, but Arrow doesn't. Clear as mud! The question remains: "What is special about Monad or ArrowApply, compared to Arrow?" or "What is more general about Arrow, compared to Monad or ArrowApply?" -- Ron From ccshan at post.harvard.edu Sat Aug 11 14:54:42 2007 From: ccshan at post.harvard.edu (Chung-chieh Shan) Date: Sat Aug 11 14:51:53 2007 Subject: [Haskell-cafe] Re: zip3, zip4 ... -> zipn? References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> Message-ID: Frank Buss wrote in article <0e3d01c7dbed$59676970$64c5a8c0@galilei> in gmane.comp.lang.haskell.cafe: > Is it possible to write a function like this: > > zipn n list_1 list_2 list_3 ... list_n > > which implements zip3 for n=3, zip4 for n=4 etc.? Looks like variable number > of arguments are possible, like printf shows, so a general zipn should be > possible, too. If it is possible, why there are functions like zip5 and not > just zipn? Check out: Fridlender, Daniel, and Mia Indrika. 2000. Do we need dependent types? Journal of Functional Programming 10(4):409-415. http://www.math.chalmers.se/~indrika/jfp.ps.gz McBride, Conor. 2002. Faking it: Simulating dependent types in Haskell. Journal of Functional Programming 12(4-5): 375-392. -- Edit this signature at http://www.digitas.harvard.edu/cgi-bin/ken/sig Remember Hirosima 1945-08-06, Nagasaki 1945-08-09. http://petitions.pm.gov.uk/Free-Vanunu/ http://www.vanunu.org/ From lemming at henning-thielemann.de Sat Aug 11 15:10:19 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sat Aug 11 15:02:05 2007 Subject: [Haskell-cafe] Re: default for quotRem in terms of divMod? Message-ID: Btw. is there any application, where 'quot' and 'rem' are needed? All occurrences of 'quot' and 'rem' I found in code so far were actually wrong and should have been 'div' and 'mod'. http://www.haskell.org/haskellwiki/Things_to_avoid#Forget_about_quot_and_rem From stefanor at cox.net Sat Aug 11 15:17:16 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sat Aug 11 15:09:04 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46BE0734.3040308@mindspring.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> <46BE0734.3040308@mindspring.com> Message-ID: <20070811191716.GA3460@localhost.localdomain> On Sat, Aug 11, 2007 at 03:00:04PM -0400, Ronald Guida wrote: > The question remains: "What is special about Monad or ArrowApply, > compared to Arrow?" or "What is more general about Arrow, compared to > Monad or ArrowApply?" If all you have is an Arrow, then you must make up your mind what you're going to do ahead of time. ArrowChoice gives you the ability to make basic "yes or no" decisions at run time. ArrowApply gives you arbitrary computed jumps. Sometimes it's useful to restrict what you can do. Duponcheel and Swierstra wrote a parser library as an Arrow; because it forced you to decide the parsing structure ahead of time, their library had enough information to build LR-type parsing tables, and thus to do yacc-style error correction. (Nobody found it useful enough to use, but it still makes a nice demonstration of why plain Arrow is sometimes better.) Conversely, some applications *need* the extra freedom. Imagine trying to write an interpreter for a toy language with I/O, and IO is a plain Arrow and not a Monad. You can read input and parse it, but you can't actually do IO because the IO you need to do, depends on the input you read - precisely what Arrow forbids! Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/91a863a8/attachment.bin From stefanor at cox.net Sat Aug 11 15:24:05 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sat Aug 11 15:15:53 2007 Subject: [Haskell-cafe] zip3, zip4 ... -> zipn? In-Reply-To: <837db430708110227j6e401e78n783f228388e7e05a@mail.gmail.com> References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> <34e5cfb80708110152k18d789b4jdbba48d2e6aabbc2@mail.gmail.com> <837db430708110227j6e401e78n783f228388e7e05a@mail.gmail.com> Message-ID: <20070811192405.GB3460@localhost.localdomain> On Sat, Aug 11, 2007 at 05:27:19PM +0800, Hugh Perkins wrote: > I was looking for something like this too. > > Note that Erlang can do this ;-) but Erlang is probably not so > strongly typed, so it's easier to do? I think the main issue is that Erlang doesn't use currying (IIRC). Currying makes it MUCH harder to implement varargs functions. (We thought this was a good tradeoff - partial applications give Haskell much more power than varargs would have.) (Unfortunately I don't know of any good languages with powerful type systems and vararg functions that can take advantage of powerful types... I'd love to give example code here :)) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/71fa2fb6/attachment.bin From derek.a.elkins at gmail.com Sat Aug 11 15:24:57 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Sat Aug 11 15:17:05 2007 Subject: [Haskell-cafe] Re: default for quotRem in terms of divMod? In-Reply-To: References: Message-ID: <1186860297.6796.80.camel@derek-laptop> On Sat, 2007-08-11 at 21:10 +0200, Henning Thielemann wrote: > Btw. is there any application, where 'quot' and 'rem' are needed? All > occurrences of 'quot' and 'rem' I found in code so far were actually wrong > and should have been 'div' and 'mod'. > > http://www.haskell.org/haskellwiki/Things_to_avoid#Forget_about_quot_and_rem quotRem is faster than divMod, and my understanding is that even divMod is arguably broken. http://www.cs.uu.nl/~daan/download/papers/divmodnote-letter.pdf From stefanor at cox.net Sat Aug 11 15:37:20 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sat Aug 11 15:29:08 2007 Subject: [Haskell-cafe] howto install ghc-6.7.* ? In-Reply-To: <200708111144.23249.coeus@gmx.de> References: <200708111144.23249.coeus@gmx.de> Message-ID: <20070811193720.GA3582@localhost.localdomain> On Sat, Aug 11, 2007 at 11:44:17AM +0200, Marc A. Ziegert wrote: > i just don't get it. > please, can anybody explaim me how to do that? > i tried it the last few days with ghc-6.7.20070807, ghc-6.7.20070809, and ghc-6.7.20070810. > it always results in a broken library (without Prelude): > > # ghc-pkg list > /usr/local/lib/ghc-6.7.20070810/package.conf: > {ghc-6.7.20070810}, rts-1.0 > > i did this on my gentoo-i386-box (pretty old, takes 1h for quick build, 3.5h without mk/build.mk): > > T=20070810 > tar xjf ghc-6.7.$T-src.tar.bz2 > tar xjf ghc-6.7.$T-src-extralibs.tar.bz2 > cd ghc-6.7.$T > ( > #echo BuildFlavour = quick > #cat mk/build.mk.sample > echo HADDOCK_DOCS = YES > ) > mk/build.mk > ./configure && ( time nice -n 19 make all install ) > > > those extralibs seem to be installed in > /usr/local/lib/ghc-6.7.20070810/lib/ > but registered in > ghc-6.7.20070810/driver/package.conf.inplace > instead of > /usr/local/lib/ghc-6.7.20070810/package.conf Last time I built GHC, I needed to run 'sh boot' right before configure. Don't know if this has anything to do with your problem, however. (It would also be a Good Idea to add 2>&1 | tee -a make.log to that command line, and look at the logs afterward...) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/d3f7be27/attachment.bin From gregorypropf at yahoo.com Sat Aug 11 16:06:43 2007 From: gregorypropf at yahoo.com (Gregory Propf) Date: Sat Aug 11 15:58:31 2007 Subject: [Haskell-cafe] IO within parser Message-ID: <672187.69183.qm@web31409.mail.mud.yahoo.com> I've been struggling with writing a parser that needs to parse include files within source files. So far I cannot get this to work (in reality to get work done I wrote a kludge that returns a list of include filenames to be run later in a pure IO function. I realized that this just amounted to creating my own half-assed monad system so I really don't want to use this approach). I have read the tutorials I could find on monad transformers but I still don't see what's going on. I'm using the Parsec parser library. Here's an simple example of what I've tried. I also tried using liftIO and got a message about needing to add an instance of MonadIO. This made more sense but the type of liftIO is baffling class Monad m => MonadIO m where liftIO :: IO a -> m a But how do you define this function? There is no constructor for "IO a" that you can "take apart". Anyway, here is the code that just uses lift. Keep in mind that the outer monad is just "GenParser Char st [Char]". I'm guessing this is wrong and I should have a transformer monad as the outer layer. But which one? and how to use it? pio = do { s <- many1 alphaNum; input <- lift (readFile s); return input; } go6 = runParser pio () "" "This is a test" ================================= ghc output from trying to load this is ================================= Couldn't match kind `* -> * -> *' against `(* -> *) -> * -> *' When matching the kinds of `GenParser Char :: * -> * -> *' and `t :: (* -> *) -> * -> *' Expected type: GenParser Char st Inferred type: t IO In a 'do' expression: lift (writeFile "Foo" s) ____________________________________________________________________________________ Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/9500d77b/attachment.htm From andrewcoppin at btinternet.com Sat Aug 11 16:25:16 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 11 16:16:27 2007 Subject: [Haskell-cafe] IO within parser In-Reply-To: <672187.69183.qm@web31409.mail.mud.yahoo.com> References: <672187.69183.qm@web31409.mail.mud.yahoo.com> Message-ID: <46BE1B2C.5070000@btinternet.com> Gregory Propf wrote: > I've been struggling with writing a parser that needs to parse include > files within source files. So far I cannot get this to work (in > reality to get work done I wrote a kludge that returns a list of > include filenames to be run later in a pure IO function. I realized > that this just amounted to creating my own half-assed monad system so > I really don't want to use this approach). I have read the tutorials > I could find on monad transformers but I still don't see what's going > on. I'm using the Parsec parser library. Here's an simple example of > what I've tried. I also tried using liftIO and got a message about > needing to add an instance of MonadIO. This made more sense but the > type of liftIO is baffling The fun part is that Parsec already has a feature for include files... (I can't remember where the heck it is or how you use it though.) From marco-oweber at gmx.de Sat Aug 11 16:47:40 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Sat Aug 11 16:39:30 2007 Subject: [Haskell-cafe] Re: zip3, zip4 ... -> zipn? In-Reply-To: References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> Message-ID: <20070811204740.GC18563@gmx.de> > Also, applicative functors can help > > GHCi> :m +Control.Applicative > GHCi> (\x y z -> x*(y+z)) <$> ZipList [1,2,3] > <*> ZipList [-1,0,1] <*> ZipList [1,1,1] > ZipList [0,2,6] > GHCi> http://www.soi.city.ac.uk/~ross/papers/Applicative.pdf quote "The general scheme is as follows:" (page 2) Marc From isaacdupree at charter.net Sat Aug 11 17:53:50 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Sat Aug 11 17:56:35 2007 Subject: [Haskell-cafe] Re: default for quotRem in terms of divMod? In-Reply-To: References: Message-ID: <46BE2FEE.9020607@charter.net> Henning Thielemann wrote: > Btw. is there any application, where 'quot' and 'rem' are needed? All > occurrences of 'quot' and 'rem' I found in code so far were actually wrong > and should have been 'div' and 'mod'. > > http://www.haskell.org/haskellwiki/Things_to_avoid#Forget_about_quot_and_rem Yes, my implementation of Integer in terms of lists of Int, deliberately uses the symmetry of quotRem in order to store negative numbers as the negation of all elements of the positive number, and be able to virtually ignore the signs most of the time. (Also because quotRem is usually faster, I figured it made sense to use that technique.) (It doesn't make any difference on numbers that cannot be negative, also.) Everywhere else I remember when coding, div/mod were the correct ones to use (even back when I was coding in C, I wished I had that rounding behavior some time). I do think that if you almost always want to _use_ div and mod, you should be able to just define div and mod too (not quot and rem) -- one reason I brought up the issue :) Isaac From isaacdupree at charter.net Sat Aug 11 18:02:00 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Sat Aug 11 18:04:50 2007 Subject: [Haskell-cafe] Re: default for quotRem in terms of divMod? In-Reply-To: <46BE2FEE.9020607@charter.net> References: <46BE2FEE.9020607@charter.net> Message-ID: <46BE31D8.3000004@charter.net> Isaac Dupree wrote: > I do think that if you almost always want to _use_ div and mod, you > should be able to just define div and mod too (not quot and rem) that was unclear - I mean you should have that choice, not that it should be disallowed to define quot and rem only! Isaac From goalieca at gmail.com Sat Aug 11 20:03:47 2007 From: goalieca at gmail.com (Ryan Dickie) Date: Sat Aug 11 19:55:33 2007 Subject: [Haskell-cafe] howto install ghc-6.7.* ? In-Reply-To: <200708111144.23249.coeus@gmx.de> References: <200708111144.23249.coeus@gmx.de> Message-ID: <4c69c1be0708111703o501eb298o93469ddf262e6235@mail.gmail.com> Same problem here. I downloaded the ghc-6.7.20070811.tar.bz2 snapshot build on amd64 under ubuntu. >From the README > The "sh boot" step is only necessary if this is a tree checked out > from darcs. For source distributions downloaded from GHC's web site, > this step has already been performed. On 8/11/07, Marc A. Ziegert wrote: > > i just don't get it. > please, can anybody explaim me how to do that? > i tried it the last few days with ghc-6.7.20070807, ghc-6.7.20070809, and > ghc-6.7.20070810. > it always results in a broken library (without Prelude): > > # ghc-pkg list > /usr/local/lib/ghc-6.7.20070810/package.conf: > {ghc-6.7.20070810}, rts-1.0 > > i did this on my gentoo-i386-box (pretty old, takes 1h for quick build, > 3.5h without mk/build.mk): > > T=20070810 > tar xjf ghc-6.7.$T-src.tar.bz2 > tar xjf ghc-6.7.$T-src-extralibs.tar.bz2 > cd ghc-6.7.$T > ( > #echo BuildFlavour = quick > #cat mk/build.mk.sample > echo HADDOCK_DOCS = YES > ) > mk/build.mk > ./configure && ( time nice -n 19 make all install ) > > > those extralibs seem to be installed in > /usr/local/lib/ghc-6.7.20070810/lib/ > but registered in > ghc-6.7.20070810/driver/package.conf.inplace > instead of > /usr/local/lib/ghc-6.7.20070810/package.conf > . > > > - marc > > _______________________________________________ > 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/haskell-cafe/attachments/20070811/ba22a057/attachment.htm From bhurt at spnz.org Sat Aug 11 21:12:19 2007 From: bhurt at spnz.org (Brian Hurt) Date: Sat Aug 11 20:52:43 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <3d96ac180708110948tdbb4d51q30d2eef9a9e69012@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <3d96ac180708110948tdbb4d51q30d2eef9a9e69012@mail.gmail.com> Message-ID: On Sat, 11 Aug 2007, Sebastian Sylvan wrote: > How is this any better than using "par" in Haskell? Mainly how the threads are actually scheduled. Mind you, I'm an *incredible* Haskell newbie, so take all of my comments with a 5-pound salt block, but as I understand how the current implementation of parallel Haskell works, all threads spawned go into a communal heap. When a thread blocks, it's put back into the communal queue, and a new thread is selected to run by the worker thread. In Cilk, the task structure is more tree-like. When thread A spawns thread B, the worker thread stops executing thread A and starts executing thread B. When thread B exits, the worker thread then resumes thread A. So in any given point in time, the worker thread has a stack of processes waiting for subthreads to complete so they can be resumed- not unlike function calls in other languages, or nested lazy blocks in Haskell. When a worker thread runs out of work to do, when it has no more threads to execute, it picks another worker thread at random, and asks the other worker thread for work to do. The other worker thread (assuming it has work to do) then picks the microthread at the bottom of the resume stack, that is farthest away from being resumed, and passes that microthread's state to the original worker thread. >From the user program's perspective, this is no different from the current implementation. Threads get spawned, get executed in some unspecified order, and then complete. What's interesting (to me, at least) are the optimization opportunities this model provides that the shared-queue model doesn't. Consider the following structural model: we have a two-tiered heap. Each worker thread has it's own local heap, which only microthreads it is managing can see. Plus there is a global heap with objects that all microthreads in all worker threads can see. Objects are originally allocated in the local heap. When a microthread to start being executed on another worker thread, all objects it can see (reach, in the conservative GC sense) are promoted to the global heap. The advantage of all of this is that now we can easily distinguish between objects that can be seen from other real threads, and those that can't. All of the mutable data structures- tvars, lazy thunks, everything- can be much more cheaply implemented if you know that no other thread can access them. Take the example of a parallel map, where I'm using a tvar in my map function. The likelyhood is that all of the (short-lived) microthreads I'm spawning will execute on the same worker thread- and that thus the tvar will never leave the local heap, and thus can be optimized down to something close to a single-threaded mvar. I have, via optimization, turned a parallel map and a synchronized tvar back into something approaching a serial map and an mvar. Brian From dry.green.tea at gmail.com Sat Aug 11 22:56:31 2007 From: dry.green.tea at gmail.com (Alexis Hazell) Date: Sat Aug 11 22:48:28 2007 Subject: [Haskell-cafe] zip3, zip4 ... -> zipn? In-Reply-To: <20070811192405.GB3460@localhost.localdomain> References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> <837db430708110227j6e401e78n783f228388e7e05a@mail.gmail.com> <20070811192405.GB3460@localhost.localdomain> Message-ID: <200708121256.32439.dry.green.tea@gmail.com> On Sunday 12 August 2007 05:24, Stefan O'Rear wrote: > Currying makes it MUCH harder to implement varargs functions. That's interesting - why is that the case? Alexis. From stefanor at cox.net Sat Aug 11 23:25:43 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sat Aug 11 23:17:32 2007 Subject: [Haskell-cafe] zip3, zip4 ... -> zipn? In-Reply-To: <200708121256.32439.dry.green.tea@gmail.com> References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> <837db430708110227j6e401e78n783f228388e7e05a@mail.gmail.com> <20070811192405.GB3460@localhost.localdomain> <200708121256.32439.dry.green.tea@gmail.com> Message-ID: <20070812032543.GA10207@localhost.localdomain> On Sun, Aug 12, 2007 at 12:56:31PM +1000, Alexis Hazell wrote: > On Sunday 12 August 2007 05:24, Stefan O'Rear wrote: > > > Currying makes it MUCH harder to implement varargs functions. > > That's interesting - why is that the case? varsum 2 3 -- varsum receives 2, and returns a function, which when -- passed 3, returns 5 varsum 2 3 4 -- varsum receives 2, and returns a function, which when -- passed 3, returns a function that when passed 4 returns -- 9. Because of this, the number of arguments must somehow be passed out-of-band; but then the type of the whole function (usually) must depend on the control parameter, requiring dependent types. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/d3ac03f2/attachment.bin From mad.one at gmail.com Sun Aug 12 00:13:38 2007 From: mad.one at gmail.com (Austin Seipp) Date: Sun Aug 12 00:05:24 2007 Subject: [Haskell-cafe] Infinity v0.1 Message-ID: Hello! Over the past couple of days I've been working on an IRC bot in the essence of lambdabot; that is, it should be extendable through plugins and plugins should be easy to write, modify and contribute. I also wanted the bot to be small in terms of LOC (as of 0.1, about ~360 including the two bundled plugins,) but still be usable. Well, now I have something to show for it, and I introduce infinity v0.1: http://austin.youareinferior.net/infinity-0.1.tar.gz (there is no darcs repo yet, although I have emailed someone about a possible account for darcs.haskell.org.) Everything from building to writing plugins should become fairly self evident from reading the README. You will need the hs-plugins to use it. As it stands, the bot is incredibly primitive and there are almost no plugins (I only wrote 'hello world' and 'goodbye world' plugins to test the code as it moved forward) as of yet, however, I had fun with this thing and I hope maybe someone could do something interesting with it. There're some parts of the code that I'm not particularly happy with. For the 0.2 release I have a couple of goals in mind: 1. To move the basic ad-hoc IRC parsing code (lots of drop and dropWhile and whatnot) to a more robust implementation such as parsec. This should hopefully clean up some of the code I'm not on good terms with. 2. To add support for in-situ reloading and re-compilation of modules, so you won't even have to restart the bot if you update a plugin. This will probably require some reworking of my threading code so that the environment stays safe and stable (STM?) 3. To move all of the built-in core commands to plugins as well; this will probably require encapsulating plugins in a monad (StateT) henceforth. I'm not exactly the most advanced haskell programmer ever born, but I enjoyed working on this code and while it isn't and probably won't ever be the next lambdabot, I hope someone can learn something from it or just have fun with it. If anybody would like to take the time to write a plugin or something for some interesting purpose, I would be happy to include it in the source tree (I'm sure you guys can come up with something more interesting than I can.) I would really appreciate any and all comments on the code. I still feel myself to be in an 'intermediate' area with Haskell, so anything you guys can add that would improve the code would be incredibly appreciated. PS: I've only tested this on an i386 linux box so if anybody here can confirm it works on other systems (bsd, solaris?) where hs-plugins is available, that would be awesome. Thanks! -- - Austin From brandon at regurgitate.ugcs.caltech.edu Sun Aug 12 01:10:09 2007 From: brandon at regurgitate.ugcs.caltech.edu (Brandon Michael Moore) Date: Sun Aug 12 01:02:00 2007 Subject: [Haskell-cafe] Re: towards a new foundation for set theory with atoms In-Reply-To: <5de3f5ca0708101554w471314c4ydd272d71081ca4e8@mail.gmail.com> References: <5de3f5ca0708101218j56a7b84fj50acef000dfb8433@mail.gmail.com> <5de3f5ca0708101554w471314c4ydd272d71081ca4e8@mail.gmail.com> Message-ID: <20070812051009.GA14652@regurgitate.ugcs.caltech.edu> On Fri, Aug 10, 2007 at 03:54:23PM -0700, Greg Meredith wrote: > Haskellians, > > A quick follow up. If you look at the code that i have written there is a > great deal of repeated structure. Each of these different kinds of sets and > atoms are isomorphic copies of each other. Because, however, of the > alternation discipline, i could see no way to abstract the structure and > simplify the code. Perhaps someone better versed in the Haskellian mysteries > could enlighten me. You could take a less absolute view of the game, and describe each node instead locally from the perspective of a player. Imagine Alice Bob and Carol sitting around a table: data ThreePlayers a b c = Next (ThreePlayer b c a) | Prev (ThreePlayers c a b) In general you can get subgroups of a symmetric group as your sets of colors this way (i.e, the set of elements of any group), I'm not quite sure how much freedom you have in the sets of allowed transitions (in particular, making some of the argument types identical can break symmetry). You could also go for the obvious big hammer, pretend that Haskell has a strongly normalizing subset and encode inequality explicitly with GADTs and such. date Eq a b where Refl a a data False type Neq a b = Eq a b -> False -- might be trouble if a and b are only equal non-constructively? data Red = Red data Green = Green .... data Set color where Red :: Neq Red color -> Set Red -> Set color ... Brandon From lemming at henning-thielemann.de Sun Aug 12 01:24:16 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sun Aug 12 01:16:02 2007 Subject: [Haskell-cafe] Re: default for quotRem in terms of divMod? In-Reply-To: <1186860297.6796.80.camel@derek-laptop> References: <1186860297.6796.80.camel@derek-laptop> Message-ID: On Sat, 11 Aug 2007, Derek Elkins wrote: > On Sat, 2007-08-11 at 21:10 +0200, Henning Thielemann wrote: > > Btw. is there any application, where 'quot' and 'rem' are needed? All > > occurrences of 'quot' and 'rem' I found in code so far were actually wrong > > and should have been 'div' and 'mod'. > > > > http://www.haskell.org/haskellwiki/Things_to_avoid#Forget_about_quot_and_rem > > quotRem is faster than divMod, Seems that CPU design should be changed. > and my understanding is that even divMod is arguably broken. In what way? I can't deduce it from your reference. Quote: "Boute argues that Euclidean division is superior to the other ones in terms of regularity and useful mathematical properties, although floored division, promoted by Knuth, is also a good definition. Despite its widespread use, truncated division is shown to be inferior to the other definitions." > http://www.cs.uu.nl/~daan/download/papers/divmodnote-letter.pdf Thanks for the reference! From gregorypropf at yahoo.com Sun Aug 12 01:32:04 2007 From: gregorypropf at yahoo.com (Gregory Propf) Date: Sun Aug 12 01:23:50 2007 Subject: Fw: [Haskell-cafe] IO within parser Message-ID: <725763.68337.qm@web31404.mail.mud.yahoo.com> Well the docs ( http://legacy.cs.uu.nl/daan/download/parsec/parsec.html ) hint that setInput and getInput are good for this. I can certainly how they *would* be - if I knew how to pull in files within the parse. Actually I use those functions to do multiple recursive passes but of course you already have the output from the first pass in the parser there. runParser only *looks* like it takes input from a file. Actually it just parses the string you give it and uses the filename arg for error messages only. You still need a way to pull the data into the string from the file. (Note: I accidentally sent this to Andrew instead of the list originally) ----- Original Message ---- From: Andrew Coppin To: haskell-cafe@haskell.org Sent: Saturday, August 11, 2007 1:25:16 PM Subject: Re: [Haskell-cafe] IO within parser Gregory Propf wrote: > I've been struggling with writing a parser that needs to parse include > files within source files. So far I cannot get this to work (in > reality to get work done I wrote a kludge that returns a list of > include filenames to be run later in a pure IO function. I realized > that this just amounted to creating my own half-assed monad system so > I really don't want to use this approach). I have read the tutorials > I could find on monad transformers but I still don't see what's going > on. I'm using the Parsec parser library. Here's an simple example of > what I've tried. I also tried using liftIO and got a message about > needing to add an instance of MonadIO. This made more sense but the > type of liftIO is baffling The fun part is that Parsec already has a feature for include files... (I can't remember where the heck it is or how you use it though.) _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. ____________________________________________________________________________________ Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070811/b429257d/attachment.htm From ronguida at mindspring.com Sun Aug 12 02:22:11 2007 From: ronguida at mindspring.com (Ronald Guida) Date: Sun Aug 12 02:11:57 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <20070811191716.GA3460@localhost.localdomain> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> <46BE0734.3040308@mindspring.com> <20070811191716.GA3460@localhost.localdomain> Message-ID: <46BEA713.8030201@mindspring.com> Stefan O'Rear wrote: > On Sat, Aug 11, 2007 at 03:00:04PM -0400, Ronald Guida wrote: >> The question remains: "What is special about Monad or ArrowApply, >> compared to Arrow?" or "What is more general about Arrow, compared >> to Monad or ArrowApply?" > > If all you have is an Arrow, then you must make up your mind what > you're going to do ahead of time. > > ArrowChoice gives you the ability to make basic "yes or no" > decisions at run time. > > ArrowApply gives you arbitrary computed jumps. OK, so I thought this through. To summarize the classes of arrows: 1. Arrow is a device for sequencing side-effects in a fixed order. > If all you have is an Arrow, then you must make up your mind what > you're going to do ahead of time. 2. ArrowChoice is a device for sequencing side-effects in a fixed order with options. Some effects can be selected at run-time, but (1) the available choices are fixed at compile-time and (2) options have to be selected before running the arrow computation. > ArrowChoice gives you the ability to make basic "yes or no" > decisions at run time. BUT, you have to make these decisions before you run the arrow computation. 3. ArrowApply is a device for sequencing side-effects, such that functions can dynamically choose side-effects at run-time based on intermediate results of arrow computations. > ArrowApply gives you arbitrary computed jumps. --- We know that ArrowApply is equivalent to Monad. > Imagine trying to write an interpreter for a toy language with I/O, > and IO is a plain Arrow and not a Monad. You can read input and > parse it, but you can't actually do IO because the IO you need to > do, depends on the input you read - precisely what Arrow forbids! Here's a toy language, described by a regular expression: 0(10)*110 I want to read characters, one at a time, and eventually decide to "Accept" or "Reject" a string. Let me try to understand my options. * With a simple Arrow, I can create a fixed sequence of "read" operations, and I can't act on the results (i.e. by choosing whether or not to keep reading) at run-time. * With ArrowChoice, I can create a set of alternative paths for "read" operations, and I can choose a path at run-time, but I have to choose a fixed path /before/ I get to see any results. * With ArrowApply, I can "read" one character and act on that character to choose what actions to perform next. I can read characters until I can render an "Accept" or "Reject" decision. Clearly, I need ArrowApply (or Monad) to get the job done. In conclusion: "What is special about Monad or ArrowApply, compared to Arrow?" Arrow lets me sequence side-effects in a fixed order. Monad lets me dynamically choose side effects at run-time based on intermediate results of previous side-effects. -- Ron From bulat.ziganshin at gmail.com Sun Aug 12 02:33:00 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Sun Aug 12 02:25:26 2007 Subject: Fw: [Haskell-cafe] IO within parser In-Reply-To: <725763.68337.qm@web31404.mail.mud.yahoo.com> References: <725763.68337.qm@web31404.mail.mud.yahoo.com> Message-ID: <1991698420.20070812103300@gmail.com> Hello Gregory, Sunday, August 12, 2007, 9:32:04 AM, you wrote: >> I've been struggling with writing a parser that needs to parse include >> files within source files.?? Parsec can't accomplish with without using unsafePerformIO because it's monad is pure. it's algorithmically impossible to have any i/o actions inside it. there was plans to rewrite Parsec in monad-transformer way and afair it was even one of GSOC projects -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From malte at gmx-topmail.de Sun Aug 12 03:09:26 2007 From: malte at gmx-topmail.de (Malte Milatz) Date: Sun Aug 12 02:58:09 2007 Subject: [Haskell-cafe] IO within parser In-Reply-To: <672187.69183.qm@web31409.mail.mud.yahoo.com> References: <672187.69183.qm@web31409.mail.mud.yahoo.com> Message-ID: <20070812090926.30ad56f0@aligatoro.ret> Gregory Propf, Sat, 11 Aug 2007 13:06:43 -0700: > but the type of liftIO is baffling > > class Monad m => MonadIO m where > liftIO :: IO a -> m a > > But how do you define this function? There is no constructor for "IO a" that you can "take apart". If not using unsafePerformIO, which is usually not what we want, the monad m in question must incorporate IO. That is, it could be defined something like (say we want a parser with state): newtype IOParser tok s a = IOParser (s -> [tok] -> IO (s,a)) You can then define liftIO without ?taking apart? the IO value; instead you put liftIO's IO action (IO a) into IOParser's IO action (IO (s,a)). Parsec does not define any such parser, though, so there's nothing for which you may define an instance of MonadIO. Malte From gregorypropf at yahoo.com Sun Aug 12 03:10:44 2007 From: gregorypropf at yahoo.com (Gregory Propf) Date: Sun Aug 12 03:02:30 2007 Subject: Fw: [Haskell-cafe] IO within parser Message-ID: <219332.11492.qm@web31412.mail.mud.yahoo.com> I noticed that StateT can enclose IO actions for instance. So you are saying the whole Parsec library would need to be rewritten as something like a ParsecT transformer monad for this to work? If this is the case I suppose I will stick with returning my list of include files. - Greg ----- Original Message ---- From: Bulat Ziganshin To: Gregory Propf Cc: haskell-cafe@haskell.org Sent: Saturday, August 11, 2007 11:33:00 PM Subject: Re: Fw: [Haskell-cafe] IO within parser Hello Gregory, Sunday, August 12, 2007, 9:32:04 AM, you wrote: >> I've been struggling with writing a parser that needs to parse include >> files within source files. Parsec can't accomplish with without using unsafePerformIO because it's monad is pure. it's algorithmically impossible to have any i/o actions inside it. there was plans to rewrite Parsec in monad-transformer way and afair it was even one of GSOC projects -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com ____________________________________________________________________________________ Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070812/f80dd612/attachment.htm From tomasz.zielonka at gmail.com Sun Aug 12 04:02:07 2007 From: tomasz.zielonka at gmail.com (Tomasz Zielonka) Date: Sun Aug 12 03:53:57 2007 Subject: [Haskell-cafe] zip3, zip4 ... -> zipn? In-Reply-To: <0e3d01c7dbed$59676970$64c5a8c0@galilei> References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> Message-ID: <20070812080207.GB23188@lambda> On Sat, Aug 11, 2007 at 09:58:05AM +0200, Frank Buss wrote: > Is it possible to write a function like this: > > zipn n list_1 list_2 list_3 ... list_n > > which implements zip3 for n=3, zip4 for n=4 etc.? Looks like variable number > of arguments are possible, like printf shows, so a general zipn should be > possible, too. If it is possible, why there are functions like zip5 and not > just zipn? I prefer to do n-ary zips this way: zipApply = zipWith ($) x = repeat (,,) `zipApply` [1,2,3] `zipApply` ["a", "bc", "de"] `zipApply` [1.0, 1.2..] Best regards Tomek From rendel at rbg.informatik.tu-darmstadt.de Sun Aug 12 05:54:05 2007 From: rendel at rbg.informatik.tu-darmstadt.de (Tillmann Rendel) Date: Sun Aug 12 05:45:58 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46BEA713.8030201@mindspring.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> <46BE0734.3040308@mindspring.com> <20070811191716.GA3460@localhost.localdomain> <46BEA713.8030201@mindspring.com> Message-ID: <46BED8BD.2030707@rbg.informatik.tu-darmstadt.de> Ronald Guida wrote: > Here's a toy language, described by a regular expression: > 0(10)*110 > > I want to read characters, one at a time, and eventually decide to > "Accept" or "Reject" a string. > > Let me try to understand my options. > > * With a simple Arrow, I can create a fixed sequence of "read" > operations, and I can't act on the results (i.e. by choosing > whether or not to keep reading) at run-time. Nothing stops your Arrow-based RegExp-library from defining suitable combinators to implement choices in RegExp's without using ArrowChoice or ArrowApply. But if your Arrow-type is abstract, the users of your library can only use the combinators you provided, so you can safely assume they do only RegExp parsing, and optimize your Arrows in the runRegExp-function for the special case of RegExp-matching. But if you decide to expose ArrowApply-functionality to the users of your RegExp-library, they are able to define arbitrary string matching on top of your RegExp library, so you can't do any optimizations because you never know what your users decided to do. From a software engineering point of view, the idea of Arrow-and-only-Arrow is to encode the whole computation in the internal structure of the arrow, independent of the interpreting language Haskell. This internal structure could be as expressible as Haskell. In contrast, ArrowApply and Monad use regular Haskell expressions for everything Haskell can do (like if-then-else, recursion, ...) and only encode special operations into the internal structure (like access to state, nondeterminism, ...). This distinction is reflected in the treatment of variables in arrow-based vs. monadic code. monadic code can use normal Haskell variables, arrow-based code has to keep the variables "inside" the arrow in some structure. Tillmann From ctm at cs.nott.ac.uk Sun Aug 12 06:31:42 2007 From: ctm at cs.nott.ac.uk (Conor McBride) Date: Sun Aug 12 06:23:32 2007 Subject: [Haskell-cafe] varsum, was zip3, zip4 ... -> zipn? In-Reply-To: <20070812032543.GA10207@localhost.localdomain> References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> <837db430708110227j6e401e78n783f228388e7e05a@mail.gmail.com> <20070811192405.GB3460@localhost.localdomain> <200708121256.32439.dry.green.tea@gmail.com> <20070812032543.GA10207@localhost.localdomain> Message-ID: <0B5093DA-17E6-469A-A546-5336878BEBF5@cs.nott.ac.uk> Hi Stefan I'd have my membership of the one-leg club taken away if I didn't write in and say that,... On 12 Aug 2007, at 04:25, Stefan O'Rear wrote: > On Sun, Aug 12, 2007 at 12:56:31PM +1000, Alexis Hazell wrote: >> On Sunday 12 August 2007 05:24, Stefan O'Rear wrote: >> >>> Currying makes it MUCH harder to implement varargs functions. ...while I wouldn't disagree,... >>> >> >> That's interesting - why is that the case? > > varsum 2 3 -- varsum receives 2, and returns a function, which when > -- passed 3, returns 5 > varsum 2 3 4 -- varsum receives 2, and returns a function, which when > -- passed 3, returns a function that when passed 4 > returns > -- 9. ...this is one of the more elementary exercises in overloading... > > Because of this, the number of arguments must somehow be passed > out-of-band; ...the type... > but then the type of the whole function (usually) must > depend on the control parameter, requiring dependent types. ...of dependent walk you can mimic by hopping in Haskell. > module VarSum where > class VarSum t where > varacc :: Int -> t > varsum :: VarSum t => t > varsum = varacc 0 > type Z = Int > type S = (->) Int > instance VarSum Z where > varacc a = a > instance VarSum t => VarSum (S t) where > varacc a b = varacc (a + b) Of course, you have to say stuff like varsum (2 :: Int) (3 :: Int) :: Int to determine the type at which the overloading happens. Or perhaps (varsum :: S (S Z)) 2 3 But there am I, proving your point. In Haskell, this sort of thing is a stunt. I'd much rather it was boring. All the best Conor From lemming at henning-thielemann.de Sun Aug 12 08:01:24 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sun Aug 12 07:53:12 2007 Subject: [Haskell-cafe] Re: default for quotRem in terms of divMod? In-Reply-To: References: <1186860297.6796.80.camel@derek-laptop> Message-ID: On Sun, 12 Aug 2007, Lennart Augustsson wrote: > CPU design cannot be changed, because they implement well defined ISA. What is ISA? Why is it not possible to add CPU functions for `div` and `mod`? > The only processor I know of (NS 32k) with a different division is long > dead. If efficiency on current CPUs is the only advantage of `quot` and `rem`, then for future versions of Haskell I propose to fix these functions to the type Int rather than making them class methods. For non-machine types like Integer the efficiency argument does certainly not hold. From isaacdupree at charter.net Sun Aug 12 08:20:27 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Sun Aug 12 08:23:22 2007 Subject: [Haskell-cafe] Re: default for quotRem in terms of divMod? In-Reply-To: References: <1186860297.6796.80.camel@derek-laptop> Message-ID: <46BEFB0B.4000307@charter.net> Henning Thielemann wrote: > On Sun, 12 Aug 2007, Lennart Augustsson wrote: > >> CPU design cannot be changed, because they implement well defined ISA. > > What is ISA? Why is it not possible to add CPU functions for `div` and > `mod`? "Instruction set architecture" - it would take a concerted industry effort to add these to new machines (and new machines only, obviously), maybe. Then compilers would have to support the new instructions. Probably it would not help efficiency much, anyway (div and mod are rather fast too, Haskell is generally slower with current compilers, algorithms can often be defined in a way that uses only nonnegative numbers...). > If efficiency on current CPUs is the only advantage of `quot` and `rem`, > then for future versions of Haskell I propose to fix these functions to > the type Int rather than making them class methods. For non-machine types > like Integer the efficiency argument does certainly not hold. It is not. *Sometimes I want to round towards zero*. Aside from my Haskell-implemented Integer type, which as well as using quotRem also provides a quotRem that is a little faster than divMod (I have no idea what GMP's speeds are like)... I believe I have used quotRem to round a difference (a directed distance vector, in a discrete space) towards zero, while preserving its sign. And I was using Integer, not Int, for correctness. I think quotRem deserves to stay usable on Integrals, and also it would break too many things to remove it from the class (it may be something to consider for Prelude redesigns though, along with the rest of the numeric hierarchy!). Isaac From mailing_list at istitutocolli.org Sun Aug 12 09:04:38 2007 From: mailing_list at istitutocolli.org (Andrea Rossato) Date: Sun Aug 12 09:09:02 2007 Subject: [Haskell-cafe] Help with a project design Message-ID: <20070812130438.GB11356@laptop.nowhere.net> Hi, I'm going to be long, sorry for it. And probably also off topic, a bit at least...;-) I need a way to manage bibliographies, pretty common problem isn't it? I used to use a wiki I developed also for such a task.[1] The wiki was basically based on Bibtex. I thought I could rewrite that bibliographic management system in Haskell, but I've been also following the work of some guys who are trying to develop a style citation language in XML.[2] Since my confidence with Haskell is growing, I though I could try to write an implementation of that Citation Style Language, but now I start hitting my basic lack of computer science education. Such an effort would be useful if I could write a library and release it, which requires a clean architecture and a simple exported API. But, while I can grasp difficult computational concepts like monads or arrows, choosing a given path of development and create that API is probably out of my reach. This is why I'm asking for help. Or, probably better, for directions on how to start acquiring such capacities. The task this library should do is simple: given an xml object (representing a bibliographic reference), render it with rules stored in a different xml object (the citation style). While I think I can find solutions for this problem - the rendering -, what I find difficult is the design of the reference xml objects. Bibliographic entries have different types, which must be rendered differently. These types can be classified into 3 main classes (books, articles, parts of a book) that can be rendered with the same methods. That seems to fit Haskell perfectly. Now, I basically see 2 approaches: 1. create some data structures (most part of them is common) to map different types of bibliographic entries, and create the needed classes with the render methods; 2. keep the xml objects as xml and create an abstract interface to the xml objects to get the data required for rendering and classifying the xml objects. This way I would have to: - create data types to store different types of xml objects (data Book = Book XmlTree, data Artilce, etc.): these data types represent my reference classes; - create a class of 'render'-able types with the render method and define the instances; - create an existential type to set the type of the xml objects with some kind of setType :: XmlTree -> ExistentialContainer I think that the first approach is not abstract enough and requires a lot of boilerplate code to translate into a Haskell type a specific type of bibliographic entry. Moreover, this brings me back to Bibtex, that maps each entry type to a set of rendering rules, while xml objects (MODS[3]) have no type (type must be deduced by the presence of given elements). The second one is the one I'm leaning to. But I'm also thinking that probably I should first study a bit the "scrap your boilerplate" approach ... on the other side I think that I should probably take a path, follow it and see what happens. In other words, I keep on testing the feasibility of different approaches, probably because I did not grasp the problem entirely. And then there is the API, function names, argument disposition, and so on. Is there some material I could read to have some guidelines for such a task? I know that this is some kind of meta question that is not really Haskell specific, even though I would like to have Haskell specific answers...;-) But any kind of suggestion will be appreciated, especially if you can give me directions to materials that, even if not directly connected with my specific problem, can help me in understanding the basic principle of functional programming design. Thanks for your kind attention and sorry for such a long message. Andrea [1] http://uniwakka.sf.net [2] xbiblio.sf.net [3] "Metadata Object Description Schema" (MODS) http://www.loc.gov/standards/mods/ From lgreg.meredith at biosimilarity.com Sun Aug 12 09:49:42 2007 From: lgreg.meredith at biosimilarity.com (Greg Meredith) Date: Sun Aug 12 09:41:27 2007 Subject: [Haskell-cafe] Re: towards a new foundation for set theory with atoms In-Reply-To: <20070812051009.GA14652@regurgitate.ugcs.caltech.edu> References: <5de3f5ca0708101218j56a7b84fj50acef000dfb8433@mail.gmail.com> <5de3f5ca0708101554w471314c4ydd272d71081ca4e8@mail.gmail.com> <20070812051009.GA14652@regurgitate.ugcs.caltech.edu> Message-ID: <5de3f5ca0708120649y5bbd6752tca77dffdd9c113a6@mail.gmail.com> Brandon, Cool. Well spotted. i was thinking a lot about the symmetry in the type space as a kind of group. i'll play around with your suggestion. Best wishes, --greg On 8/11/07, Brandon Michael Moore wrote: > > On Fri, Aug 10, 2007 at 03:54:23PM -0700, Greg Meredith wrote: > > Haskellians, > > > > A quick follow up. If you look at the code that i have written there is > a > > great deal of repeated structure. Each of these different kinds of sets > and > > atoms are isomorphic copies of each other. Because, however, of the > > alternation discipline, i could see no way to abstract the structure and > > simplify the code. Perhaps someone better versed in the Haskellian > mysteries > > could enlighten me. > > You could take a less absolute view of the game, and describe each node > instead locally from the perspective of a player. Imagine Alice Bob and > Carol sitting around a table: > > data ThreePlayers a b c = > Next (ThreePlayer b c a) > | Prev (ThreePlayers c a b) > > In general you can get subgroups of a symmetric group as your sets of > colors this way (i.e, the set of elements of any group), I'm not quite > sure how much freedom you have in the sets of allowed transitions > (in particular, making some of the argument types identical can break > symmetry). > > You could also go for the obvious big hammer, pretend that Haskell has > a strongly normalizing subset and encode inequality explicitly with > GADTs and such. > > date Eq a b where Refl a a > data False > type Neq a b = Eq a b -> False > -- might be trouble if a and b are only equal non-constructively? > > data Red = Red > data Green = Green > .... > > data Set color where > Red :: Neq Red color -> Set Red -> Set color > ... > > Brandon > -- L.G. Meredith Managing Partner Biosimilarity LLC 505 N 72nd St Seattle, WA 98103 +1 206.650.3740 http://biosimilarity.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070812/c1523710/attachment.htm From ronguida at mindspring.com Sun Aug 12 11:36:18 2007 From: ronguida at mindspring.com (Ronald Guida) Date: Sun Aug 12 11:26:02 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46BED8BD.2030707@rbg.informatik.tu-darmstadt.de> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> <46BE0734.3040308@mindspring.com> <20070811191716.GA3460@localhost.localdomain> <46BEA713.8030201@mindspring.com> <46BED8BD.2030707@rbg.informatik.tu-darmstadt.de> Message-ID: <46BF28F2.1070101@mindspring.com> Tillmann Rendel wrote: > Ronald Guida wrote: >> Here's a toy language, described by a regular expression: >> 0(10)*110 >> >> I want to read characters, one at a time, and eventually decide to >> "Accept" or "Reject" a string. >> >> Let me try to understand my options. >> >> * With a simple Arrow, I can create a fixed sequence of "read" >> operations, and I can't act on the results (i.e. by choosing >> whether or not to keep reading) at run-time. > > Nothing stops your Arrow-based RegExp-library from defining suitable > combinators to implement choices in RegExp's without using > ArrowChoice or ArrowApply. But if your Arrow-type is abstract, the > users of your library can only use the combinators you provided, so > you can safely assume they do only RegExp parsing, and optimize your > Arrows in the runRegExp-function for the special case of > RegExp-matching. So it seems I was thinking too narrowly of arrows... If I think of an arrow as defining a Domain Specific Embedded Language (DSEL), then with a plain arrow, users can't embed Haskel inside the DSEL. > But if you decide to expose ArrowApply-functionality to the users of > your RegExp-library, they are able to define arbitrary string > matching on top of your RegExp library, so you can't do any > optimizations because you never know what your users decided to do. If I think of a monad (ArrowApply) as defining a Domain Specific Embedded Language (DSEL), then users can embed anything they want within the DSEL. > From a software engineering point of view, the idea of > Arrow-and-only-Arrow is to encode the whole computation in the > internal structure of the arrow, independent of the interpreting > language Haskell. This internal structure could be as expressible as > Haskell. In contrast, ArrowApply and Monad use regular Haskell > expressions for everything Haskell can do (like if-then-else, > recursion, ...) and only encode special operations into the internal > structure (like access to state, nondeterminism, ...). > > This distinction is reflected in the treatment of variables in > arrow-based vs. monadic code. monadic code can use normal Haskell > variables, arrow-based code has to keep the variables "inside" the > arrow in some structure. So if I want to explain arrows and monads as concisely as possible: Arrows and monads are abstract data types used to construct Domain Specific Embedded Languages (DSELs) within Haskel. A simple arrow provides a closed DSEL. A monad is a special type of arrow that creates an open DSEL by allowing users to embed arbitrary Haskel within it. -- Ron From igloo at earth.li Sun Aug 12 13:07:32 2007 From: igloo at earth.li (Ian Lynagh) Date: Sun Aug 12 12:59:16 2007 Subject: [Haskell-cafe] howto install ghc-6.7.* ? In-Reply-To: <200708111144.23249.coeus@gmx.de> References: <200708111144.23249.coeus@gmx.de> Message-ID: <20070812170732.GA17515@matrix.chaos.earth.li> On Sat, Aug 11, 2007 at 11:44:17AM +0200, Marc A. Ziegert wrote: > > those extralibs seem to be installed in > /usr/local/lib/ghc-6.7.20070810/lib/ > but registered in > ghc-6.7.20070810/driver/package.conf.inplace > instead of > /usr/local/lib/ghc-6.7.20070810/package.conf Now fixed, thanks. By the way questions about the HEAD are generally best sent to the cvs-ghc@haskell.org list. Thanks Ian From brianh at metamilk.com Sun Aug 12 14:05:12 2007 From: brianh at metamilk.com (Brian Hulley) Date: Sun Aug 12 13:56:39 2007 Subject: [Haskell-cafe] Re: Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> Message-ID: <46BF4BD8.9080809@metamilk.com> apfelmus wrote: > Brian Hulley schrieb: >> main = do >> buffer <- createBuffer >> edit1 <- createEdit buffer >> edit2 <- createEdit buffer >> splitter <- createSplitter (wrapWidget edit1) (wrapWidget >> edit2) >> runMessageLoopWith splitter >> >> ... Thus the ability to abstract mutable state gives to my mind by >> far the best solution. > > I'm not sure whether mutable state is the real goodie here. I think > it's the ability to indpendently access parts of a compound state. In > other words, the IORef created by buffer is a part of the total > program state but you can access it independently. There is a > functional idiom for that, see also > > Sander Evers, Peter Achten, and Jan Kuper. "A Functional Programming > Technique for Forms in Graphical User Interfaces". > http://www.st.cs.ru.nl/papers/2005/eves2005-FFormsIFL04.pdf Thanks for this reference. This is indeed a real key to the problem. (Though a possible downside with compositional references might be efficiency as the modified sub-state needs to be injected back into a new composite state but perhaps the solution here would be to have uniqueness typing as in Clean so that these injections could hopefully be erased at compile time.) I think one of the issues with Haskell is that there are so many features to choose from it is difficult to know how to approach a problem eg for streams you can have 1) A lazy list 2) A typeclass with get and pushBack methods 3) An object using an existential to wrap (2) 4) A record containing get and pushBack methods 5) A monad with get and pushBack actions 6) A simple function wrapped in a newtype: newtype Stream a = Stream (() -> Maybe (a, Stream a)) and I tend to only discover a simple solution like (6) (which works equally well for both strict and lazy languages) after spending an enormous amount of time on 1,2,3,4,5... ;-) > - For Graphics, I want to build a graphic from smaller ones and then > draw it. I don't want to know how drawing is implemented and what > mutable state might be involved. > - For a GUI, I want to write down the data dependencies and a library > converts this to a mesh of mutable state. > > That's what I mean with "higher level functional model". I agree this would be ideal. A challenge I don't yet know how to solve, when dealing with 3d graphics, is that it seems that for efficiency it is necessary to consider a mesh of triangles to be an object with identity in order to be able to display an updated mesh (eg as the user drags a vertex with the mouse) in real time. This is because the representation of a mesh is constrained by the low level details of the graphics system eg vertices might need to be represented by a contiguous array of unboxed positions and normals, and triangles by a contiguous array of vertex indices, and it is too expensive to copy these arrays on each frame. Perhaps though this is another case where some form of uniqueness typing as in Clean could come to the rescue so one could write: createMesh :: [Vertex] -> [[VertIndex]] -> Mesh moveVertex :: Vertex -> *Mesh -> *Mesh instead of createMesh :: [Vertex] -> [[VertIndex]] -> IO Mesh moveVertex :: Vertex -> Mesh -> IO () Best regards, Brian. From igloo at earth.li Sun Aug 12 14:20:59 2007 From: igloo at earth.li (Ian Lynagh) Date: Sun Aug 12 14:12:48 2007 Subject: [Haskell-cafe] Infinity v0.1 In-Reply-To: References: Message-ID: <20070812182059.GB17515@matrix.chaos.earth.li> Hi Austin, On Sat, Aug 11, 2007 at 11:13:38PM -0500, Austin Seipp wrote: > > (there is no darcs repo yet, although I have emailed someone about a > possible account for darcs.haskell.org.) http://community.haskell.org/admin/ is probably a better fit. Thanks Ian From a.biurvOir4 at asuhan.com Sun Aug 12 15:43:49 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Sun Aug 12 15:35:32 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> Message-ID: <12117211.post@talk.nabble.com> David Menendez wrote: > > This is probably because no one has found a compelling use case for > comonadic-style programming in Haskell. There have been some > interesting papers, such as "Comonadic functional attribute > evaluation" by Uustalu and Vene, but nothing as compelling as Wadler's > "Monads for functional programming". > That same "Comonadic" paper describes how every zipper is a comonad. I bet if we found more examples of zippers, comonads would be in business. Much as I respect Huet 1997, more zipper tutorials wouldn't harm either. -- View this message in context: http://www.nabble.com/Explaining-monads-tf4244948.html#a12117211 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From isaacdupree at charter.net Sun Aug 12 15:49:45 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Sun Aug 12 15:52:49 2007 Subject: [Haskell-cafe] Re: Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> Message-ID: <46BF6459.6010709@charter.net> apfelmus wrote: > (3+) :: Int -> Int > ([1,2]++) :: [Int] -> [Int] > insert "x" 3 :: Map String Int -> Map String Int > > Of course, from the purely functional point of view, this is hardly > perceived as mutation since the original value is not changed at all and > still available. In other words, the need to "change" a value doesn't > imply the need to discard (and thus mutate) the old one. Yes, and pure functions in Haskell often get funny imperative-sounding names like "insert" because of it - which is quite nice IMO. I like perceiving it like mutation because 99% of the time these are used in the places that mutation normally needs to be used in imperative languages. It is only occasionally that destructive mutation (for lack of a better name) is needed - for all I know, those situations may be a named "pattern" or something in imperative languages. type Mutate a = a -> a --I've also caught myself calling it Mon, Endo, IdF, Change ... insert :: (Ord k) => k -> v -> Mutate (Map k v) It's annoying when the arguments are in the wrong order, such as Data.Bits.shift. (perhaps for the flimsy excuse that they expected you to use it infix...) > Mutable data structures in the sense of ephemeral (= not persistent = > update in-place) data structure indeed do introduce the need to work in > ST since the old version is - by definition - not available anymore. Not in the quantum/information-theoretic sense, not necessarily. Consider import Control.Monad.ST import Data.STRef main = print (runST (do r <- newSTRef 1 notUnavailable <- readSTRef r writeSTRef r 5 return notUnavailable )) Of course that's something you can do in imperative languages too, but it's still easier in Haskell where you don't have to worry about what something implicitly refers to, and can pass around anything (any data, functions, IO-actions) as first-class citizens :) (including storing them in parametrically-polymorphic state-refs like STRef, and, even for non-polymorphic refs, you can get the value out and keep it after the mutatable state has changed) See, the imperative paradigm has trouble scaling down to the quantum level, where information cannot be copied at will, too! This proves why computers generate heat(entropy) from the unprincipled destruction of information. Of course, computation near the quantum scale is a subject that has not nearly been thoroughly explored yet, but I suspect that (purely) functional languages are a little more likely to be easier to compile to such a type of machine, some decades from now... Playfully, Isaac From jon at ffconsultancy.com Sun Aug 12 18:09:12 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Sun Aug 12 19:16:12 2007 Subject: [Haskell-cafe] Suffix tree Message-ID: <200708122309.13110.jon@ffconsultancy.com> Suffix trees are a data structure used to search for a substring of length "m" in a string of length "n" in O(m) time. Suffix trees can also be used for efficient approximate searches. This data structure is of particular importance in bioinformatics. Does anyone have any Haskell code implementing suffix trees? I'm particularly interested in high-performance construction. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/?e From hughes at rpi.edu Sun Aug 12 20:12:55 2007 From: hughes at rpi.edu (Sam Hughes) Date: Sun Aug 12 20:04:39 2007 Subject: [Haskell-cafe] IO within parser In-Reply-To: <20070812090926.30ad56f0@aligatoro.ret> References: <672187.69183.qm@web31409.mail.mud.yahoo.com> <20070812090926.30ad56f0@aligatoro.ret> Message-ID: <46BFA207.3050806@rpi.edu> Malte Milatz wrote: > If not using unsafePerformIO, which is usually not what we want, the > monad m in question must incorporate IO. That is, it could be defined > something like (say we want a parser with state): > > newtype IOParser tok s a > = IOParser (s -> [tok] -> IO (s,a)) > > You can then define liftIO without ?taking apart? the IO value; > instead you put liftIO's IO action (IO a) into IOParser's IO action > (IO (s,a)). Parsec does not define any such parser, though, so > there's nothing for which you may define an instance of MonadIO. > > Malte I'm making (or have "made") such a thing, although not necessarily atop IO, atop any monad that provides certain stream-like functionality. It's kind of done, but not really. $ darcs get http://samuelhughes.com/darcs/partran/ That is virtually completely untested and has not been proven correct either. Also, whatever documentation there is has probably accidentally been copied and pasted from Parsec's (except for the documentation of Stream.hs). Some of the unthinkingly done translations of the files found in Parsec's hierarchy seem to be idiomatically immoral. (Token.hs comes to mind. Something went wrong with functional dependencies and avoiding things like breaking the coverage condition/undecidable instances and it hurts. Maybe somebody could tell me what I'm doing wrong.) Also, some functions and definitions of things might be appropriately moved around, and you'll probably end up having to import more than you'd like to. "Text.ParserCombinators.ParTran.Parsec" /might/ currently contain a correct simulation of "Text.ParserCombinators.Parsec". - Sam From ketil at ii.uib.no Mon Aug 13 04:15:21 2007 From: ketil at ii.uib.no (Ketil Malde) Date: Mon Aug 13 04:20:25 2007 Subject: [Haskell-cafe] Suffix tree In-Reply-To: <200708122309.13110.jon@ffconsultancy.com> References: <200708122309.13110.jon@ffconsultancy.com> Message-ID: <1186992921.4442.192.camel@nmd9999> On Sun, 2007-08-12 at 23:09 +0100, Jon Harrop wrote: > Suffix trees are a data structure used to search for a substring of length "m" > in a string of length "n" in O(m) time. Suffix trees can also be used for > efficient approximate searches. This data structure is of particular > importance in bioinformatics. Suffix trees (and their sibling, suffix arrays) are cool. Basically a suffix tree is a trie, but where any nodes with only one child are collapsed. Easy to construct through sorting, linear time is trickier, and perhaps the biggest problem is keeping memory use reasonable. Suffix arrays is a sorted array of indices, so it's more compact, but takes O(m log n) to search. There's also the enhanced suffix array, which provides the same functionality as the suffix tree, but uses approximately the same space as well (something like 12n bytes vs 5n bytes, IIRC). > Does anyone have any Haskell code implementing suffix trees? I'm particularly > interested in high-performance construction. I was using a suffix tree to index some data, but I discovered I only needed the tree to constant depth, so - shame on me - I ended up simply sorting the suffixes in one case, and storing hashed words in a Map in another. I've also toyed with FFI'ing to comressed suffix arrays, but in the end, this wasn't as successful as I'd hoped. For straightforward suffix array construction, this is probably the fastest way to go about it, though. Linear time suffix trees are a bit complicated to implement in a functional language, as they depend on additional links in the tree during construction. I'm sure this can be done using IO/STrefs, but it would of course be cooler if it could be done tying-the-knot style. Anyway, I have a handful of shaky FFI bindings, a reasonable bibtex file, and lots of good will and encouragement. Let me know if you have use for any of them! -k From ajb at spamcop.net Mon Aug 13 07:21:56 2007 From: ajb at spamcop.net (ajb@spamcop.net) Date: Mon Aug 13 07:13:38 2007 Subject: [Haskell-cafe] Suffix tree In-Reply-To: <200708122309.13110.jon@ffconsultancy.com> References: <200708122309.13110.jon@ffconsultancy.com> Message-ID: <20070813072156.ufh7s4s4gw4w4w4k@webmail.spamcop.net> G'day all. Quoting Jon Harrop : > Does anyone have any Haskell code implementing suffix trees? I'm particularly > interested in high-performance construction. No, but I have this: http://citeseer.ist.psu.edu/giegerich95comparison.html First person to implement them gets the eternal gratitude of hackage. Cheers, Andrew Bromage From brian at ithil.org Mon Aug 13 07:31:14 2007 From: brian at ithil.org (Brian Brunswick) Date: Mon Aug 13 07:22:56 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46BD2E4B.3010202@mindspring.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> Message-ID: <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> On 11/08/07, Ronald Guida wrote: > > > Here's my interpretation of the table: > > ---------------------------------------------------------------------- > Structure | Subject | Action | Verb | Result > ------------+----------+------------+------------+---------- > function | a | a->b | flip ($) | b > Functor | f a | a->b | <$> | f b > Applicative | f a | f (a->b) | flip <*> | f b > Monad | m a | a->m b | >>= | m b > Comonad | w a | w a->b | =>> | w b > Arrow | a b c | a c d | >>> | a b d > ---------------------------------------------------------------------- Nice Kim-Ee Yeoh wrote: > > ... I think you'll find that each of those structures have their > > privileged place in your code. > > Agreed. I'm still a beginner; I'm not sure how to choose one > structure over another, at least not yet. But that's because ... > > > Monads are undoubtedly more pervasive, and that could be because there > > aren't as many arrow and comonad tutorials, atomic ones or otherwise. And I'm trying to say that these shouldn't be separate tutorials at all - its much more instructive to compare and contrast. Moreover, Comonad isn't even in the standard libraries (Hoogle returns > no results for it). > > When I searched for tutorials on monads, I found lots of them. In > fact, I have heard that writing (yet another) monad tutorial is part > of standard Haskell initiation. Thats what I was doing above :-) .... One thing that I keep seeing people say (not you), is that monads /sequence/ side effects. This is wrong, or at least a limited picture. /All/ of the above structures are about combining compatible things things together in a row. /None/ of them force any particular order of evaluation - that all comes from the particular instance. So its only a particular feature of IO that it sequences the side effects. Others don't - we can have a lazy State monad that just builds up big thunks. IO could be implemented as any of the above structures, and still be perfectly able to keep things in order. Indeed, uniqueness types as in clean, are arguably just the first one - function composition functor IO would be really boring - we could just perform a sequence of actions with no choices at all. (But the whole sequence could be repeated, and I guess the Structure could be nested for fixed loops) The key to the choice of IO as a Monad comes back the the argument about 'simplicity' or what ever we want to call it - I agree its rather context dependent, and indeed I was rather flippant at the end of my first message But lets look at the nature of the actual things being sequenced, the actions above. In only 3 cases are the actions simple enough to take a single /a/ argument. Function a->b; Functor a->b; Monad a->m b In function and functor, the action takes no part in the complexity, doesn't know about it. In function application the action gets used (possibly) once, in functor and monad possibly many times. Only in Monad does the action have a say in the complexity, by returning an possibly non-trivial m b. So thats the reason Monads are so handy - the combined actions are simple, but they can at least participate - influence the flow of control if we are talking about a IO-like Monad. Also, arrows are supposed to be more general than both monads and > comonads. If I could just figure out what each structure (functor, > monad, comonad, arrow) is doing, and compare and contrast them, then I > probably will have made leaps of understanding. I have a sense that > tells me that the table above and the data structures below probably > start to scratch the surface of understanding. > > ---------------------------------------------------------------------- > > Arrows are most general because they have full access to the complexity going on in the structure. Each arrow can do arbitrarily complex (possibly bidirectional) negotiation with its input, and possibly asynchronously arbitrarily complex negotiation with its output. Any sort of data can flow any way at any time, the only restriction is that for an 'Arrow a b' object, the input side uses a's and the output b's. Compare a monad - the input must be single, simple a's. All that can happen is that the function gets called multiple times. -- Brian_Brunswick____brian@ithil.org____Wit____Disclaimer____!Shortsig_rules! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/bc4d7152/attachment.htm From hughes at rpi.edu Mon Aug 13 08:50:01 2007 From: hughes at rpi.edu (Sam Hughes) Date: Mon Aug 13 08:41:43 2007 Subject: [Haskell-cafe] IO within parser In-Reply-To: <20070813141655.4cd9e636@aligatoro.ret> References: <672187.69183.qm@web31409.mail.mud.yahoo.com> <20070812090926.30ad56f0@aligatoro.ret> <46BFA207.3050806@rpi.edu> <20070813141655.4cd9e636@aligatoro.ret> Message-ID: <46C05379.4010706@rpi.edu> Malte Milatz wrote: > Sam Hughes , Sun, 12 Aug 2007 20:12:55 -0400: > [A parser like Parsec, with monad transformers:] >> $ darcs get http://samuelhughes.com/darcs/partran/ > > Is this related in any way to the following GSoC project? > > http://code.google.com/soc/2007/haskell/appinfo.html?csaid=B97EF4562EF3B244 > > No, I just wanted it for my own purposes. - Sam From apfelmus at quantentunnel.de Mon Aug 13 08:55:48 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Mon Aug 13 08:48:18 2007 Subject: [Haskell-cafe] Re: Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46BF6459.6010709@charter.net> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> <46BF6459.6010709@charter.net> Message-ID: Isaac Dupree schrieb: > apfelmus wrote: >> Mutable data structures in the sense of ephemeral (= not persistent = >> update in-place) data structure indeed do introduce the need to work >> in ST since the old version is - by definition - not available anymore. > > Not in the quantum/information-theoretic sense, not necessarily. Consider > > import Control.Monad.ST > import Data.STRef > main = print (runST (do > r <- newSTRef 1 > notUnavailable <- readSTRef r > writeSTRef r 5 > return notUnavailable > )) I'm not sure what this has to do with quantum mechanics ;) but you're right, I forgot that. This means that either STRefs cannot be updated in-place or that every read operation copies the contents or something like that. In any case, simple values like Ints or Bools are rather uninteresting, update in-place is only important for larger structures like arrays. Here, ST does updates in-place and retaining an array will copy it. Regards, apfelmus From a.biurvOir4 at asuhan.com Mon Aug 13 09:30:12 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Mon Aug 13 09:21:53 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46BE0734.3040308@mindspring.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> <46BE0734.3040308@mindspring.com> Message-ID: <12126170.post@talk.nabble.com> Ronald Guida wrote: > > Given the question "What is a Monad", I would have to say "A Monad is > a device for sequencing side-effects." > There are side-effects and there are side-effects. If the only monad you use is Maybe, the only side-effect you get is a slight warming of the CPU. Dave Menendez pointed to that fine Wadler link earlier. Please read it. To wit, in Section 2: "Explaining Monads" the "essence of an algorithm can become buried under the plumbing required to carry data from its point of creation to its point of use." Monads can help keep the clarity of your code untrammelled by providing implicit plumbing, "side-channels" if you prefer, when data is moved around. In fact if you follow Wadler all the way to his monadic expression evaluator, you see that you could modularize your code in awesomely cool ways. You get to see how the kernel of the expression evaluator could be written for a generic monad and compiled once-and-for-all. Any additional feature (the "variations") is coded by enriching the monad. Monads are powerful devices for modularizing code. Available for free. Only in Haskell (thanks to type classes!). Get them today. "Side-effects" is a piece of linguistic cruft played fast-and-loose by too many people in this game. "Sequencing" suffers the same disease. -- View this message in context: http://www.nabble.com/Explaining-monads-tf4244948.html#a12126170 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From leaveye.guo at gmail.com Mon Aug 13 10:22:30 2007 From: leaveye.guo at gmail.com (L.Guo) Date: Mon Aug 13 10:14:27 2007 Subject: [Haskell-cafe] A few questions on primes generating. Message-ID: <200708132222225629298@gmail.com> Hi All: I am reading http://www.haskell.org/haskellwiki/Prime_numbers The code in sector "1 Bitwise prime sieve". I have 3 questions about it. 1) In function go, what does the number 46340 mean ? Is it sqrt(MAX_LONG) ? 2) We have this type definition : pureSieve :: Int -> Int Why there is no error (type mismatch) of this call in func main : pureSieve 10000000 3) In main again, what does expression [| x |] mean ? Why this cannot be execute in GHCi ? Thanks for any advice. Regards -------------- L.Guo 2007-08-13 From apfelmus at quantentunnel.de Mon Aug 13 10:35:12 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Mon Aug 13 10:27:05 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell In-Reply-To: References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <20070809185658.GF30903@darcs.net> Message-ID: Benjamin Franksen wrote: > As has been already mentioned in this thread, in > http://www.soi.city.ac.uk/~ross/papers/Applicative.html Conor McBride and > Ross Paterson invent/explain a new type class that is now part of the base > package (Control.Applicative). They also use/propose syntactic sugar for > it, i.e. > > pure f <*> u1 <*> ... <*> un > > ~~> (| f u1 ... un |) > > (I just made up the symbols '(|' and '|)', the concrete syntax would have to > be fixed by people more knowledgeable than me.) The problem with [| and |] lifted to monads that this only works for fully applied arguments, i.e. that handle :: IO Handle string :: IO String [| hPutStr handle string |] :: IO () works but [| hPutStr handle |] = join (return hPutStr `ap` handle) ^= join ((f :: m (a -> b -> m c)) `ap` (x :: m a)) = join ( y :: m (b -> m c)) is a type error. I think this is also what makes the (<- action) proposal so non-local and what is the source of this whole discussion. The core problem is: Functions like a -> b -> m c can't be partially applied to monadic actions like m a without specifying the number of arguments in advance. In other words, such functions aren't curried correctly. Clearly, LiftMn specifies the number of arguments. But _both_ the (<-) proposal and idiom brackets specify the number of arguments too! Namely by requiring that all arguments are fully applied. So, neither one is capable of partially applying the first argument without saturating the call, you can only write handle :: IO Handle -- define putStr in terms of the above hPutStr putStr :: String -> IO () putStr = \x -> [| hPutStr handle (return x) |] putStr = \x -> do { hPutStr (<- handle) x } One way to get currying for monads is to work with functions m a -> m b -> m c However, this type is larger than a -> b -> m c , i.e. the function from :: Monad m => (a -> b -> m c) -> (m a -> m b -> m c) from f ma mb = ma >>= \a -> mb >>= \b -> f a b is not surjective since we could perform the actions in a different order from2 f ma mb = mb >>= \b -> ma >>= \a -> f a b In other words, if someone gives you a value of type m a -> m b -> m c , then you can't convert it to a -> b -> m c and back without risking that you end up with a different result. But there is another type suitable for currying m (a -> m (b -> m c)) which I believe is in some way equivalent to a -> b -> m c from :: Monad m => (a -> b -> m c) -> m (a -> m (b -> m c)) from f = return $ \a -> return $ \b -> f a b to :: Monad m => m (a -> m (b -> m c)) -> (a -> b -> m c) to f a b = f >>= \g -> g a >>= \h -> h b but I'm not sure. My assumption is that we have an equivalence forall a,b . m (a -> m b) ~ (a -> m b) because any side effect executed by the extra m on the outside can well be delayed until we are supplied a value a. Well, at least when all arguments are fully applied, for some notion of "fully applied" Anyway, here's how to curry with that type: (@) :: Monad m => m (a -> m b) -> (m a -> m b) (@) f x = join (f `ap` x) hPutStr :: IO (Handle -> IO (String -> IO ())) handle :: IO Handle putStr :: IO (String -> IO ()) putStr = hPutStr @ handle With the infix type synonym type (~>) a b = a -> IO b we can also write hPutStr :: IO (Handle ~> String ~> () ) putStr :: IO (String ~> () ) This is of course the Kleisli-Arrow which explains why currying works. Regards, apfelmus From jmaessen at alum.mit.edu Mon Aug 13 10:40:14 2007 From: jmaessen at alum.mit.edu (Jan-Willem Maessen) Date: Mon Aug 13 10:31:26 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> Message-ID: On Aug 11, 2007, at 12:35 PM, Brian Hurt wrote: > > You guys might also want to take a look at the Cilk programming > language, and how it managed threads. If you know C, learning Cilk > is about 2 hours of work, as it's C with half a dozen extra > keywords and a few new concepts. I'd love to see Cilk - C + > Haskell as a programming language. It was called pH, and we (meaning Alejandro Caro and myself) implemented it back in the mid/late 90's using Lennart Augustsson's hbcc front end (which he hacked to add a bunch of pH-specific syntax). Arvind and Nikhil wrote a textbook on pH programming. There are two problems, still: one is that laziness means you can't actually prove you need something until very close to the time you actually want it. By the time I know that I'm adding f x to g y, it's probably too late to usefully run them in parallel (unless they're both *very* large). We used eager evaluation in pH---to the point that we actually gave up the ability to manipulate infinite lazy data structures. In NDP they've done much the same thing, first instrumenting the program to see that the eagerness they introduce won't disrupt execution. Even the "par" annotation has this feel: we are telling the implementation that it's OK to do some computation even if it isn't yet obvious that we'll need the results. The second problem is controlling the overhead. More on this below. > The key idea of Cilk is that it's easier to deparallelize than it > is to parallelize, especially automatically. So the idea is that > the program is written incredibly parallel, with huge numbers of > microthreads, which are (on average) very cheap to spawn. The > runtime then deparallelizes the microthreads, running multiple > microthreads sequentially within a single real thread (a worker > thread). Microthreads that live their entire life within a single > real thread are cheap to spawn (as in "not much more expensive than > a normal function call" cheap). The problem here is that while Cilk spawns are incredibly cheap, they're still more than a simple procedure call (2-10x as expensive if my fading memory serves me rightly). Let's imagine we have a nice, parallelizable computation that we've expressed using recursive subdivision (the Cilk folks like to use matrix multiplication as an example here). Near the leaves of that computation we still spend the majority of our time paying the overhead of spawning. So we end up actually imposing a depth bound, and writing two versions of our computation---the one that spawns, which we use for coarse-grained computations, and the one that doesn't, which we use when computation gets fine-grained. It makes a really big difference in practice. The programmer is free to use this trick in any programming language. But we haven't yet figured out a way to *avoid* the need to do so. This continues to worry me to this day, because making the right choices is black magic and specific to a particular combination of algorithm and machine. That said, there is some reason for optimism: the overhead of creating work in Cilk is comparable to the overhead of creating a thunk in Haskell. > The problem that Cilk runs into is that it's, well, C. It doesn't > deal with contention at well at all- a single microthread blocking > blocks the whole worker thread- meaning, among other things, that > you can have "false deadlocks", where one microthread blocks on > another microthread in the same real thread, and thus acts like > it's deadlocked even though it really isn't. This is actually a fundamental problem with the threading model: there is no guarantee of fairness using work stealing, so if you do something that requires fair scheduling you get into a lot of trouble fast. It's not fair to blame C for this. You have to be very careful to define the interaction between fair IO-style threads and unfair get-my-work-done threads. > You have greatly increased the likelyhood of raceconditions as well > (mutable data and multithreading just don't mix). Plus you have > all the normal fun you have with C bugs- wild pointers, buffer over > runs, etc. This, however, *is* C's fault. :-) More on pH: we got our programs to scale, but had troubles going past 8 threads. We found ourselves limited by a non-parallel GC (my fault, but labor-intensive to get right) and the absence of parallelism in the underlying algorithms. For the latter problem there simply is no magic bullet. -Jan-Willem Maessen From dry.green.tea at gmail.com Mon Aug 13 10:45:59 2007 From: dry.green.tea at gmail.com (Alexis Hazell) Date: Mon Aug 13 10:37:46 2007 Subject: [Haskell-cafe] A few questions on primes generating. In-Reply-To: <200708132222225629298@gmail.com> References: <200708132222225629298@gmail.com> Message-ID: <200708140046.00650.dry.green.tea@gmail.com> On Tuesday 14 August 2007 00:22, L.Guo wrote: > 2) We have this type definition : > pureSieve :: Int -> Int > Why there is no error (type mismatch) of this call in func main : > pureSieve 10000000 The Haskell Report says that an Int covers at least the range [- 2^29, 2^29 - 1], which that number is well within . . . . why do you think it should report a type error? Alexis. From stefanor at cox.net Mon Aug 13 10:50:30 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 13 10:42:12 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell In-Reply-To: References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <20070809185658.GF30903@darcs.net> Message-ID: <20070813145030.GA3395@localhost.localdomain> On Mon, Aug 13, 2007 at 04:35:12PM +0200, apfelmus wrote: > My assumption is that we have an equivalence > > forall a,b . m (a -> m b) ~ (a -> m b) > > because any side effect executed by the extra m on the outside can well be > delayed until we are supplied a value a. Well, at least when all arguments > are fully applied, for some notion of "fully applied" (\a x -> a >>= ($ x)) ((\f -> return f) X) ==> (?) (\a x -> a >>= ($ x)) (return X) ==> (?) (\x -> (return X) >>= ($ x)) ==> (monad law) (\x -> ($ x) X) ==> (? on the sugar-hidden 'flip') (\x -> X x) ==> (?) X Up to subtle strictness bugs arising from my use of ? :), you're safe. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/e336f356/attachment.bin From p3k at iki.fi Mon Aug 13 11:19:10 2007 From: p3k at iki.fi (Pekka Karjalainen) Date: Mon Aug 13 11:10:51 2007 Subject: [Haskell-cafe] A few questions on primes generating. In-Reply-To: <200708132222225629298@gmail.com> References: <200708132222225629298@gmail.com> Message-ID: <233457100708130819i7e14abc3q1e896264d4b8214c@mail.gmail.com> On 8/13/07, L.Guo wrote: > Hi All: Hello, > > I am reading http://www.haskell.org/haskellwiki/Prime_numbers > > The code in sector "1 Bitwise prime sieve". > > I have 3 questions about it. > > 1) In function go, what does the number 46340 mean ? Is it sqrt(MAX_LONG) ? Yes, it appears so. In a 32 bit implementation I get: Prelude> sqrt $ fromIntegral (maxBound :: Int) 46340.950001051984 > 2) We have this type definition : > pureSieve :: Int -> Int > Why there is no error (type mismatch) of this call in func main : > pureSieve 10000000 If you have integer literals in your program, the compiler sees a fromInteger in front of them. So the value is just converted to type Int automatically, because that is expected here. You can give different numeric default declarations in your own modules. Please see sections 10.3 (for overloaded literals) and 10.4 (for defaults) here: http://www.haskell.org/tutorial/numbers.html Sometimes you can get an overflow like this: Prelude> 100000000000000000000000 :: Int -159383552 > 3) In main again, what does expression [| x |] mean ? Why this cannot be execute in > GHCi ? It's Template Haskell, and is used there for some kind of optimisation (I think). Template Haskell needs to be enabled with a command line switch for it to work. Please see the documentation for more information. It's section 7.6 in your User's Guide. Though in this case you can probably just remove it to try out the program. Perhaps someone else can explain what actual effect it has here. Pekka From leaveye.guo at gmail.com Mon Aug 13 11:23:59 2007 From: leaveye.guo at gmail.com (L.Guo) Date: Mon Aug 13 11:15:52 2007 Subject: [Haskell-cafe] A few questions on primes generating. References: <200708132222225629298@gmail.com> <200708140046.00650.dry.green.tea@gmail.com> Message-ID: <200708132323506876214@gmail.com> Because 10,000,000 is too large for a Int, it is always in type of Integer or some higher level data type. ------------------ L.Guo 2007-08-13 ------------------------------------------------------------- From: Alexis Hazell At: 2007-08-13 22:46:46 Subject: Re: [Haskell-cafe] A few questions on primes generating. On Tuesday 14 August 2007 00:22, L.Guo wrote: > 2) We have this type definition : > pureSieve :: Int -> Int > Why there is no error (type mismatch) of this call in func main : > pureSieve 10000000 The Haskell Report says that an Int covers at least the range [- 2^29, 2^29 - 1], which that number is well within . . . . why do you think it should report a type error? Alexis. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From stefanor at cox.net Mon Aug 13 11:31:10 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 13 11:22:51 2007 Subject: [Haskell-cafe] A few questions on primes generating. In-Reply-To: <200708132323506876214@gmail.com> References: <200708132222225629298@gmail.com> <200708140046.00650.dry.green.tea@gmail.com> <200708132323506876214@gmail.com> Message-ID: <20070813153110.GB3543@localhost.localdomain> On Mon, Aug 13, 2007 at 11:23:59PM +0800, L.Guo wrote: > Because 10,000,000 is too large for a Int, it is always in type of Integer or some higher level data type. In Haskell, Int always supports at least -536,870,912 to 536,870,911. Also, large numbers don't (this is arguably a bug...) have restricted types: stefan@stefans:~$ ghc -e '1000000000000000000 :: Int' -1486618624 stefan@stefans:~$ Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/99f976b1/attachment-0001.bin From apfelmus at quantentunnel.de Mon Aug 13 11:39:34 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Mon Aug 13 11:31:28 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell In-Reply-To: <20070813145030.GA3395@localhost.localdomain> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <20070809185658.GF30903@darcs.net> <20070813145030.GA3395@localhost.localdomain> Message-ID: Stefan O'Rear schrieb: > On Mon, Aug 13, 2007 at 04:35:12PM +0200, apfelmus wrote: >> My assumption is that we have an equivalence >> >> forall a,b . m (a -> m b) ~ (a -> m b) >> >> because any side effect executed by the extra m on the outside can well be >> delayed until we are supplied a value a. Well, at least when all arguments >> are fully applied, for some notion of "fully applied" > > (\a x -> a >>= ($ x)) ((\f -> return f) X) ==> (?) > (\a x -> a >>= ($ x)) (return X) ==> (?) > (\x -> (return X) >>= ($ x)) ==> (monad law) > (\x -> ($ x) X) ==> (? on the sugar-hidden 'flip') > (\x -> X x) ==> (?) > X > > Up to subtle strictness bugs arising from my use of ? :), you're safe. Yes, but that's only one direction :) The other one is the problem: return . (\f x -> f >>= ($ x)) =?= id Here's a counterexample f :: IO (a -> IO a) f = writeAHaskellProgram >> return return f' :: IO (a -> IO a) f' = return $ (\f x -> f >>= ($ x)) $ f ==> (?) return $ \x -> (writeAHaskellProgram >> return return) >>= ($ x) ==> (BIND) return $ \x -> writeAHaskellProgram >> (return return >>= ($ x)) ==> (LUNIT) return $ \x -> writeAHaskellProgram >> (($ x) return) ==> (?) return $ \x -> writeAHaskellProgram >> return x Those two are different, because clever = f >> return () = writeAHaskellProgram clever' = f' >> return () = return () are clearly different ;) Regards, apfelmus From isaacdupree at charter.net Mon Aug 13 11:35:33 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Mon Aug 13 11:38:50 2007 Subject: [Haskell-cafe] A few questions on primes generating. In-Reply-To: <200708132323506876214@gmail.com> References: <200708132222225629298@gmail.com> <200708140046.00650.dry.green.tea@gmail.com> <200708132323506876214@gmail.com> Message-ID: <46C07A45.1020403@charter.net> L.Guo wrote: > Because 10,000,000 is too large for a Int On my pitiful system, > maxBound::Int 2147483647 is certainly greater than 10000000 . > it is always in type of Integer or some higher level data type. Haskell doesn't do static checking like that. In GHC on my system (where 10,000,000,000 is too large for an Int - note ten zeroes), > 10000000000::Int 1410065408 (Hugs gives "Program error: arithmetic overflow") Isaac From stefanor at cox.net Mon Aug 13 12:10:43 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 13 12:02:25 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell In-Reply-To: References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <20070809185658.GF30903@darcs.net> <20070813145030.GA3395@localhost.localdomain> Message-ID: <20070813161043.GB3638@localhost.localdomain> On Mon, Aug 13, 2007 at 05:39:34PM +0200, apfelmus wrote: > Stefan O'Rear schrieb: >> On Mon, Aug 13, 2007 at 04:35:12PM +0200, apfelmus wrote: >>> My assumption is that we have an equivalence >>> >>> forall a,b . m (a -> m b) ~ (a -> m b) >>> >>> because any side effect executed by the extra m on the outside can well >>> be delayed until we are supplied a value a. Well, at least when all >>> arguments are fully applied, for some notion of "fully applied" >> (\a x -> a >>= ($ x)) ((\f -> return f) X) ==> (?) >> (\a x -> a >>= ($ x)) (return X) ==> (?) >> (\x -> (return X) >>= ($ x)) ==> (monad law) >> (\x -> ($ x) X) ==> (? on the sugar-hidden >> 'flip') >> (\x -> X x) ==> (?) >> X >> Up to subtle strictness bugs arising from my use of ? :), you're safe. > > Yes, but that's only one direction :) The other one is the problem: > > return . (\f x -> f >>= ($ x)) =?= id > > Here's a counterexample > > f :: IO (a -> IO a) > f = writeAHaskellProgram >> return return > > f' :: IO (a -> IO a) > f' = return $ (\f x -> f >>= ($ x)) $ f > ==> (?) > return $ \x -> (writeAHaskellProgram >> return return) >>= ($ x) > ==> (BIND) > return $ \x -> writeAHaskellProgram >> (return return >>= ($ x)) > ==> (LUNIT) > return $ \x -> writeAHaskellProgram >> (($ x) return) > ==> (?) > return $ \x -> writeAHaskellProgram >> return x > > Those two are different, because > > clever = f >> return () = writeAHaskellProgram > clever' = f' >> return () = return () > > are clearly different ;) I figured that wouldn't be a problem since our values don't escape, and the functions we define all respect the embedding... More formally: Projections and injections: proj ma = \x -> ma >>= \ fn' -> fn' x inj fn = return fn Define an equivalence relation: ma ? mb <-> proj ma = proj mb Projection respects equivalence: ma ? mb -> proj ma = proj mb (intro ->) ma ? mb => proj ma = proj mb (equiv def) proj ma = proj mb => proj ma = proj mb (assumption) Application: (@) ma1 = \x -> join (proj ma1 x) Application respects equivalence: ma1 ? ma2 -> (@) ma1 = (@) ma2 (intro ->) ma1 ? ma2 => (@) ma1 = (@) ma2 (?) ma1 ? ma2 => (\x -> join (proj ma1 x)) = (\x -> join (proj ma2 x)) (extensionality) ma1 ? ma2 => join (proj ma1 x) = join (proj ma2 x) (application respects = left) ma1 ? ma2 => proj ma1 x = proj ma2 x (application respects = right) ma1 = ma2 => proj ma1 = proj ma2 (lemma) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/2e088453/attachment.bin From alex at alexjacobson.com Mon Aug 13 12:29:26 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Mon Aug 13 12:22:31 2007 Subject: [Haskell-cafe] xpath types for SYB/generic haskell type system? Message-ID: <46C086E6.3040708@alexjacobson.com> The SYB papers provide really powerful functions for accessing and manipulating a values in arbitrary shaped containers. The cost of this capability appears to be loss of type checking. For example gfindtype x returns a maybe y. Given that the type checker actually has to know whether or not x actually contains a y inside of it, is there a way to annotate a gfindtype sort of function that just returns a value and if applied with the wrong type has a compiler enforce error? It may not be in this version of haskell, but it seems like there is no technical reason you could not have partial type annotations that describe the traversal strategies described in SYB. Perhaps it is a type version of an xpath expression e.g myFindType::(.//y) x => x->y The (.//y) x says that y is a type nested somewhere in x. Note, since this is happening at compiler time, this capability will still not prevent you from doing a (fromJust Nothing), but it still seems super valuable if you are doing generic haskell type stuff? Is there a mathematical reason why this wouldn't work? -Alex- From isaacdupree at charter.net Mon Aug 13 12:27:45 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Mon Aug 13 12:36:13 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell In-Reply-To: <20070809185658.GF30903@darcs.net> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <20070809185658.GF30903@darcs.net> Message-ID: <46C08681.3080808@charter.net> David Roundy wrote: > The only cost is that > this syntax relies on the do notation, and thus makes the desugaring of > that do notation slightly more complicated when used. If I understand correctly, do blah f (do foo bar (<- action) ) blah has an ambiguity: which do-block is the action bound in? I can easily imagine myself being frustrated at having to refactor my code if the defined answer is not the one I want at the moment. Isaac From droundy at darcs.net Mon Aug 13 13:26:53 2007 From: droundy at darcs.net (David Roundy) Date: Mon Aug 13 13:18:36 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell In-Reply-To: <46C08681.3080808@charter.net> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <20070809185658.GF30903@darcs.net> <46C08681.3080808@charter.net> Message-ID: <20070813172653.GE15292@darcs.net> On Mon, Aug 13, 2007 at 01:27:45PM -0300, Isaac Dupree wrote: > David Roundy wrote: > >The only cost is that > >this syntax relies on the do notation, and thus makes the desugaring of > >that do notation slightly more complicated when used. > > If I understand correctly, > > do > blah > f (do > foo > bar (<- action) > ) > blah > > has an ambiguity: which do-block is the action bound in? I can easily > imagine myself being frustrated at having to refactor my code if the > defined answer is not the one I want at the moment. It doesn't have an ambiguity, because it's defined to be bound in the innermost do loop. This isn't a new concept, the <- syntax in the existing do notation has the same behavior. -- David Roundy Department of Physics Oregon State University From bf3 at telenet.be Mon Aug 13 13:31:48 2007 From: bf3 at telenet.be (peterv) Date: Mon Aug 13 13:23:34 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <12126170.post@talk.nabble.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> <46BE0734.3040308@mindspring.com> <12126170.post@talk.nabble.com> Message-ID: <000001c7ddcf$d42323f0$7c696bd0$@be> When I read "side-effects", I understand it as "unwanted effects", like "aliasing", and "effects depending on the order of execution". I'm not sure if my understanding here is correct. I hope Haskell does not allow "side-effects" but only "effects", meaning the monads do not allow you to write the typical ill-behaving code you get when doing real imperative programming, enforcing a single wiring of execution, not allowing the capture of the RealWorld object. In Concurrent Clean special compiler support is present to enforce "uniqueness typing", and in Haskell special compiler support is available to make the RealWorld object not available at runtime (so e.g. you can't put the RealWorld object in a list). Is this correct? BTW: What is the correct word in Haskell for "object"? I mean the (lazy) value you get when evaluating a data constructor? -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Kim-Ee Yeoh Sent: Monday, August 13, 2007 15:30 To: haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] Explaining monads Ronald Guida wrote: > > Given the question "What is a Monad", I would have to say "A Monad is > a device for sequencing side-effects." > There are side-effects and there are side-effects. If the only monad you use is Maybe, the only side-effect you get is a slight warming of the CPU. Dave Menendez pointed to that fine Wadler link earlier. Please read it. To wit, in Section 2: "Explaining Monads" the "essence of an algorithm can become buried under the plumbing required to carry data from its point of creation to its point of use." Monads can help keep the clarity of your code untrammelled by providing implicit plumbing, "side-channels" if you prefer, when data is moved around. In fact if you follow Wadler all the way to his monadic expression evaluator, you see that you could modularize your code in awesomely cool ways. You get to see how the kernel of the expression evaluator could be written for a generic monad and compiled once-and-for-all. Any additional feature (the "variations") is coded by enriching the monad. Monads are powerful devices for modularizing code. Available for free. Only in Haskell (thanks to type classes!). Get them today. "Side-effects" is a piece of linguistic cruft played fast-and-loose by too many people in this game. "Sequencing" suffers the same disease. -- View this message in context: http://www.nabble.com/Explaining-monads-tf4244948.html#a12126170 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe No virus found in this incoming message. Checked by AVG Free Edition. Version: 7.5.476 / Virus Database: 269.11.15/949 - Release Date: 12/08/2007 11:03 No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.476 / Virus Database: 269.11.15/949 - Release Date: 12/08/2007 11:03 From andrewcoppin at btinternet.com Mon Aug 13 14:05:03 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Mon Aug 13 13:56:05 2007 Subject: [Haskell-cafe] GHC optimisations Message-ID: <46C09D4F.1020507@btinternet.com> Does GHC do dead code elimination? I observe that if you take a module and edit it so that some function is now no longer exported or called by any exported function, the size of the *.o file seems to go down. This suggests that dead code within a single module is eliminated. However... how about this? module Foo where f = ... g = ... h = ... module Main where import Foo main = ...f... Will the generated executable contain the code for g and h, even though they aren't called? Or does the unused code get eliminated? How about the standard libraries? I read somewhere that if one funtion returns a tuple, and the caller immediately extracts the values from the tuple, GHC tries to optimise away the tuple - so it's as if the function can just return multiple values at once. Is this true? Does it apply only to tuples, or to all types? From byorgey at gmail.com Mon Aug 13 14:05:53 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Mon Aug 13 13:57:35 2007 Subject: [Haskell-cafe] Re: zip3, zip4 ... -> zipn? In-Reply-To: References: <0e3d01c7dbed$59676970$64c5a8c0@galilei> Message-ID: <22fcbd520708131105n48f6136br3e64266432488ae0@mail.gmail.com> On 8/11/07, Per Vognsen wrote: > > Applicative functors can indeed help: > > (,,,) <$> [1,2,3] <*> [-1,0,1] <*> [1,1,1] <*> [0,2,6] > > You just use n-1 commas when you want the effect of zipn. Actually, that's not quite right, since that uses the applicative functor related to the list monad (so you get a list of 4-tuples of all possible combinations, rather than a 4-way zip). To get the zip behavior, you need to add a ZipList constructor in front of all the lists, and then apply getZipList at the end to extract. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/11e236dd/attachment-0001.htm From stefanor at cox.net Mon Aug 13 14:19:49 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 13 14:12:39 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46C09D4F.1020507@btinternet.com> References: <46C09D4F.1020507@btinternet.com> Message-ID: <20070813181949.GA4103@localhost.localdomain> On Mon, Aug 13, 2007 at 07:05:03PM +0100, Andrew Coppin wrote: > Does GHC do dead code elimination? Yes - all unused let-binders are removed. > I observe that if you take a module and edit it so that some function is > now no longer exported or called by any exported function, the size of the > *.o file seems to go down. This suggests that dead code within a single > module is eliminated. > > However... how about this? > > module Foo where > > f = ... > g = ... > h = ... > > module Main where > > import Foo > > main = ...f... > > Will the generated executable contain the code for g and h, even though > they aren't called? Or does the unused code get eliminated? How about the > standard libraries? By default, GHC generates one object file per source module, so if any values from that module are used, the entire module is linked in. With the -split-objs flag, GHC generates one object file per top level function, sometimes significantly reducing the size of executables. This is not the default because it puts tremendous strain on the linker. It is common to spend several *minutes* linking base when compiling ghc, and it's not unheard of for ar to simply run out of memory and die. > I read somewhere that if one funtion returns a tuple, and the caller > immediately extracts the values from the tuple, GHC tries to optimise away > the tuple - so it's as if the function can just return multiple values at > once. Is this true? Does it apply only to tuples, or to all types? This is called the Constructed Product Return (CPR) analysis, and it applies to all types with one constructor (in archaic jargon, product types). For instance, (+) (I# x#) (I# y#) = I# (x# +# y#) foo = case 2 + 2 of I# x# -> ... is transformed into: zdzp (I# x#) (I# y#) = (x# +# y#) foo = case 2 + 2 of x# -> ... This is one of the two main pillars of arithmetic unboxing, alongside and equally important to strictness analysis. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/19c61f7f/attachment.bin From andrewcoppin at btinternet.com Mon Aug 13 14:35:31 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Mon Aug 13 14:26:32 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070813181949.GA4103@localhost.localdomain> References: <46C09D4F.1020507@btinternet.com> <20070813181949.GA4103@localhost.localdomain> Message-ID: <46C0A473.5030308@btinternet.com> Stefan O'Rear wrote: > On Mon, Aug 13, 2007 at 07:05:03PM +0100, Andrew Coppin wrote: > >> Does GHC do dead code elimination? >> > > Yes - all unused let-binders are removed. > Not related to optimisation, but... is there some switch to warn you if something gets removed? (Presumably this means you forgot to export something, or you haven't coded the bit that calls it yet or something.) >> Will the generated executable contain the code for g and h, even though >> they aren't called? Or does the unused code get eliminated? How about the >> standard libraries? >> > > By default, GHC generates one object file per source module, so if any > values from that module are used, the entire module is linked in. Right, OK. I had a feeling that was the case. (I once compiled a program that used the GHC API. The final binary was several times larger than ghc.exe...) > With > the -split-objs flag, GHC generates one object file per top level > function, sometimes significantly reducing the size of executables. > This is not the default because it puts tremendous strain on the linker. > It is common to spend several *minutes* linking base when compiling ghc, > and it's not unheard of for ar to simply run out of memory and die. > Ouch! o_O Probably simpler for me, as a human, to split the program into a sensible module structure... ;-) >> I read somewhere that if one funtion returns a tuple, and the caller >> immediately extracts the values from the tuple, GHC tries to optimise away >> the tuple - so it's as if the function can just return multiple values at >> once. Is this true? Does it apply only to tuples, or to all types? >> > > This is called the Constructed Product Return (CPR) analysis, and it > applies to all types with one constructor (in archaic jargon, product > types). > Right. So it doesn't have to have strict fields or anything? Just has to have exactly one constructor? From stefanor at cox.net Mon Aug 13 14:44:21 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 13 14:36:08 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46C0A473.5030308@btinternet.com> References: <46C09D4F.1020507@btinternet.com> <20070813181949.GA4103@localhost.localdomain> <46C0A473.5030308@btinternet.com> Message-ID: <20070813184421.GA4174@localhost.localdomain> On Mon, Aug 13, 2007 at 07:35:31PM +0100, Andrew Coppin wrote: > Not related to optimisation, but... is there some switch to warn you if > something gets removed? (Presumably this means you forgot to export > something, or you haven't coded the bit that calls it yet or something.) -fwarn-unused-binds (included in -Wall) > (I once compiled a program that used the GHC API. The final binary was > several times larger than ghc.exe...) GHC is a particularly bad case because what it does is determined by the settings of a bunch of switches in the configuration data. Of course, GHC isn't smart enough to perform inter-module control flow analysis, so even with -split-objs you'd probably still link most of GHC. >>> I read somewhere that if one funtion returns a tuple, and the caller >>> immediately extracts the values from the tuple, GHC tries to optimise >>> away the tuple - so it's as if the function can just return multiple >>> values at once. Is this true? Does it apply only to tuples, or to all >>> types? >> >> This is called the Constructed Product Return (CPR) analysis, and it >> applies to all types with one constructor (in archaic jargon, product >> types). > > Right. So it doesn't have to have strict fields or anything? Just has to > have exactly one constructor? Yep, CPR is completely independent of strictness, however the returned product must be *new*, since returning an old object by value risks losing sharing (and thus creating large memory leaks). Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/4946077a/attachment.bin From andrewcoppin at btinternet.com Mon Aug 13 14:51:06 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Mon Aug 13 14:42:08 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070813184421.GA4174@localhost.localdomain> References: <46C09D4F.1020507@btinternet.com> <20070813181949.GA4103@localhost.localdomain> <46C0A473.5030308@btinternet.com> <20070813184421.GA4174@localhost.localdomain> Message-ID: <46C0A81A.7060507@btinternet.com> Stefan O'Rear wrote: > On Mon, Aug 13, 2007 at 07:35:31PM +0100, Andrew Coppin wrote: > >> (I once compiled a program that used the GHC API. The final binary was >> several times larger than ghc.exe...) >> > > GHC is a particularly bad case because what it does is determined by the > settings of a bunch of switches in the configuration data. Of course, > GHC isn't smart enough to perform inter-module control flow analysis, so > even with -split-objs you'd probably still link most of GHC. > Is it likely that GHC will ever become "smart enough" to do that kind of analysis? (I imagine this is going to be especially fun with precompiled libraries...) >>> This is called the Constructed Product Return (CPR) analysis, and it >>> applies to all types with one constructor (in archaic jargon, product >>> types). >>> >> Right. So it doesn't have to have strict fields or anything? Just has to >> have exactly one constructor? >> > > Yep, CPR is completely independent of strictness, however the returned > product must be *new*, since returning an old object by value risks > losing sharing (and thus creating large memory leaks). > Right, OK. From mmitar at gmail.com Mon Aug 13 14:53:06 2007 From: mmitar at gmail.com (Mitar) Date: Mon Aug 13 14:44:47 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> Message-ID: Hi! I am thinking about a model where you would have only n threads on a n-core (or processor) machine. They would be your worker threads and you would spawn them only once (at the beginning of the program) and then just delegate work between them. On 8/13/07, Jan-Willem Maessen wrote: > The problem here is that while Cilk spawns are incredibly cheap, > they're still more than a simple procedure call (2-10x as expensive > if my fading memory serves me rightly). Let's imagine we have a > nice, parallelizable computation that we've expressed using recursive > subdivision (the Cilk folks like to use matrix multiplication as an > example here). Near the leaves of that computation we still spend > the majority of our time paying the overhead of spawning. So we end > up actually imposing a depth bound, and writing two versions of our > computation---the one that spawns, which we use for coarse-grained > computations, and the one that doesn't, which we use when computation > gets fine-grained. It makes a really big difference in practice. But this could be done at the runtime too. If the lazy-non-evaluated-yet chunk is "big" then divide it into a few parts and run each part in its thread. But if the chunk is small (you are at the end of the evaluation and you already evaluated necessary subexpressions) you do it in the thread which encounters this situation (which is probably near the end of the program or the end of the monadic IO action). And this line when you choose to delegate or not can be determined at runtime too. In combination with some transactional memory or some other trick which would be behind this delegation this could be probably possible. We could also hint runtime that the function would probably take a long time to compute (even if it is lazy) with making a type for such functions which would signal this. Of course this could also make things worse if used improperly. But sometimes you know that you will be running the map of time-consuming function. Yes, you have parMap but the problem I saw with it (and please correct me if I am wrong) is that it spawns a new thread for every application of the function to the element? But what if functions are small? Then this is quite an overhead. And you have to know this in advance if you want to use something else than the default parMap which is not always possible (if we are passing a function as an argument to the function which calls map). For example: calculate f xs = foldl (+) 0 $ map f xs -- or foldr, I am not sure And I would like to see something like this: it gets to the point when we need to evaluate this function call, for some "big" f and some "big" list of xs, so the thread which gets to it starts evaluating the first value and when it starts with another (it is recursive call so it is a "similar" evaluation) it sees that the other thread is empty and the function would probably take a long time (it speculates) so it delegates it there and continues with the third element that is a dummy recursive call to the function, in this case foldl (dummy because it did not really evaluate everything at the previous level). Now, if the second thread finishes first, it goes to the next element (recursive call) but sees that it is already (still) evaluating, so it gets to the fourth. Otherwise, it the first thread finishes first just goes to the next element. This would be some kind of speculative evaluating. If the CPUs know how to do that why would not we at the higher level? It would be also an interesting lazy evaluation of the, in this example, foldl function. The system would make a recursive call but would just go another call deeper if it finds that it is impossible (because it is still evaluating somewhere else) to evaluate it. And at every level it finishes it will check previous levels if it can collapse them (and maybe prematurely finish the whole thing). It would be like that I unwind the loop (in this case recursion), evaluate everything (on many threads) and then (try to) calculate the value. If it finishes prematurely ... sad, but for "big" lists and "big" functions it would be a saver. And the size of this window (unwinding) would be a heuristic speculative function of number of possible threads (cores, processors) and of information how long have previous evaluations of the same function taken. I really messed this explanation up. Or maybe it is completely wrong and this is why it looks like a mess to me. :-) Mitar From andrewcoppin at btinternet.com Mon Aug 13 15:14:44 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Mon Aug 13 15:05:46 2007 Subject: [Haskell-cafe] A few questions on primes generating. In-Reply-To: <20070813153110.GB3543@localhost.localdomain> References: <200708132222225629298@gmail.com> <200708140046.00650.dry.green.tea@gmail.com> <200708132323506876214@gmail.com> <20070813153110.GB3543@localhost.localdomain> Message-ID: <46C0ADA4.8080807@btinternet.com> Stefan O'Rear wrote: > Also, large numbers don't (this is arguably a bug...) have restricted > types: > > stefan@stefans:~$ ghc -e '1000000000000000000 :: Int' > -1486618624 > So many other programming languages allow weird things to happen with numeric overflows... it would be nice if Haskell didn't. From cartazio at yahoo.com Mon Aug 13 15:29:25 2007 From: cartazio at yahoo.com (Carter T Schonwald) Date: Mon Aug 13 15:21:07 2007 Subject: [Haskell-cafe] out of core computing in haskell Message-ID: <923570.28642.qm@web30202.mail.mud.yahoo.com> Hello Everyone, I'm not quite sure if I'm posing this question correctly, but what facilities currently exist in haskell to nicely deal with datastructures that won't fit within a given machine's ram? And if there are no such facilities, what would it take to fix that? thanks -Carter -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/4ad38d40/attachment.htm From stefanor at cox.net Mon Aug 13 15:44:42 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 13 15:36:34 2007 Subject: [Haskell-cafe] out of core computing in haskell In-Reply-To: <923570.28642.qm@web30202.mail.mud.yahoo.com> References: <923570.28642.qm@web30202.mail.mud.yahoo.com> Message-ID: <20070813194441.GA4631@localhost.localdomain> On Mon, Aug 13, 2007 at 12:29:25PM -0700, Carter T Schonwald wrote: > Hello Everyone, > I'm not quite sure if I'm posing this question correctly, but what > facilities currently exist in haskell to nicely deal with > datastructures that won't fit within a given machine's ram? And if > there are no such facilities, what would it take to fix that? You're asking correctly, and according to the Hackage list: http://hackage.haskell.org/packages/archive/pkg-list.html we have: * anydbm library and program: Interface for DBM-like database systems * BerkeleyDB library: Bindings for Berkeley DB v1.x * haskelldb library: SQL unwrapper for Haskell. * HDBC library * hsql library * PostgreSQL library: Thin wrapper over the C postgresql library We also have Data.Binary and Data.ByteString, but those are more useful for building data stores, than as data stores themselves. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/6a7945cc/attachment-0001.bin From andrewcoppin at btinternet.com Mon Aug 13 15:55:57 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Mon Aug 13 15:46:59 2007 Subject: [Haskell-cafe] out of core computing in haskell In-Reply-To: <923570.28642.qm@web30202.mail.mud.yahoo.com> References: <923570.28642.qm@web30202.mail.mud.yahoo.com> Message-ID: <46C0B74D.5030103@btinternet.com> Carter T Schonwald wrote: > Hello Everyone, > I'm not quite sure if I'm posing this question correctly, but what > facilities currently exist in haskell to nicely deal with > datastructures that won't fit within a given machine's ram? > And if there are no such facilities, what would it take to fix that? If you just want to process a big chunk of data from one end to the other without loading it all into RAM at once... that's fairly easy. Haskell is a lazy language. By playing with functions such as getContents, you can automatically load the data as you access it. No tricky programming required. If you're asking for something more specific -- e.g., "how do I talk to a standard database like Oracle / MySql / et al.", there are a couple of libraries for that. (Unfortunately, no one standard one.) See Stefan's answer. I'd you'd like to be more specific about what you'd like to do... From jmaessen at alum.mit.edu Mon Aug 13 16:01:14 2007 From: jmaessen at alum.mit.edu (Jan-Willem Maessen) Date: Mon Aug 13 15:52:27 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> Message-ID: On Aug 13, 2007, at 2:53 PM, Mitar wrote: > Hi! > > I am thinking about a model where you would have only n threads on a > n-core (or processor) machine. They would be your worker threads and > you would spawn them only once (at the beginning of the program) and > then just delegate work between them. > > On 8/13/07, Jan-Willem Maessen wrote: >> The problem here is that while Cilk spawns are incredibly cheap, >> they're still more than a simple procedure call (2-10x as expensive >> if my fading memory serves me rightly). Let's imagine we have a >> nice, parallelizable computation that we've expressed using recursive >> subdivision (the Cilk folks like to use matrix multiplication as an >> example here). Near the leaves of that computation we still spend >> the majority of our time paying the overhead of spawning. So we end >> up actually imposing a depth bound, and writing two versions of our >> computation---the one that spawns, which we use for coarse-grained >> computations, and the one that doesn't, which we use when computation >> gets fine-grained. It makes a really big difference in practice. > > But this could be done at the runtime too. If the > lazy-non-evaluated-yet chunk is "big" then divide it into a few parts > and run each part in its thread. But if the chunk is small (you are at > the end of the evaluation and you already evaluated necessary > subexpressions) you do it in the thread which encounters this > situation (which is probably near the end of the program or the end of > the monadic IO action). I didn't make my point very well. The hard part is determining exactly when a chunk is "big" or "small" without actually computing its value. Consider recursive fib (which I use only because it's easy to understand, and has been used as an example of this problem by the Cilk implementors): fib n = if n <= 1 then n else fib (n-1) + fib (n-2) Imagine we're computing (fib 30). We can divide and conquer; plenty of parallelism there! But do most calls to fib represent enough work to justify running them in parallel? No, because most of the calls are to (fib 0) or (fib 1)! We should only pay the spawn cost up to a certain bound --- say n >= 5 --- and then run serially for smaller n. This has a dramatic effect on how fast fib runs, but of course the best possible choice of bound is going to be machine-dependent. We can instrument our program and have some chance of doing OK for fib :: Int -> Int; it's not at all obvious what to do for: myFunction :: [Int] -> (Int -> Bool) -> [Frob] In effect, I end up needing to write myFunction with a built-in bound on computation, and I need to do it in such a way that the underlying systems knows that one branch should be serial and the other branch parallel. This is the problem I was attempting to allude to above. Yes, we can decide on a function-by-function or callsite-by-callsite basis that "enough work" is being done to justify parallelism. But the answer to this question is often "maybe", or even "no" (as in fib). > Yes, you have parMap but the problem I saw with it (and please correct > me if I am wrong) is that it spawns a new thread for every application > of the function to the element? > But what if functions are small? Then > this is quite an overhead. And you have to know this in advance if you > want to use something else than the default parMap which is not always > possible (if we are passing a function as an argument to the function > which calls map). > > For example: > > calculate f xs = foldl (+) 0 $ map f xs -- or foldr, I am not sure You seem to be arguing that we can pick the right implementation of "map" and "fold" (serial or parallel) here if we only knew that xs was "big enough" and f "expensive enough". I agree. But that begs the question: let's assume "calculate" is a function that's called from numerous places, with a mixture of "big" and "small" arguments. Now I need two versions of calculate, and I need to decide at each call site whether to call "big calculate" or "small calculate". We also need to make sure any eagerness we introduce is semantically sound, too, but I think we've got a pretty good handle on that part in practice between my work on resource- bounded evaluation in Eager Haskell, Rob Ennals' work on eager evaluation in GHC, and the Singh & Harris paper. That isn't to say that any of this is impossible---but it's going to take a while to figure out how to get it right [it'd be a great Ph.D. project to even knock off the low-hanging fruit like fib and recursive matrix multiply]. Meanwhile, we also need to work hard educating programmers how to write code that'll run in parallel in the first place, and giving them the libraries that'll make it easy. -Jan-Willem Maessen From cartazio at yahoo.com Mon Aug 13 16:27:03 2007 From: cartazio at yahoo.com (Carter T Schonwald) Date: Mon Aug 13 16:18:44 2007 Subject: [Haskell-cafe] out of core computing in haskell Message-ID: <126067.12566.qm@web30215.mail.mud.yahoo.com> The main two use cases I have in mind are 1) really really really big abstract syntax trees or proof trees (a la compilers or theorem provers) 2) random access to numerical data does that help clarify what i'm asking about? In each case, is there a standard way of dealing with this? in the case of (1) the sensible way seems to me to do some sort of zipper representation which loads adjacent nodes to some depth surrounding your current location in the tree, and in the case of (2) it seems like the sensible way would be load subsequences of the data into memory. ----- Original Message ---- From: Andrew Coppin To: haskell-cafe@haskell.org Sent: Monday, August 13, 2007 3:55:57 PM Subject: Re: [Haskell-cafe] out of core computing in haskell Carter T Schonwald wrote: > Hello Everyone, > I'm not quite sure if I'm posing this question correctly, but what > facilities currently exist in haskell to nicely deal with > datastructures that won't fit within a given machine's ram? > And if there are no such facilities, what would it take to fix that? If you just want to process a big chunk of data from one end to the other without loading it all into RAM at once... that's fairly easy. Haskell is a lazy language. By playing with functions such as getContents, you can automatically load the data as you access it. No tricky programming required. If you're asking for something more specific -- e.g., "how do I talk to a standard database like Oracle / MySql / et al.", there are a couple of libraries for that. (Unfortunately, no one standard one.) See Stefan's answer. I'd you'd like to be more specific about what you'd like to do... _______________________________________________ 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/haskell-cafe/attachments/20070813/48bc8046/attachment.htm From benjamin.franksen at bessy.de Mon Aug 13 16:29:37 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Mon Aug 13 16:21:56 2007 Subject: [Haskell-cafe] Re: Explaining monads References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> Message-ID: Brian Brunswick wrote: > One thing that I keep seeing people say (not you), is that monads /sequence/ > side effects. This is wrong, or at > least a limited picture. > > /All/ of the above structures are about combining compatible things things > together in a row. > /None/ of them force any particular order of evaluation - that all comes > from the particular instance. So its > only a particular feature of IO that it sequences the side effects. Others > don't - we can have a lazy State > monad that just builds up big thunks. I am a bit astonished. Let's take the simplest example: Maybe. The effect in question is the premature abortion of a computation (when Nothing is returned). And of course Maybe sequences these effects, that's what you use it for: the _first_ action to be encountered that returns Nothing aborts the computation. Clearly sequencing goes on here. Similar with the Error Monad (i.e. Either Err, for some Err type). I won't talk about List Monad because I always had difficulty understanding the List Monad. What about State? The effect is reading/writing the state. Again, the State Monad takes care that these effects get sequenced, and again that's what you expect it to do for you. And so on... This is -- of course -- not a proof, so maybe there /are/ Monads that don't sequence (their) effects. I'd be most interested to see an example, if there is one, to bring myself nearer to the -- unattainable -- goal of full enlightenment wrt Monads. Cheers Ben From allbery at ece.cmu.edu Mon Aug 13 17:13:01 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Mon Aug 13 17:04:58 2007 Subject: [Haskell-cafe] Re: Explaining monads In-Reply-To: References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> Message-ID: <1FB24845-06B7-460E-97A6-368BE0BA0BF0@ece.cmu.edu> On Aug 13, 2007, at 16:29 , Benjamin Franksen wrote: > Let's take the simplest example: Maybe. The effect in question is the > premature abortion of a computation (when Nothing is returned). And of > course Maybe sequences these effects, that's what you use it for: the > _first_ action to be encountered that returns Nothing aborts the > computation. Clearly sequencing goes on here. Clearly it does, but not as a side effect of the *monad*. It's ordinary Haskell data dependencies at work here, not some mystical behavior of a monad. > What about State? The effect is reading/writing the state. Again, > the State > Monad takes care that these effects get sequenced, and again that's > what > you expect it to do for you. No, I expect it to carry a value around for me. If I carry that value around myself instead of relying on the monad to do it for me, *the calculation still gets sequenced by the data dependencies*. -- 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 benjamin.franksen at bessy.de Mon Aug 13 17:15:24 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Mon Aug 13 17:07:18 2007 Subject: [Haskell-cafe] Re: Help with a project design References: <20070812130438.GB11356@laptop.nowhere.net> Message-ID: Andrea Rossato wrote: > The task this library should do is simple: given an xml object > (representing a bibliographic reference), render it with rules stored > in a different xml object (the citation style). While I think I can > find solutions for this problem - the rendering -, what I find > difficult is the design of the reference xml objects. > > Bibliographic entries have different types, which must be rendered > differently. These types can be classified into 3 main classes (books, > articles, parts of a book) that can be rendered with the same methods. > That seems to fit Haskell perfectly. > > Now, I basically see 2 approaches: > > 1. create some data structures (most part of them is common) to map > different types of bibliographic entries, and create the needed > classes with the render methods; > > 2. keep the xml objects as xml and create an abstract interface to the > xml objects to get the data required for rendering and classifying > the xml objects. This way I would have to: > - create data types to store different types of xml objects (data > Book = Book XmlTree, data Artilce, etc.): these data types > represent my reference classes; > - create a class of 'render'-able types with the render method and > define the instances; > - create an existential type to set the type of the xml objects > with some kind of setType :: XmlTree -> ExistentialContainer I may not be overly qualified (and experienced with Haskell) to give you advice, so take what follows with caution. I would definitely prefer choice 1 over 2. I think it is very important to design the data structure independent from any external representation of that data. XML is a fine way to externally represent data, but this should not influence your choice of data structure. I'd rather keep the possibility of alternative representations in the back of my head, and make the data structure general enough that they could be added w/o disrupting your main algorithms. Abstraction can be added later; if you find that you need to maintain invariants for you bibliographic data that cannot be easily expressed in the type itself, then you might consider to make your data type abstract, i.e. put it into a module of its own and export only an API. > I think that the first approach is not abstract enough and requires a > lot of boilerplate code to translate into a Haskell type a specific > type of bibliographic entry. A certain amount of boiler plate may be unavoidable. I never found this to be a serious obstacle, but again that may be due to my limited experience. It is a bit tedious to write but OTOH may even serve you as 'finger exercise'. If it really gets out of hand, 'scrap' it in some way ;) I recommend the Uniplate approach because it is very easy to understand, performs good, and requires the least amount of extensions. OK, you have been warned... Cheers Ben From brianh at metamilk.com Mon Aug 13 17:28:11 2007 From: brianh at metamilk.com (Brian Hulley) Date: Mon Aug 13 17:19:33 2007 Subject: [Haskell-cafe] Re: Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46BF4BD8.9080809@metamilk.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> <46BF4BD8.9080809@metamilk.com> Message-ID: <46C0CCEB.2060505@metamilk.com> Brian Hulley wrote: > apfelmus wrote: >> Brian Hulley schrieb: >>> main = do >>> buffer <- createBuffer >>> edit1 <- createEdit buffer >>> edit2 <- createEdit buffer >>> splitter <- createSplitter (wrapWidget edit1) (wrapWidget >>> edit2) >>> runMessageLoopWith splitter >>> >>> ... Thus the ability to abstract mutable state gives to my mind by >>> far the best solution. >> >> I'm not sure whether mutable state is the real goodie here. I think >> it's the ability to indpendently access parts of a compound state. >> http://www.st.cs.ru.nl/papers/2005/eves2005-FFormsIFL04.pdf > > This is indeed a real key to the problem. Of course this is only one aspect of the problem... Thinking about this a bit more, and just so this thought is recorded for posterity (!) and for the benefit of anyone now or in a few hundred years time, trying to solve "Fermat's last GUI", the object oriented solution allows the buffer object to do anything it wants, so that it could negotiate a network connection and implement the interface based on a shared network buffer for example, without needing any changes to the client code above, so a functional gui would need to have the same flexibility to compete with the OO solution. Another thing that would be interesting would be to have a formal treatment of what is supposed to happen in a gui. For example, when you move the mouse over a control which has become dirty (ie needs to be re-rendered because its state is now inconsistent), what should the control do? Should it respond as if the new state were already visible to the user, or should it interpret the mouse position according to the last state that was rendered, or should it just ignore all mouse events until the next time it gets rendered? This is not a trivial question because you could imagine an animated control where the user might naturally be following the movement, whereas when the user clicks on a cell in a spreadsheet when the cells to the left have now expanded due to a change in data thus moving the cell along (but where this updated model has not yet been re-rendered) the user might be irritated at the wrong cell being selected... It's tricky little issues like this that I haven't found any documentation for anywhere, and which would make a proper mathematical treatment of interaction with a gui very useful, regardless of whether it is implemented in OOP or functional style. Anyway just a thought, Brian. From droundy at darcs.net Mon Aug 13 17:48:10 2007 From: droundy at darcs.net (David Roundy) Date: Mon Aug 13 17:39:56 2007 Subject: [Haskell-cafe] out of core computing in haskell In-Reply-To: <126067.12566.qm@web30215.mail.mud.yahoo.com> References: <126067.12566.qm@web30215.mail.mud.yahoo.com> Message-ID: <20070813214809.GD644@darcs.net> In the second case, if your numerical data is just a big array, why not just mmap it? Unless you're running on a 32 bit machine, or have a *seriously* large amount of data, that seems like the easiest option. Although if you're talking about mutable data, that's a whole 'nother can of worms... but that's true even if your data fits into memory. You could look at Data.ByteString to get some idea as to how to wrap a pure interface around a disk-backed chunk of read-only memory. Or just read about the ffi, it's not too hard to figure out. David On Mon, Aug 13, 2007 at 01:27:03PM -0700, Carter T Schonwald wrote: > The main two use cases I have in mind are > 1) really really really big abstract syntax trees or proof trees (a la > compilers or theorem provers) > 2) random access to numerical data > > does that help clarify what i'm asking about? In each case, is there a > standard way of dealing with this? > in the case of (1) the sensible way seems to me to do some sort of zipper > representation which loads adjacent nodes to some depth surrounding your > current location in the tree, and in the case of (2) it seems like the > sensible way would be load subsequences of the data into memory. From isaacdupree at charter.net Mon Aug 13 17:42:36 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Mon Aug 13 17:45:57 2007 Subject: [Haskell-cafe] A few questions on primes generating. In-Reply-To: <46C0ADA4.8080807@btinternet.com> References: <200708132222225629298@gmail.com> <200708140046.00650.dry.green.tea@gmail.com> <200708132323506876214@gmail.com> <20070813153110.GB3543@localhost.localdomain> <46C0ADA4.8080807@btinternet.com> Message-ID: <46C0D04C.3020205@charter.net> Andrew Coppin wrote: > Stefan O'Rear wrote: >> Also, large numbers don't (this is arguably a bug...) have restricted >> types: >> >> stefan@stefans:~$ ghc -e '1000000000000000000 :: Int' >> -1486618624 >> > > So many other programming languages allow weird things to happen with > numeric overflows... it would be nice if Haskell didn't. Shall we have a GHC warning if it can detect those cases, either the Haskell report bounds or that of the target GHC is currently compiling to? (of course someone would have to implement it, and there would always be cases it didn't check, and the (non-portable) behavior is sometimes desired...) Hugs often does throw an exception (runtime error) rather than allow Int overflow (but not always). Isaac From droundy at darcs.net Mon Aug 13 18:01:01 2007 From: droundy at darcs.net (David Roundy) Date: Mon Aug 13 17:52:43 2007 Subject: [Haskell-cafe] Re: Explaining monads In-Reply-To: <1FB24845-06B7-460E-97A6-368BE0BA0BF0@ece.cmu.edu> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> <1FB24845-06B7-460E-97A6-368BE0BA0BF0@ece.cmu.edu> Message-ID: <20070813220101.GE644@darcs.net> On Mon, Aug 13, 2007 at 05:13:01PM -0400, Brandon S. Allbery KF8NH wrote: > On Aug 13, 2007, at 16:29 , Benjamin Franksen wrote: > >Let's take the simplest example: Maybe. The effect in question is the > >premature abortion of a computation (when Nothing is returned). And of > >course Maybe sequences these effects, that's what you use it for: the > >_first_ action to be encountered that returns Nothing aborts the > >computation. Clearly sequencing goes on here. > > Clearly it does, but not as a side effect of the *monad*. It's ordinary > Haskell data dependencies at work here, not some mystical behavior of a > monad. It's the *effect* of a monad, not the *side* effect. The type of >>= defines this dependency. And when you have a chain of dependencies, that is sometimes referred to as a sequence. True, it's not mystical, but it's still sequenced. Try executing: do { x <- return 2; undefined; return (x*x); } in any monad you like, and you'll find that regardless of the *data* dependencies (the return value of this monadic action is unambiguous), the undefined is evaluated *before* the value 4 is returned. -- David Roundy Department of Physics Oregon State University From isaacdupree at charter.net Mon Aug 13 17:59:15 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Mon Aug 13 18:02:32 2007 Subject: [Haskell-cafe] Re: Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: <46C0CCEB.2060505@metamilk.com> References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> <46BF4BD8.9080809@metamilk.com> <46C0CCEB.2060505@metamilk.com> Message-ID: <46C0D433.9010509@charter.net> Brian Hulley wrote: > Thinking about this a bit more, and just so this thought is recorded for > posterity (!) and for the benefit of anyone now or in a few hundred > years time, trying to solve "Fermat's last GUI", the object oriented > solution allows the buffer object to do anything it wants, so that it > could negotiate a network connection and implement the interface based > on a shared network buffer for example, without needing any changes to > the client code above, so a functional gui would need to have the same > flexibility to compete with the OO solution. Probably it would be parametric in the input mechanism, somehow. (A Haskell approach might use type classes, slightly obscuring the parametricity..) > Another thing that would be interesting would be to have a formal > treatment of what is supposed to happen in a gui. For example, when you > move the mouse over a control which has become dirty (ie needs to be > re-rendered because its state is now inconsistent), what should the > control do? Should it respond as if the new state were already visible > to the user, or should it interpret the mouse position according to the > last state that was rendered, or should it just ignore all mouse events > until the next time it gets rendered? This is not a trivial question > because you could imagine an animated control where the user might > naturally be following the movement, whereas when the user clicks on a > cell in a spreadsheet when the cells to the left have now expanded due > to a change in data thus moving the cell along (but where this updated > model has not yet been re-rendered) the user might be irritated at the > wrong cell being selected... It's tricky little issues like this that I > haven't found any documentation for anywhere, and which would make a > proper mathematical treatment of interaction with a gui very useful, > regardless of whether it is implemented in OOP or functional style. Jef Raskin (late interface designer, author of _The Humane Interface_) would probably say that anything with such importance to user decisions, should be rendered within a tenth of a second. Computers fifteen years ago could sometimes do it! Fancy details can be filled in later if it takes that long. Of course that completely dodges the mathematical question... in which human response time should really be taken into account too! Humans really are not like machines and are not all alike either! Oh no, do we need psychological formalisms? Firefox suffers the above problems badly, alas - the "Stop" button is half useless because it doesn't even noticed you pressed it for such a long time, etc... Reading up on user interface design principles as well as thinking functionally, is probably a useful approach - although not everything that you read will agree or be right. The whole concept of GUIs - they are very complicated - it is quite arguable that they are just a wrong interface - however, some of the world's people are fortunate enough to be accustomed to them already, which complicates matters considerably. Isaac From benjamin.franksen at bessy.de Mon Aug 13 18:11:58 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Mon Aug 13 18:03:54 2007 Subject: [Haskell-cafe] Re: Re: Language support for imperative code. Was: Re: monad subexpressions References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> <46BF4BD8.9080809@metamilk.com> <46C0CCEB.2060505@metamilk.com> Message-ID: Brian Hulley wrote: > Brian Hulley wrote: >> apfelmus wrote: >>> Brian Hulley schrieb: >>>> main = do >>>> buffer <- createBuffer >>>> edit1 <- createEdit buffer >>>> edit2 <- createEdit buffer >>>> splitter <- createSplitter (wrapWidget edit1) (wrapWidget >>>> edit2) >>>> runMessageLoopWith splitter >>>> >>>> ... Thus the ability to abstract mutable state gives to my mind by >>>> far the best solution. >>> >>> I'm not sure whether mutable state is the real goodie here. I think >>> it's the ability to indpendently access parts of a compound state. >>> http://www.st.cs.ru.nl/papers/2005/eves2005-FFormsIFL04.pdf >> >> This is indeed a real key to the problem. > Of course this is only one aspect of the problem... > > Thinking about this a bit more, and just so this thought is recorded for > posterity (!) and for the benefit of anyone now or in a few hundred > years time, trying to solve "Fermat's last GUI", the object oriented > solution allows the buffer object to do anything it wants, so that it > could negotiate a network connection and implement the interface based > on a shared network buffer for example, without needing any changes to > the client code above, so a functional gui would need to have the same > flexibility to compete with the OO solution. I'd be careful. Introducing a network connection into the equation makes the object (its methods) susceptible to a whole new bunch of failure modes; think indefinite delays, connection loss, network buffer overflow, etc etc. It may be a mistake to abstract all that away; in fact I am convinced that the old Unix habit of sweeping all these failure modes and potentially long delays under a big carpet named 'file abstraction' was a bad idea to begin with. The ages old and still not solved problems with web browsers hanging indefinitely (w/o allowing any GUI interaction) while name resolution waits for completion is only the most prominent example. Cheers Ben From benjamin.franksen at bessy.de Mon Aug 13 18:24:11 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Mon Aug 13 18:16:03 2007 Subject: [Haskell-cafe] Re: Re: Explaining monads References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> <1FB24845-06B7-460E-97A6-368BE0BA0BF0@ece.cmu.edu> Message-ID: Brandon S. Allbery KF8NH wrote: > On Aug 13, 2007, at 16:29 , Benjamin Franksen wrote: >> Let's take the simplest example: Maybe. The effect in question is the >> premature abortion of a computation (when Nothing is returned). And of >> course Maybe sequences these effects, that's what you use it for: the >> _first_ action to be encountered that returns Nothing aborts the >> computation. Clearly sequencing goes on here. > > Clearly it does, but not as a side effect of the *monad*. It's > ordinary Haskell data dependencies at work here, not some mystical > behavior of a monad. I can't remember claiming that Monads have any mystic abilities. In fact, these Monads are implemented in such a way that their definition /employs/ data dependencies to enforce a certain sequencing of effects. I think that is exactly the point, isn't it? >> What about State? The effect is reading/writing the state. Again, >> the State >> Monad takes care that these effects get sequenced, and again that's >> what >> you expect it to do for you. > > No, I expect it to carry a value around for me. If I carry that > value around myself instead of relying on the monad to do it for me, > *the calculation still gets sequenced by the data dependencies*. Of course, you can unfold (itso inline) bind and return (or never use them in the first place). Again, nobody claimed Monads do the sequencing by employing Mystic Force (tm); almost all Monads can be implemented in plain Haskell, nevertheless they sequence certain effects -- You Could Have Invented Them Monads Yourself ;-) The Monad merely captures the idiom, abstracts it and ideally implements it in a library for your convenience and for the benefit of those trying to understand what your code is supposed to achieve. She reads 'StateM ...' and immediately sees 'ah, there he wants to use some data threaded along for reading and writing'. Cheers Ben From rendel at rbg.informatik.tu-darmstadt.de Mon Aug 13 18:34:55 2007 From: rendel at rbg.informatik.tu-darmstadt.de (Tillmann Rendel) Date: Mon Aug 13 18:26:25 2007 Subject: [Haskell-cafe] Re: Explaining monads In-Reply-To: <20070813220101.GE644@darcs.net> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> <1FB24845-06B7-460E-97A6-368BE0BA0BF0@ece.cmu.edu> <20070813220101.GE644@darcs.net> Message-ID: <46C0DC8F.3090907@rbg.informatik.tu-darmstadt.de> David Roundy wrote: > It's the *effect* of a monad, not the *side* effect. The type of >>= > defines this dependency. And when you have a chain of dependencies, that > is sometimes referred to as a sequence. True, it's not mystical, but it's > still sequenced. How can a Haskell type define a data dependency? Haskell functions are non-strict, so they may choose to ignore arguments, and ignored arguments are not evaluated at all. > Try executing: > > do { x <- return 2; undefined; return (x*x); } > > in any monad you like, and you'll find that regardless of the *data* > dependencies (the return value of this monadic action is unambiguous), the > undefined is evaluated *before* the value 4 is returned. > runIdentity $ do {x <- return 2; undefined; return (x * x) } 4 Tillmann From brian at ithil.org Mon Aug 13 18:35:29 2007 From: brian at ithil.org (Brian Brunswick) Date: Mon Aug 13 18:27:09 2007 Subject: [Haskell-cafe] Re: Explaining monads In-Reply-To: <20070813220101.GE644@darcs.net> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> <1FB24845-06B7-460E-97A6-368BE0BA0BF0@ece.cmu.edu> <20070813220101.GE644@darcs.net> Message-ID: <6f680f6d0708131535g6b3769j3ca18d0df9a58e6b@mail.gmail.com> On 13/08/07, David Roundy wrote: > > Try executing: > > do { x <- return 2; undefined; return (x*x); } > > in any monad you like, and you'll find that regardless of the *data* > dependencies (the return value of this monadic action is unambiguous), the > undefined is evaluated *before* the value 4 is returned. > -- > > Prelude> :m + Control.Monad.Identity Prelude Control.Monad.Identity> runIdentity $ do { x <- return 2; undefined; return (x*x); } Loading package mtl-1.0 ... linking ... done. 4 -- Brian_Brunswick____brian@ithil.org____Wit____Disclaimer____!Shortsig_rules! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/74d8866c/attachment-0001.htm From derek.a.elkins at gmail.com Mon Aug 13 18:35:59 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Mon Aug 13 18:27:44 2007 Subject: [Haskell-cafe] Re: Explaining monads In-Reply-To: References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> Message-ID: <1187044559.5448.6.camel@derek-laptop> On Mon, 2007-08-13 at 22:29 +0200, Benjamin Franksen wrote: > Brian Brunswick wrote: > > One thing that I keep seeing people say (not you), is that > monads /sequence/ > > side effects. This is wrong, or at > > least a limited picture. > > > > /All/ of the above structures are about combining compatible things things > > together in a row. > > /None/ of them force any particular order of evaluation - that all comes > > from the particular instance. So its > > only a particular feature of IO that it sequences the side effects. Others > > don't - we can have a lazy State > > monad that just builds up big thunks. > > I am a bit astonished. > > Let's take the simplest example: Maybe. The effect in question is the > premature abortion of a computation (when Nothing is returned). And of > course Maybe sequences these effects, that's what you use it for: the > _first_ action to be encountered that returns Nothing aborts the > computation. Clearly sequencing goes on here. You are wrong. Proof: Let's take a simpler example: Identity. QED This also disproves David Roundy's statement that do x <- return 2; undefined; return (x*x) will hit bottom. Reader also does not sequence it's "actions". Writer is a kind of funny example. Certainly, any monad instance where (>>=) needs it's first argument to determine whether to continue, e.g. Maybe, Either, IO, Parser, Cont, List, Tree will clearly need to force it's first argument before continuing, but that's just the nature of the situation. From sebastian.sylvan at gmail.com Mon Aug 13 18:41:04 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Mon Aug 13 18:32:45 2007 Subject: [Haskell-cafe] A few questions on primes generating. In-Reply-To: <233457100708130819i7e14abc3q1e896264d4b8214c@mail.gmail.com> References: <200708132222225629298@gmail.com> <233457100708130819i7e14abc3q1e896264d4b8214c@mail.gmail.com> Message-ID: <3d96ac180708131541lc07a39ambbecee2438656355@mail.gmail.com> On 13/08/07, Pekka Karjalainen wrote: > On 8/13/07, L.Guo wrote: > > Hi All: > > Hello, > > > > > I am reading http://www.haskell.org/haskellwiki/Prime_numbers > > > > The code in sector "1 Bitwise prime sieve". > > > > I have 3 questions about it. > > > > 1) In function go, what does the number 46340 mean ? Is it sqrt(MAX_LONG) ? > > Yes, it appears so. In a 32 bit implementation I get: > > Prelude> sqrt $ fromIntegral (maxBound :: Int) > 46340.950001051984 > > > 2) We have this type definition : > > pureSieve :: Int -> Int > > Why there is no error (type mismatch) of this call in func main : > > pureSieve 10000000 > > If you have integer literals in your program, the compiler sees a > fromInteger in front of them. So the value is just converted to type > Int automatically, because that is expected here. > > You can give different numeric default declarations in your own > modules. Please see sections 10.3 (for overloaded literals) and 10.4 > (for defaults) here: > http://www.haskell.org/tutorial/numbers.html > > Sometimes you can get an overflow like this: > > Prelude> 100000000000000000000000 :: Int > -159383552 > > > 3) In main again, what does expression [| x |] mean ? Why this cannot be execute in > > GHCi ? > > It's Template Haskell, and is used there for some kind of optimisation > (I think). Template Haskell needs to be enabled with a command line > switch for it to work. Please see the documentation for more > information. It's section 7.6 in your User's Guide. > > Though in this case you can probably just remove it to try out the > program. Perhaps someone else can explain what actual effect it has > here. I think it just computes a single function call to pureSieve at compile time. I believe its origin is from making a point that when you stop comparing apples to apples it's easy to cheat (this code comes from a discussion on this list where someone insisted on adding optimizations to the, admittedly naive, algorithm in C# and comparing it without making the same optimizations in Haskell -- so someone, I forget who but I'm a search will turn it up, wrote a quick template Haskell "optimization" to make a point that we don't really get useful results unless we compare the same algorithms in both languages). In general you should probably ignore that TH bit and just call pureSieve normally. -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From derek.a.elkins at gmail.com Mon Aug 13 18:47:20 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Mon Aug 13 18:39:10 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <000001c7ddcf$d42323f0$7c696bd0$@be> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <49a77b7a0708110032k3f9d9f15v17be842233a30cab@mail.gmail.com> <46BE0734.3040308@mindspring.com> <12126170.post@talk.nabble.com> <000001c7ddcf$d42323f0$7c696bd0$@be> Message-ID: <1187045241.5448.16.camel@derek-laptop> On Mon, 2007-08-13 at 19:31 +0200, peterv wrote: > When I read "side-effects", I understand it as "unwanted effects", like > "aliasing", and "effects depending on the order of execution". I'm not sure > if my understanding here is correct. I hope Haskell does not allow > "side-effects" but only "effects", meaning the monads do not allow you to > write the typical ill-behaving code you get when doing real imperative > programming, enforcing a single wiring of execution, not allowing the > capture of the RealWorld object. In Concurrent Clean special compiler > support is present to enforce "uniqueness typing", and in Haskell special > compiler support is available to make the RealWorld object not available at > runtime (so e.g. you can't put the RealWorld object in a list). Is this > correct? Monads certainly do allow "side-effects" in that way. Heck, without allowing aliasing there wouldn't be much to compel the use of mutability. Aliasing is the great boon and great curse of imperative programming. Order of execution issues are tricky. On the one hand, you must always (directly or indirectly) specify the order of execution, so technically there's no uncertainty. On the other hand, there are two distinct definitions of liftM2, liftM2'1 f ma mb = do a <- ma; b <- mb; return (f a b) -- and liftM2'2 f ma mb = do b <- mb; a <- ma; return (f a b) Note that order of -evaluation- is moot (at least as much as it is for any term). Laziness does not come into it (unless you use lazy IO, in which case you get what you deserve.) > BTW: What is the correct word in Haskell for "object"? I mean the (lazy) > value you get when evaluating a data constructor? What you said doesn't really make much sense, but I think the(/a) word you want is a "thunk". From isaacdupree at charter.net Mon Aug 13 18:46:17 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Mon Aug 13 18:49:35 2007 Subject: [Haskell-cafe] Re: Re: Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> <46BF4BD8.9080809@metamilk.com> <46C0CCEB.2060505@metamilk.com> Message-ID: <46C0DF39.5030703@charter.net> Benjamin Franksen wrote: > I'd be careful. Introducing a network connection into the equation makes the > object (its methods) susceptible to a whole new bunch of failure modes; > think indefinite delays, connection loss, network buffer overflow, etc etc. > It may be a mistake to abstract all that away; in fact I am convinced that > the old Unix habit of sweeping all these failure modes and potentially long > delays under a big carpet named 'file abstraction' was a bad idea to begin > with. The ages old and still not solved problems with web browsers hanging > indefinitely (w/o allowing any GUI interaction) while name resolution waits > for completion is only the most prominent example. IMO it's just a terribly stupid bug in the best web browsers. Maybe inefficient, poorly, or not-at-all-used multithreading? "file abstraction" has its points. We just need a (type-level?) clear-to-program-with distinction between operations that may block indefinitely, and operations that have particular bounds on their difficulty. Although, modern OSes try to balance too many things, don't usually make any such hard real-time guarantees, in favor of everything turning out more-or-less correct eventually. Back to "file abstraction" - well, considering the benefits of mounting remote systems as a filesystem. The hierarchy abstraction of the filesystem didn't stay the same performance characteristics... And all kinds of potential problems result too, when the connection breaks down! How do you program with all those error conditions explicitly? It is difficult. You need libraries to do it well - and I'm not at all sure whether there exist such libraries yet! I mean, programs are much too complicated already without infesting them with a lot of special cases. > indefinite delays I can create with `someCommand | haskellProgram` too > connection loss Is there a correct way to detect this? I find it rather odd when I lose my IRC connection for a moment and then it comes back a moment later (Wesnoth games are worse, apparently, as they don't reconnect automatically). I often prefer considering them an indefinite delay. > network buffer overflow that is: too much input, not processing it fast enough? (or similar). Memory size limitations are considerably unhandled in programs of all sorts, not just networked ones, though they(networked) may suffer the most. We wish we had true unlimited-memory Turing machines :) ...this is possibly the most difficult issue to deal with formally. Probably requires limiting input data rates artificially. Isaac From dpiponi at gmail.com Mon Aug 13 19:24:58 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Mon Aug 13 19:16:38 2007 Subject: [Haskell-cafe] Re: Explaining monads In-Reply-To: <20070813220101.GE644@darcs.net> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> <1FB24845-06B7-460E-97A6-368BE0BA0BF0@ece.cmu.edu> <20070813220101.GE644@darcs.net> Message-ID: <625b74080708131624gf75ef28h280b1f6086140d94@mail.gmail.com> On 8/13/07, David Roundy wrote: > Try executing: > > do { x <- return 2; undefined; return (x*x); } > > in any monad you like instance Monad M where return a = M a ~(M a) >>= f = f a Or is that cheating? -- Dan From donn at drizzle.com Mon Aug 13 19:39:49 2007 From: donn at drizzle.com (Donn Cave) Date: Mon Aug 13 19:31:31 2007 Subject: [Haskell-cafe] Re: Re: Language support for imperative code. Was: Re: monad subexpressions In-Reply-To: Message-ID: On Tue, 14 Aug 2007, Benjamin Franksen wrote: ... > I'd be careful. Introducing a network connection into the equation makes the > object (its methods) susceptible to a whole new bunch of failure modes; > think indefinite delays, connection loss, network buffer overflow, etc etc. > It may be a mistake to abstract all that away; in fact I am convinced that > the old Unix habit of sweeping all these failure modes and potentially long > delays under a big carpet named 'file abstraction' was a bad idea to begin > with. The ages old and still not solved problems with web browsers hanging > indefinitely (w/o allowing any GUI interaction) while name resolution waits > for completion is only the most prominent example. Ironically, the place where all this sweeping under the carpet has caused me personally the most irritation is one of the most appealing file abstractions - remote disk filesystems, NFS. In any case, I agree (I think) that a sophisticated user interface needs to deal with time. I think that's a key motivation for reactive object approaches. It has to be considered part of the equation, along with the rest of the I/O situation, if you're trying to reason about it that way. Donn Cave, donn@drizzle.com From ariep at xs4all.nl Mon Aug 13 19:46:29 2007 From: ariep at xs4all.nl (Arie Peterson) Date: Mon Aug 13 19:38:09 2007 Subject: [Haskell-cafe] Re: Explaining monads In-Reply-To: <625b74080708131624gf75ef28h280b1f6086140d94@mail.gmail.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> <1FB24845-06B7-460E-97A6-368BE0BA0BF0@ece.cmu.edu> <20070813220101.GE644@darcs.net> <625b74080708131624gf75ef28h280b1f6086140d94@mail.gmail.com> Message-ID: <8150.213.84.177.94.1187048789.squirrel@webmail.xs4all.nl> On 8/13/07, David Roundy wrote: | Try executing: | | do { x <- return 2; undefined; return (x*x); } | | in any monad you like It's not just the identity monad: Prelude> :m +Control.Monad.State Prelude Control.Monad.State> flip evalState () $ do { x <- return 2; undefined; return (x*x); } 4 Regards, Arie From benjamin.franksen at bessy.de Mon Aug 13 20:13:22 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Mon Aug 13 20:05:16 2007 Subject: [Haskell-cafe] Re: Re: Explaining monads References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> <1187044559.5448.6.camel@derek-laptop> Message-ID: Derek Elkins wrote: > On Mon, 2007-08-13 at 22:29 +0200, Benjamin Franksen wrote: >> Brian Brunswick wrote: >> > One thing that I keep seeing people say (not you), is that >> monads /sequence/ >> > side effects. This is wrong, or at >> > least a limited picture. >> > >> > /All/ of the above structures are about combining compatible things things >> > together in a row. >> > /None/ of them force any particular order of evaluation - that all comes >> > from the particular instance. So its >> > only a particular feature of IO that it sequences the side effects. Others >> > don't - we can have a lazy State >> > monad that just builds up big thunks. >> >> I am a bit astonished. >> >> Let's take the simplest example: Maybe. The effect in question is the >> premature abortion of a computation (when Nothing is returned). And of >> course Maybe sequences these effects, that's what you use it for: the >> _first_ action to be encountered that returns Nothing aborts the >> computation. Clearly sequencing goes on here. > > You are wrong. Proof: Let's take a simpler example: Identity. QED I don't accept this proof. Note the wording: 'Monads sequence (certain, monad specific) effects'. Identity has no effects, ergo no sequencing has to happen. I didn't claim that /all/ monadic actions are (necessarily) sequenced. > This also disproves David Roundy's statement that > do x <- return 2; undefined; return (x*x) will hit bottom. > > Reader also does not sequence it's "actions". Ok, I admit defeat now ;-) Monads in general /allow/ sequencing of (certain) effects, but it is not necessary for a monad to do so. > Writer is a kind of funny example. In which way? > Certainly, any monad instance where (>>=) needs it's first argument to > determine whether to continue, e.g. Maybe, Either, IO, Parser, Cont, > List, Tree will clearly need to force it's first argument before > continuing, but that's just the nature of the situation. Don't forget State, clearly it sequences actions even though it always continues; but maybe 'sequencing' is too strong a word: Just as with Reader, a sequence of reads (with no writes in between) may actually happen in any order, State imposes strict order on groups of adjacent reads and all (single) writes, correct? Ok, I think I understand where I was misled: I took the means for the end. There are many monads that impose a certain order on (some) effects; but this is done only as far as necessary to maintain X, whatever X may be, maybe X is just the monad laws? What about: The imperative way always imposes a sequencing of actions, period. Monads in Haskell (except IO which is just imperative programming) allow us to impose ordering on effects only partially, ideally only where necessary. Thanks for further enlightening me. Hey, I just said that sequencing is a means, not an end, but maybe even this is not necessarily true. I imagine a 'Sequence Monad' whose only effect would be to order evaluation... would that be possible? Or useful? Cheers Ben From gregorypropf at yahoo.com Mon Aug 13 20:16:36 2007 From: gregorypropf at yahoo.com (Gregory Propf) Date: Mon Aug 13 20:08:15 2007 Subject: [Haskell-cafe] Explaining monads Message-ID: <234992.65432.qm@web31410.mail.mud.yahoo.com> I made this mistake myself at first too. It seems that the Monad = "side effect machine" error is common to Haskell newbies. Probably to do with the fact that the first thing every programmer wants to do is write a hello world program and for that you need the IO Monad which requires some explanation of how a Monad can allow for side effects (at least the IO Monad). - Greg ----- Original Message ---- From: peterv To: Kim-Ee Yeoh ; haskell-cafe@haskell.org Sent: Monday, August 13, 2007 10:31:48 AM Subject: RE: [Haskell-cafe] Explaining monads Ronald Guida wrote: > > Given the question "What is a Monad", I would have to say "A Monad is > a device for sequencing side-effects." > There are side-effects and there are side-effects. If the only monad you use is Maybe, the only side-effect you get is a slight warming of the CPU. .... "Side-effects" is a piece of linguistic cruft played fast-and-loose by too many people in this game. "Sequencing" suffers the same disease. ____________________________________________________________________________________ Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070813/8ce02e1a/attachment.htm From dpiponi at gmail.com Mon Aug 13 20:57:11 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Mon Aug 13 20:48:51 2007 Subject: [Haskell-cafe] Re: Re: Explaining monads In-Reply-To: References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> <1187044559.5448.6.camel@derek-laptop> Message-ID: <625b74080708131757h249f2967v88e05263d353a4c3@mail.gmail.com> On 8/13/07, Benjamin Franksen wrote: > Ok, I admit defeat now ;-) Monads in general /allow/ sequencing of (certain) > effects, but it is not necessary for a monad to do so. I'm sure I said that 300 or so posts ago :-) Here's an example that might help make some of this explicit. Suppose I have a function f :: a -> b -> c. Now suppose I have some values "in a monad": x :: m a y :: m b How do I lift f so I can apply it to x and y and get a value of type m c? Obviously I can't just write f x y. There's an obvious solution that comes to mind: do x' <- x y' <- y return $ f x' y' But there's another solution: do y' <- y x' <- x return $ f x' y' So in order to lift f I was forced to make an explicit decision about the order in which I wanted to process x and y. (I think of >>= as a kind of bottleneck that forces you to compute the arguments to f one at a time in a particular order - but there are already too many metaphors flying around so maybe you should ignore that.) Information about that decision now becomes available to the monad's implementation. If you want, you can use this information to implement 'sequencing' (whatever that means). But you're also free to ignore it. If you do ignore it then you have a commutative monad, with Reader being the best known example. It's just like ordinary monoids. The very act of writing x*y imposes an order on x and y. You can use this to define binary operators that can make use of this ordering. But the most familiar monoid operators (addition and multiplication of course) are commutative and order doesn't matter. It'd be cool to have a notation that didn't force you to put one argument or the other first. (Well, I know of one, but it's a bit wacky: http://www.lawsofform.org/interpretations.html) -- Dan From benjamin.franksen at bessy.de Mon Aug 13 21:06:35 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Mon Aug 13 20:58:35 2007 Subject: [Haskell-cafe] Re: Re: Re: Language support for imperative code. Was: Re: monad subexpressions References: <00ab01c7d5bd$24eff7b0$14217ad5@cr3lt> <016d01c7d5e9$0eec4550$14217ad5@cr3lt> <1955583864.20070804083549@gmail.com> <46B9DAA7.4070006@metamilk.com> <46BF4BD8.9080809@metamilk.com> <46C0CCEB.2060505@metamilk.com> <46C0DF39.5030703@charter.net> Message-ID: Isaac Dupree wrote: > Benjamin Franksen wrote: >> I'd be careful. Introducing a network connection into the equation makes the >> object (its methods) susceptible to a whole new bunch of failure modes; >> think indefinite delays, connection loss, network buffer overflow, etc etc. >> It may be a mistake to abstract all that away; in fact I am convinced that >> the old Unix habit of sweeping all these failure modes and potentially long >> delays under a big carpet named 'file abstraction' was a bad idea to begin >> with. The ages old and still not solved problems with web browsers hanging >> indefinitely (w/o allowing any GUI interaction) while name resolution waits >> for completion is only the most prominent example. > > IMO it's just a terribly stupid bug in the best web browsers. Maybe > inefficient, poorly, or not-at-all-used multithreading? Explicitly creating a (system) thread with all the overhead (in computing resources, as well as code complexity) only because the system interface is broken? Yes, of course, necessary, but not nice. An extra parameter for a continuation would be a lot more light-weight and would also make explicit that we must expect the call to be delayed. I think the main reason why systems don't regularly employ this scheme is that it is so tedious to work with closures in low-level languages like C. > "file abstraction" has its points. We just need a (type-level?) > clear-to-program-with distinction between operations that may block > indefinitely, and operations that have particular bounds on their > difficulty. Although, modern OSes try to balance too many things, don't > usually make any such hard real-time guarantees, in favor of everything > turning out more-or-less correct eventually. Back to "file abstraction" > - well, considering the benefits of mounting remote systems as a > filesystem. The hierarchy abstraction of the filesystem didn't stay the > same performance characteristics... And all kinds of potential problems > result too, when the connection breaks down! Indeed, as I have experienced multiple times: NFS clients completely hanging for minutes, enforcing coffee break for the whole office! Not that I would mind a coffee break now or then, but it tends to happen in the middle of an attempt to fix a critical bug in the production system... > How do you program with all those error conditions explicitly? It is > difficult. You need libraries to do it well - and I'm not at all sure > whether there exist such libraries yet! I mean, programs are much too > complicated already without infesting them with a lot of special cases. What I would like to have is a clear distinction, apparent in the type, between actions that can be expected to terminate fast and with certainty (apart from broken hardware, that is) and others which are inherently insecure and may involve considerable or even indefinite delays. The latter should accept a continuation argument. However, there is obviously a judgement call involved here. Thus, the system should be flexible enough to allow to treat the same resource either as one or the other, depending on the demands of the application. There may be situations where a name lookup can safely be treated as a synchronous operation (e.g. a script run as a cron job); in other situations one might need to regard even local bus access to some I/O card as asynchronous. > > indefinite delays > I can create with `someCommand | haskellProgram` too Yes, user input as well as reading from a pipe should be handled like a network connection: call my continuation whenever input is available. > > connection loss > Is there a correct way to detect this? There are many ways, typically involving some sort of beacons. Anyway, if all else fails the operation times out. > I find it rather odd when I lose > my IRC connection for a moment and then it comes back a moment later > (Wesnoth games are worse, apparently, as they don't reconnect > automatically). I often prefer considering them an indefinite delay. Right: The user (the application) is in the best position to decide how long to wait before an operation times out. > > network buffer overflow > that is: too much input, not processing it fast enough? (or similar). Yeah, though usually the other way around, i.e. too much output and the system can't send it fast enough (maybe because the other side is slow in accepting data, or because the connection is bad, or whatever). > Memory size limitations are considerably unhandled in programs of all > sorts, not just networked ones, though they(networked) may suffer the > most. It is usually not a problem with modern desktop or server systems, rather with so called 'real-time' OSes, where everything tends to be statically allocated. > We wish we had true unlimited-memory Turing machines :) ...this > is possibly the most difficult issue to deal with formally. Probably > requires limiting input data rates artificially. That's what one does (or tries to do, until some arbitrary network problem, ill-configured switch or whatever, slows down the network just a bit more and for just a bit longer than you imagined could happen and the system needs to be rebooted). Anyway, scrap the network buffer overflow, I mentioned it only because we've been bitten by it just today. Cheers Ben From ajb at spamcop.net Mon Aug 13 22:12:58 2007 From: ajb at spamcop.net (ajb@spamcop.net) Date: Mon Aug 13 22:04:36 2007 Subject: [Haskell-cafe] A few questions on primes generating. In-Reply-To: <46C0ADA4.8080807@btinternet.com> References: <200708132222225629298@gmail.com> <200708140046.00650.dry.green.tea@gmail.com> <200708132323506876214@gmail.com> <20070813153110.GB3543@localhost.localdomain> <46C0ADA4.8080807@btinternet.com> Message-ID: <20070813221258.9fv74ircsg0wkk0k@webmail.spamcop.net> G'day all. Quoting Andrew Coppin : > So many other programming languages allow weird things to happen with > numeric overflows... it would be nice if Haskell didn't. It would nice if CPUs supported trapping integer arithmetic. Cheers, Andrew Bromage From newsham at lava.net Mon Aug 13 22:52:28 2007 From: newsham at lava.net (Tim Newsham) Date: Mon Aug 13 22:44:09 2007 Subject: [Haskell-cafe] Small proof intro Message-ID: I put together a small intro lesson on proving haskell code using quickcheck, equational reasoning and Isabelle/HOL. Its very elementary, but might be of interest to some people here. http://www.thenewsh.com/%7Enewsham/formal/reverse/ Feedback is appreciated. Tim Newsham http://www.thenewsh.com/~newsham/ From ronguida at mindspring.com Mon Aug 13 23:53:33 2007 From: ronguida at mindspring.com (Ronald Guida) Date: Mon Aug 13 23:43:07 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <234992.65432.qm@web31410.mail.mud.yahoo.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> Message-ID: <46C1273D.50303@mindspring.com> Ronald Guida wrote: > Given the question "What is a Monad", I would have to say "A Monad is > a device for sequencing side-effects." peterv wrote: > "Side-effects" is a piece of linguistic cruft played fast-and-loose > by too many people in this game. "Sequencing" suffers the same > disease. Gregory Propf wrote: > I made this mistake myself at first too. It seems that the Monad = > "side effect machine" error is common to Haskell newbies. Probably > to do with the fact that the first thing every programmer wants to > do is write a hello world program and for that you need the IO Monad > which requires some explanation of how a Monad can allow for side > effects (at least the IO Monad). - Greg Eariler in this thread, I had a conversation with several people regarding monads and arrows. My goal was to try to come up with a brief explanation. I realized that "sequencing side-effects" is a simplistic and incorrect view, so now I'm thinking in terms of DSELs. I have heard that writing a monad tutorial is something people do when they finally understand monads. I interpret this observation to mean that either (1) monads (and arrows) are just difficult things, or (2) most of the existing explanations and tutorials are somehow inadequate or incomplete. My present goal is to understand monads well enough to be able to explain them to others. I wonder if it's possible to create a tutorial that explains monads well enough so that they just "make sense" or "click" for people. Here is the brief explanation I came up with: > Arrows and monads are abstract data types used to construct Domain > Specific Embedded Languages (DSELs) within Haskel. A simple arrow > provides a closed DSEL. A monad is a special type of arrow that > creates an open DSEL by allowing users to embed arbitrary Haskel > within it. Is this an accurate explanation? I hate to feed a fire, but is "Domain Specific Embedded Language" a well-defined phrase, or is it just another example of linguistic cruft? If DSEL is cruft, then is there a better way to briefly explain monads and arrows? Also, is this a /useful/ explanation, or have I simply hidden the complexity by invoking the concepts of ADTs and DSELs? -- Ron From a.biurvOir4 at asuhan.com Tue Aug 14 03:50:22 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Tue Aug 14 03:42:01 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C1273D.50303@mindspring.com> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> Message-ID: <12140216.post@talk.nabble.com> Ronald Guida wrote: > > Here is the brief explanation I came up with: > > Arrows and monads are abstract data types used to construct Domain > > Specific Embedded Languages (DSELs) within Haskel. A simple arrow > > provides a closed DSEL. A monad is a special type of arrow that > > creates an open DSEL by allowing users to embed arbitrary Haskel > > within it. > > Is this an accurate explanation? I hate to feed a fire, but is > "Domain Specific Embedded Language" a well-defined phrase, or is it > just another example of linguistic cruft? > Neither. It's the latest buzzword, joining the likes of AOP and Generics. Haskell has an opportunity to ride the DSEL bandwagon, and like most such opportunities it can take her where she don't want to go. Ronald Guida wrote: > > Also, is this a /useful/ explanation, or have I simply hidden the > complexity by invoking the concepts of ADTs and DSELs? > It certainly has a nice spin. I've nominated you to the Monad Marketing Team already. -- View this message in context: http://www.nabble.com/Explaining-monads-tf4244948.html#a12140216 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From apfelmus at quantentunnel.de Tue Aug 14 03:53:33 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Tue Aug 14 03:45:29 2007 Subject: [Haskell-cafe] Re: a regressive view of support for imperative programming in Haskell In-Reply-To: <20070813161043.GB3638@localhost.localdomain> References: <46BA0977.2040207@yale.edu> <20070808204103.GU13960@darcs.net> <20070809185658.GF30903@darcs.net> <20070813145030.GA3395@localhost.localdomain> <20070813161043.GB3638@localhost.localdomain> Message-ID: Stefan O'Rear wrote: > apfelmus wrote: >> >> My assumption is that we have an equivalence >> >> forall a,b . m (a -> m b) ~ (a -> m b) >> >> because any side effect executed by the extra m on the outside can well >> be delayed until we are supplied a value a. Well, at least when all >> arguments are fully applied, for some notion of "fully applied" > > I figured that wouldn't be a problem since our values don't escape, and > the functions we define all respect the embedding... More formally: > > Projections and injections: proj :: Monad m => m (a -> m b) -> (a -> m b) > proj ma = \x -> ma >>= \fn' -> fn' x > inj fn = return fn > > Define an equivalence relation: > > ma ? mb <-> proj ma = proj mb > > Projection respects equivalence: > > ma ? mb -> proj ma = proj mb (intro ->) > ma ? mb => proj ma = proj mb (equiv def) > proj ma = proj mb => proj ma = proj mb (assumption) > > Application respects equivalence: Yeah, that's the right approach, but it has a few typos. The correct version is (@) :: Monad m => m (a -> m b) -> m a -> m b (@) ma = \x -> x >>= proj ma Formulating (@) in terms of proj ma is a very clever idea since it follows immediately that ma @ x = ma' @ x iff proj ma = proj ma' iff ma ? ma' In other words, when viewed through @ and proj only, equivalent actions give equivalent results. The main point is that this does not hold for the other curry-friendly type m a -> m b proj :: Monad m => (m a -> m b) -> (a -> m b) proj f = f . return (@) :: Monad m => (m a -> m b) -> m a -> m b (@) = id ma ? ma' iff proj ma = proj ma' since those functions may execute their argument multiple times. So, here's the counterexample once :: Monad m => m A -> m A once = id twice :: Monad m => m A -> m A twice x = x >> once x Now, we have proj once = return = proj twice but effect :: IO () -- a given effect effect = putStrLn "Kilroy was here!" once @ effect = effect ? twice @ effect = effect >> effect The same can be done for several arguments, along the lines of proj2 :: m (a -> m (b -> m c)) -> (a -> b -> m c) proj2 f = proj . (proj f) app2 :: m (a -> m (b -> m c)) -> (m a -> m b -> m c) app2 f mx my = (f @ mx) @ my = my >>= proj (mx >>= proj f) = my >>= \y -> mx >>= \x -> proj2 f x y and similar results. Regards, apfelmus From ithika at gmail.com Tue Aug 14 03:56:28 2007 From: ithika at gmail.com (Dougal Stanton) Date: Tue Aug 14 03:48:11 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C1273D.50303@mindspring.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> Message-ID: <2d3641330708140056w7701e0a3mf5ba7d4a8a4a6a9b@mail.gmail.com> On 14/08/07, Ronald Guida wrote: > My present goal is to understand monads well enough to be able to > explain them to others. I wonder if it's possible to create a > tutorial that explains monads well enough so that they just "make > sense" or "click" for people. It seems everyone wants to do this, with not much success! :-( >From reading this thread (piecemeal rather than in one concentrated session) I get the impression that no-one agrees on what, if anything, a monad is. If there were a wiki page What_Is_A_Monad and all these ideas were whittled down whenever a counter-proof (such as Identity or Reader) were raised --- what would be left? I get the impression it would look like this: > (return x) >>= f == f x > m >>= return == m > (m >>= f) >>= g == m >>= (\x -> f x >>= g) And then where would we be? ;-) I say all this from the point of view of someone who has a reasonably robust intuitive idea of monads that still fails to encompass the List monad. I too would like to understand the overall idea to this monad malarkey... Cheers, D. From j.vimal at gmail.com Tue Aug 14 04:42:33 2007 From: j.vimal at gmail.com (Vimal) Date: Tue Aug 14 04:34:12 2007 Subject: [Haskell-cafe] Parsec: Parenthesized expressions and more! Message-ID: Hi I was trying out some parsing with parsec. I tried: Accepting proper parenthesized expressions, this was the code: parens :: Parser () parens = do char '(' parens char ')' parens <|> return () Implementing basically: S -> (S)S | e. I doubt the fact that 'e' was actually considered, because the program seems to be accepting all strings of the form ())*. Did I go wrong somewhere? I guess this could be because, the input was "partially" accepted. Can I force it to derive the entire input string? And, btw, is there a method to implement an epsilon production? I tried do { string "" ; rules ... } And it didn't seem to work. I am also trying out this problem just for fun, but I seem to be getting wrong answers! http://spoj.pl/problems/FOOL Maybe I implemented something wrong. So, i will wait for some comments on the above parsing, and try one more time before I ask questions on that :D Cheers -- -- Vimal Department of Computer Science and Engineering Indian Institute of Technology Madras From Christian.Maeder at dfki.de Tue Aug 14 05:00:31 2007 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Tue Aug 14 04:52:19 2007 Subject: [Haskell-cafe] Re: Parsec: Parenthesized expressions and more! In-Reply-To: References: Message-ID: <46C16F2F.4080806@dfki.de> Vimal wrote: > Hi > > I was trying out some parsing with parsec. I tried: > Accepting proper parenthesized expressions, this was the > code: > > parens :: Parser () > parens = do > char '(' > parens > char ')' > parens > <|> return () I would indent "<|> return ()" a bit less: ... parens <|> return () Use "parens >> eof" to test for full string consumption. C. From bertram.felgenhauer at googlemail.com Tue Aug 14 07:51:00 2007 From: bertram.felgenhauer at googlemail.com (Bertram Felgenhauer) Date: Tue Aug 14 07:42:49 2007 Subject: [Haskell-cafe] Re: Explaining monads In-Reply-To: References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <12087081.post@talk.nabble.com> <46BD2E4B.3010202@mindspring.com> <6f680f6d0708130431u1ebc3018ne39a7f2f4dc7a1dc@mail.gmail.com> Message-ID: <20070814115100.GA4587@zombie.inf.tu-dresden.de> Benjamin Franksen wrote: > Brian Brunswick wrote: > > One thing that I keep seeing people say (not you), is that > > monads /sequence/ side effects. This is wrong, or at > > least a limited picture. > > > > /All/ of the above structures are about combining compatible things things > > together in a row. > > I am a bit astonished. > > Let's take the simplest example: Maybe. The effect in question is the > premature abortion of a computation (when Nothing is returned). And of > course Maybe sequences these effects, that's what you use it for: the > _first_ action to be encountered that returns Nothing aborts the > computation. Clearly sequencing goes on here. "sequencing" is an overloaded term. Dan Weston said in an earlier thread that monads sequence denotationally, but not necessarily operationally. Brian makes the same point. I also believe that this is an important distinction to make. > I won't talk about List Monad because I always had difficulty understanding > the List Monad. Maybe that's because the distinction of denotational and operational sequencing actually matters for the list monad. I'll try to explain. Consider a >>= b >>= c This is equivalent to [()] >> a >>= b >>= c We can think of this as defining a tree with three levels: - () at the root. - 'a' produces the children of the root. - 'b' and 'c' each add another level to the tree - given a node from the previous level, they produce the children of that node. In other words, you *specify* a breadth first traversal of that tree, and you *sequence* the subsequent levels of that traversal. The catch here is lazy evaluation - each intermediate list of the breadth first traversal is produced incrementally so what you get at run time is actually a *depth first* traversal. As a result, there's no nice sequencing anymore, operationally. HTH, Bertram P.S. The explanation I gave above is deliberately simplified - it's actually only an explanation of the list *arrow*. The list monad allows the structure of the traversal to be different for various subtrees of a node. Consider [()] >> [1,2,3] >>= \n -> if odd n then [n] else [1..n] >>= \m -> [n+m] which produces the following tree: () +- n=1 | `- 1 +- n=2 | +- m=1 | | `- 3 | `- m=2 | `- 4 `- n=3 `- 3 This tree no longer has uniform levels. In my opinion the best way to think of this is operationally, as a depth first traversal. From bf3 at telenet.be Tue Aug 14 09:44:32 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Tue Aug 14 09:36:09 2007 Subject: [Haskell-cafe] Converting Emacs syntax coloured Haskell code to HTML Message-ID: <002901c7de79$3edb3170$bc919450$@be> I noticed many code snippets on the wiki that have syntax colouring. How is this done? Can I convert syntax coloured code from Emacs to HTML? I'm using the Haskell mode for Emacs to get the syntax colouring. I'm writing a "monads for C# programmers tutorial" (oh nooooooooo) and would like to use this feature. Of course I won't publish this tutorial before sending it to this mailing list, because when a newbie writes a tutorial, it is usually a disaster ;-) But the feedback I get from this community is super handy (that is when it is not PhD talk which I don't understand ;), so I guess comments on this tutorial will give me a better understanding. Thanks, Peter -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/698d5ae5/attachment.htm From alfonso.acosta at gmail.com Tue Aug 14 09:52:49 2007 From: alfonso.acosta at gmail.com (Alfonso Acosta) Date: Tue Aug 14 09:44:27 2007 Subject: [Haskell-cafe] Converting Emacs syntax coloured Haskell code to HTML In-Reply-To: <002901c7de79$3edb3170$bc919450$@be> References: <002901c7de79$3edb3170$bc919450$@be> Message-ID: <6a7c66fc0708140652w34d5e7dbp417885f78cf08461@mail.gmail.com> M-x htmlize-buffer On 8/14/07, Peter Verswyvelen wrote: > > > > > I noticed many code snippets on the wiki that have syntax colouring. > > > > How is this done? Can I convert syntax coloured code from Emacs to HTML? > > > > I'm using the Haskell mode for Emacs to get the syntax colouring. > > > > I'm writing a "monads for C# programmers tutorial" (oh nooooooooo) and would > like to use this feature. > > > > Of course I won't publish this tutorial before sending it to this mailing > list, because when a newbie writes a tutorial, it is usually a disaster ;-) > > > > But the feedback I get from this community is super handy (that is when it > is not PhD talk which I don't understand ;), so I guess comments on this > tutorial will give me a better understanding. > > > > Thanks, > > Peter > > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From v.dijk.bas at gmail.com Tue Aug 14 10:00:42 2007 From: v.dijk.bas at gmail.com (Bas van Dijk) Date: Tue Aug 14 09:52:21 2007 Subject: [Haskell-cafe] Converting Emacs syntax coloured Haskell code to HTML In-Reply-To: <002901c7de79$3edb3170$bc919450$@be> References: <002901c7de79$3edb3170$bc919450$@be> Message-ID: On 8/14/07, Peter Verswyvelen wrote: > I noticed many code snippets on the wiki that have syntax colouring. > > How is this done? Can I convert syntax coloured code from Emacs to HTML? Look at HsColour: http://www.cs.york.ac.uk/fp/darcs/hscolour/ regards, Bas van Dijk From lanny at cisco.com Tue Aug 14 10:55:11 2007 From: lanny at cisco.com (Lanny Ripple) Date: Tue Aug 14 10:48:26 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C1273D.50303@mindspring.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> Message-ID: <46C1C24F.1030905@cisco.com> Having just gone through all the tutorials and things (again but this time I think it stuck) the Haskell community is on the wrong track as far as teaching Monads to new programmers. If I were teaching addition and multiplication to children I wouldn't start with, "We'll begin by defining an algebraic structure named a "Group". From there we'll expand our concept to a "Ring" and "Field". A group is a set and a binary operator usually named "+" (or sometimes "*") such that...". No no no. You start with, "You all know how to count from one to 10. If we have 1 item and we 'add' another 1 item we have 2 items. We write this 1+1=2." The tutorials seriously need to step back and start with something like, "To enforce order of evaluation we evaluate closures* returning a defined type. The first closure will feed its result to the second which will in turn feed it's result to the third. Since the third closure can't be evaluated without having the results from the second and first (and thus they had to be evaluated earlier in time) we get a defined evaluation sequence. Here are some examples..." (* Even using the word 'closure' is scary for those not familiar with them.) Then, like "Monads For Functional Programming" (the paper that finally clicked Monads for me) you point out that evaluating all these closures returning a defined type in various ways form a structure (which you can then explain) and we can use that structure and change out the underlying effect(s) as needed. Now of course if your new programmer has the the necessary background you can throw them in the deep end. But don't do that to someone coming at the language from something like Java learned out of a business degree course. (My background is a CS degree with math minor and it still took two go-s at Haskell before I got as far as understanding what folks were talking about with Monads. Wish I had found Wadler's MFFP the first time around.) Where are the shallow end tutorials? (Don't get me wrong. The tutorials are good but there is also a place for the "learn-by-rote with lots of examples" ones too.) $0.02, -ljr PS - Not so much directed at Ronald's post but his was convenient to get me on my soapbox. Ronald Guida wrote: > My present goal is to understand monads well enough to be able to > explain them to others. I wonder if it's possible to create a > tutorial that explains monads well enough so that they just "make > sense" or "click" for people. -- Lanny Ripple ScmDB / Cisco Systems, Inc. From ithika at gmail.com Tue Aug 14 11:17:53 2007 From: ithika at gmail.com (Dougal Stanton) Date: Tue Aug 14 11:09:31 2007 Subject: [Haskell-cafe] Bathroom reading Message-ID: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> I'm looking for cool but mind-bending examples of functional brilliance. Let us say, hypothetically, you had a bathroom without any reading material. And having read all the Dilbert and Garfield you could seriously stomach, decide you should educate yourself while "on the job". :-) So you decide to print up some "one-liner" style programs into a little booklet. Something between credit-card and postcard sized, with a neat but mind-bending program on it. Don Stewart occasionally swoops in with some fixpoint malarkey to defuse heated discussions. I mean that kind of thing, but with a slightly wider scope than just fibs... Suggestions, please! D. From sebastian.sylvan at gmail.com Tue Aug 14 11:20:29 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Tue Aug 14 11:12:07 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C1C24F.1030905@cisco.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> Message-ID: <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> On 14/08/07, Lanny Ripple wrote: > Having just gone through all the tutorials and things (again but > this time I think it stuck) the Haskell community is on the wrong > track as far as teaching Monads to new programmers. > > If I were teaching addition and multiplication to children I > wouldn't start with, "We'll begin by defining an algebraic > structure named a "Group". From there we'll expand our concept > to a "Ring" and "Field". A group is a set and a binary operator > usually named "+" (or sometimes "*") such that...". > > No no no. You start with, "You all know how to count from one to > 10. If we have 1 item and we 'add' another 1 item we have 2 > items. We write this 1+1=2." > > The tutorials seriously need to step back and start with > something like, "To enforce order of evaluation we evaluate > closures* returning a defined type. The first closure will feed > its result to the second which will in turn feed it's result to > the third. Since the third closure can't be evaluated without > having the results from the second and first (and thus they had > to be evaluated earlier in time) we get a defined evaluation > sequence. Here are some examples..." > > (* Even using the word 'closure' is scary for those not familiar > with them.) > > Then, like "Monads For Functional Programming" (the paper that > finally clicked Monads for me) you point out that evaluating all > these closures returning a defined type in various ways form a > structure (which you can then explain) and we can use that > structure and change out the underlying effect(s) as needed. > > Now of course if your new programmer has the the necessary > background you can throw them in the deep end. But don't do that > to someone coming at the language from something like Java > learned out of a business degree course. (My background is a CS > degree with math minor and it still took two go-s at Haskell > before I got as far as understanding what folks were talking > about with Monads. Wish I had found Wadler's MFFP the first time > around.) Where are the shallow end tutorials? (Don't get me > wrong. The tutorials are good but there is also a place for the > "learn-by-rote with lots of examples" ones too.) Agreed, people tend to complicate things in the interest of being precise, which is probably a misstake when dealing with non-mathematicians. I like the very light weight analogy (which works for most practical uses of monads) that a monadic action is a "recipe" (you can even say that they're stored in sealed envelopes to model the opaqueness of e.g. IO). You can store recipes in boxes (data structures), pass them around, combine them to make new recipes etc. That's an abstraction of "actions" that everyone is familiar with. The analogy might not fit everything perfectly, but at least the reader will be with you from the start, and that makes it more likely that they'll follow you when you start diverging from the metaphor. Then you say that the GHC runtime system is the cook, who will take the "main" recipe and follow it. -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From v.dijk.bas at gmail.com Tue Aug 14 11:22:48 2007 From: v.dijk.bas at gmail.com (Bas van Dijk) Date: Tue Aug 14 11:14:27 2007 Subject: [Haskell-cafe] Bathroom reading In-Reply-To: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> Message-ID: On 8/14/07, Dougal Stanton wrote: > I'm looking for cool but mind-bending examples of functional brilliance. > > Let us say, hypothetically, you had a bathroom without any reading > material. And having read all the Dilbert and Garfield you could > seriously stomach, decide you should educate yourself while "on the > job". :-) > > So you decide to print up some "one-liner" style programs into a > little booklet. Something between credit-card and postcard sized, with > a neat but mind-bending program on it. Don Stewart occasionally swoops > in with some fixpoint malarkey to defuse heated discussions. I mean > that kind of thing, but with a slightly wider scope than just fibs... > > Suggestions, please! > > D. > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > Maybe: http://www.haskell.org/haskellwiki/Blow_your_mind and: http://haskell.org/haskellwiki/Research_papers/Functional_pearls regards, Bas van Dijk From allbery at ece.cmu.edu Tue Aug 14 11:23:08 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Tue Aug 14 11:14:45 2007 Subject: [Haskell-cafe] Bathroom reading In-Reply-To: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> Message-ID: <5780F049-0D4A-4C11-A5A4-CF0B1423CA17@ece.cmu.edu> On Aug 14, 2007, at 11:17 , Dougal Stanton wrote: > Let us say, hypothetically, you had a bathroom without any reading > material. And having read all the Dilbert and Garfield you could > seriously stomach, decide you should educate yourself while "on the > job". :-) Sounds to me like you want a waterproof panel displaying #haskell. :) -- 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 sjanssen at cse.unl.edu Tue Aug 14 11:31:51 2007 From: sjanssen at cse.unl.edu (Spencer Janssen) Date: Tue Aug 14 11:23:39 2007 Subject: [Haskell-cafe] Bathroom reading In-Reply-To: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> Message-ID: <200708141031.51497.sjanssen@cse.unl.edu> On Tuesday 14 August 2007 10:17:53 Dougal Stanton wrote: > I'm looking for cool but mind-bending examples of functional brilliance. > > Let us say, hypothetically, you had a bathroom without any reading > material. And having read all the Dilbert and Garfield you could > seriously stomach, decide you should educate yourself while "on the > job". :-) > > So you decide to print up some "one-liner" style programs into a > little booklet. Something between credit-card and postcard sized, with > a neat but mind-bending program on it. Don Stewart occasionally swoops > in with some fixpoint malarkey to defuse heated discussions. I mean > that kind of thing, but with a slightly wider scope than just fibs... > > Suggestions, please! > > D. Here's a small puzzle: without using a Haskell interpreter, explain what the 'foo' function does. > foo = filterM (const [True, False]) In case you aren't familiar, here's the definition of filterM: > filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a] > filterM _ [] = return [] > filterM p (x:xs) = do > flg <- p x > ys <- filterM p xs > return (if flg then x:ys else ys) Cheers, Spencer Janssen From jeff.polakow at db.com Tue Aug 14 11:45:06 2007 From: jeff.polakow at db.com (Jeff Polakow) Date: Tue Aug 14 11:36:51 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C1C24F.1030905@cisco.com> Message-ID: Hello, There is clearly a problem with the Haskell/monad tutorials out there... > The tutorials seriously need to step back and start with > something like, "To enforce order of evaluation we evaluate > closures* returning a defined type. The first closure will feed > its result to the second which will in turn feed it's result to > the third. Since the third closure can't be evaluated without > having the results from the second and first (and thus they had > to be evaluated earlier in time) we get a defined evaluation > sequence. Here are some examples..." > The style of this description is nice; however the description itself is wrong. Monads DO NOT determine order of evaluation. Previous posts on this thread give several examples. In lazy languages, data dependencies determine the order of evaluation. X must be evaluated before Y if Y depends upon the result of X. You can force the order of evaluation without using a monad just as you can have a monad which does not determine the order in which things get evaluated. >From the point of view of a programmer, a monad is simply a useful (higher-order) combinator pattern. All monadic code can be flattened by replacing occurrences of bind (>>=) with it's definition. One general intuition about monads is that they represent computations rather than simple (already computed) values: x :: Int -- x is an Int x :: Monad m => m Int -- x is a computation of an Int x :: [Int] -- x is a computation of an Int which can return multiplie values x :: Maybe Int -- x is a computation of an Int which might fail (return Nothing) x :: State s Int -- x is a computation of an Int which relies on, and returns (possibly modified) -- a value of type s. Note: State s Int is isomorphic to: s -> (Int,s) x :: IO Int -- x is a computation of an Int which can interact with the outside world. Return explains how to make a simple computation which returns a specified value. Bind explains how to use the result of a computation to compute something else. -Jeff --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/15725df6/attachment.htm From byorgey at gmail.com Tue Aug 14 12:24:36 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Tue Aug 14 12:16:14 2007 Subject: [Haskell-cafe] Bathroom reading In-Reply-To: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> Message-ID: <22fcbd520708140924h493aa7a3m3499ed9d32cde4f6@mail.gmail.com> > > So you decide to print up some "one-liner" style programs into a > little booklet. Something between credit-card and postcard sized, with > a neat but mind-bending program on it. Don Stewart occasionally swoops > in with some fixpoint malarkey to defuse heated discussions. I mean > that kind of thing, but with a slightly wider scope than just fibs... Clearly, we need to actually put together such a book! I'm imagining something where you have two mostly blank facing pages, with the code by itself in the middle of the right page; then the next 2-4 pages devoted to a short discussion of the code, how it works, related issues and techniques, and a list of references. All featuring beautiful typography and fantastic writing, of course. =) -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/c479d602/attachment-0001.htm From lanny at cisco.com Tue Aug 14 12:32:08 2007 From: lanny at cisco.com (Lanny Ripple) Date: Tue Aug 14 12:23:52 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: References: Message-ID: <46C1D908.4010502@cisco.com> Look! You are doing it again! :) Does that paragraph even contain the word "Monad"? :) I'm aware a monad is an abstraction and as such it doesn't *do* anything. My point was along the lines that you don't need to know that your working in a field to be able to learn that 3/2 = 1.5 . -ljr Jeff Polakow wrote: > > Hello, > > There is clearly a problem with the Haskell/monad tutorials out there... > > > The tutorials seriously need to step back and start with > > something like, "To enforce order of evaluation we evaluate > > closures* returning a defined type. The first closure will feed > > its result to the second which will in turn feed it's result to > > the third. Since the third closure can't be evaluated without > > having the results from the second and first (and thus they had > > to be evaluated earlier in time) we get a defined evaluation > > sequence. Here are some examples..." > > > The style of this description is nice; however the description itself is > wrong. > > Monads DO NOT determine order of evaluation. Previous posts on this > thread give several examples. > > In lazy languages, data dependencies determine the order of evaluation. > X must be evaluated before Y if Y depends upon the result of X. You can > force the order of evaluation without using a monad just as you can have > a monad which does not determine the order in which things get evaluated. > > From the point of view of a programmer, a monad is simply a useful > (higher-order) combinator pattern. All monadic code can be flattened by > replacing occurrences of bind (>>=) with it's definition. > > One general intuition about monads is that they represent computations > rather than simple (already computed) values: > > x :: Int -- x is an Int > > x :: Monad m => m Int -- x is a computation of an Int > > x :: [Int] -- x is a computation of an Int which can > return multiplie values > > x :: Maybe Int -- x is a computation of an Int which might > fail (return Nothing) > > x :: State s Int -- x is a computation of an Int which relies > on, and returns (possibly modified) > -- a value of type s. Note: State s Int is > isomorphic to: s -> (Int,s) > > x :: IO Int -- x is a computation of an Int which can > interact with the outside world. > > Return explains how to make a simple computation which returns a > specified value. > Bind explains how to use the result of a computation to compute > something else. > > -Jeff > > --- > > This e-mail may contain confidential and/or privileged information. If you > are not the intended recipient (or have received this e-mail in error) > please notify the sender immediately and destroy this e-mail. Any > unauthorized copying, disclosure or distribution of the material in this > e-mail is strictly forbidden. -- Lanny Ripple ScmDB / Cisco Systems, Inc. From asandroq at gmail.com Tue Aug 14 12:46:15 2007 From: asandroq at gmail.com (Alex Queiroz) Date: Tue Aug 14 12:37:55 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: References: <46C1C24F.1030905@cisco.com> Message-ID: <54e12800708140946w7efa92cbkac8c81747939ddf7@mail.gmail.com> Hallo, On 8/14/07, Jeff Polakow wrote: > > Hello, > > There is clearly a problem with the Haskell/monad tutorials out there... > > > The tutorials seriously need to step back and start with > > something like, "To enforce order of evaluation we evaluate > > closures* returning a defined type. The first closure will feed > > its result to the second which will in turn feed it's result to > > the third. Since the third closure can't be evaluated without > > having the results from the second and first (and thus they had > > to be evaluated earlier in time) we get a defined evaluation > > sequence. Here are some examples..." > > > The style of this description is nice; however the description itself is > wrong. > > Monads DO NOT determine order of evaluation. Previous posts on this thread > give several examples. > And his point was completely missed. Cheers, -- -alex http://www.ventonegro.org/ From dpiponi at gmail.com Tue Aug 14 12:56:51 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Tue Aug 14 12:48:30 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: References: <46C1C24F.1030905@cisco.com> Message-ID: <625b74080708140956j20315382s4461a37596b42427@mail.gmail.com> On 8/14/07, Jeff Polakow wrote: > One general intuition about monads is that they represent computations > rather than simple (already computed) values: > x :: Int -- x is an Int > x :: Monad m => m Int -- x is a computation of an Int What's a "computation"? It seems to me that in a lazy language, x::Int represents a computation of an int, not an "already computed" value. x::[Int] is a computation that returns multiple values. x::(Int,Int) is a computation that returns a pair of values. x::() is a computation that returns nothing. x::Map a b is a computation that gives a way to associate values of type a with values of type b. Some of these are monads, some are not. What's the difference between them? Why are you calling certain values "computations"? -- Dan From dpiponi at gmail.com Tue Aug 14 12:59:21 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Tue Aug 14 12:50:59 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> Message-ID: <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> On 8/14/07, Sebastian Sylvan wrote: > I like the very light weight analogy (which works for most practical > uses of monads) that a monadic action is a "recipe" Many introductory programming books present the idea of a program as a recipe. Here's a recipe for computing factorials: fact 0 = 1 fact n = n*fact (n-1) Where do monads come in? -- Dan From jeff.polakow at db.com Tue Aug 14 13:01:08 2007 From: jeff.polakow at db.com (Jeff Polakow) Date: Tue Aug 14 12:52:52 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C1D908.4010502@cisco.com> Message-ID: Hello, > Look! You are doing it again! :) Does that paragraph even > contain the word "Monad"? :) > Sorry. Your first paragraph led me to believe you were writing about monads. > I'm aware a monad is an abstraction and as such it doesn't *do* > anything. My point was along the lines that you don't need to > know that your working in a field to be able to learn that > > 3/2 = 1.5 > I agree. I think one of the problem with understanding monads comes from people mistakenly believing monads force an order of evaluation. This is a shortcoming of general Haskell tutorials which fail to convey that the order of evaluation is determined by data dependencies. If new programmers know that monads have nothing to do with forcing the order of evaluation when they start learning about monads, then maybe they will be less confused as they sort out what monads are actually used for. -Jeff --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/7b87c902/attachment.htm From chad.scherrer at gmail.com Tue Aug 14 13:07:00 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Tue Aug 14 12:58:39 2007 Subject: [Haskell-cafe] Re: Bathroom reading Message-ID: Maybe something of these? http://www.haskell.org/haskellwiki/Blow_your_mind -- Chad Scherrer "Time flies like an arrow; fruit flies like a banana" -- Groucho Marx From derek.a.elkins at gmail.com Tue Aug 14 13:07:18 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Tue Aug 14 12:59:03 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C1C24F.1030905@cisco.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> Message-ID: <1187111238.5456.8.camel@derek-laptop> On Tue, 2007-08-14 at 09:55 -0500, Lanny Ripple wrote: > Having just gone through all the tutorials and things (again but > this time I think it stuck) the Haskell community is on the wrong > track as far as teaching Monads to new programmers. > > If I were teaching addition and multiplication to children I > wouldn't start with, "We'll begin by defining an algebraic > structure named a "Group". From there we'll expand our concept > to a "Ring" and "Field". A group is a set and a binary operator > usually named "+" (or sometimes "*") such that...". > > No no no. You start with, "You all know how to count from one to > 10. If we have 1 item and we 'add' another 1 item we have 2 > items. We write this 1+1=2." For every monad tutorial of the former type, I can find ten of the latter. This is not the problem. A similar complaint is tutorials that invoke category theory; almost none of them do this either. What people need to do is stop reading two page blog posts by someone who's "just got" monads and read the well-written peer-reviewed papers by the people who clearly know what they are talking about. Luckily, for monads applied to Haskell we have Wadler, a witty, enjoyable and clear writer/speaker. All of Wadler's monad "introductions" are readable by anyone with a basic grasp of Haskell. You certainly don't need to be even remotely an academic to understand them. I'm willing to bet that many people who say they don't understand monads and have read "every tutorial about them" haven't read -any- of Wadler's papers. From sebastian.sylvan at gmail.com Tue Aug 14 13:11:17 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Tue Aug 14 13:03:02 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> Message-ID: <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> On 14/08/07, Dan Piponi wrote: > On 8/14/07, Sebastian Sylvan wrote: > > I like the very light weight analogy (which works for most practical > > uses of monads) that a monadic action is a "recipe" > > Many introductory programming books present the idea of a program as a > recipe. Here's a recipe for computing factorials: > > fact 0 = 1 > fact n = n*fact (n-1) > > Where do monads come in? Well I would try to distinguish between code that we write to compute values, and values which represent monadic actions when coming up with analogies. You may wish to explain code as recipes too, but I think your students would start getting confused if you overload the same analogy for two different things. The point was to find some real world analogy for "abstraction of an action". A cooking recipe fits the bill pretty well. Everyone "gets" that you can have a "model" of "making pancake batter" in the form of a recipe, and that you can combine such recipes with other recipes or store them in boxes or whatever. Once you're that far along, you're half way there in teaching them enough to be able to use most monads in practice. -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From lanny at cisco.com Tue Aug 14 13:30:28 2007 From: lanny at cisco.com (Lanny Ripple) Date: Tue Aug 14 13:22:12 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: References: Message-ID: <46C1E6B4.6090405@cisco.com> A very good point. I even knew that implicitly but wasn't thinking in those terms explicitly when writing up my first post and it does make a difference in how you view things. -ljr Jeff Polakow wrote: > > Hello, > > > Look! You are doing it again! :) Does that paragraph even > > contain the word "Monad"? :) > > > Sorry. Your first paragraph led me to believe you were writing about > monads. > > > I'm aware a monad is an abstraction and as such it doesn't *do* > > anything. My point was along the lines that you don't need to > > know that your working in a field to be able to learn that > > > > 3/2 = 1.5 > > > I agree. > > I think one of the problem with understanding monads comes from people > mistakenly believing monads force an order of evaluation. This is a > shortcoming of general Haskell tutorials which fail to convey that the > order of evaluation is determined by data dependencies. If new > programmers know that monads have nothing to do with forcing the order > of evaluation when they start learning about monads, then maybe they > will be less confused as they sort out what monads are actually used for. > > -Jeff > > > > --- > > This e-mail may contain confidential and/or privileged information. If you > are not the intended recipient (or have received this e-mail in error) > please notify the sender immediately and destroy this e-mail. Any > unauthorized copying, disclosure or distribution of the material in this > e-mail is strictly forbidden. -- Lanny Ripple ScmDB / Cisco Systems, Inc. From lennart at augustsson.net Tue Aug 14 13:37:23 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Tue Aug 14 13:29:24 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <625b74080708140956j20315382s4461a37596b42427@mail.gmail.com> References: <46C1C24F.1030905@cisco.com> <625b74080708140956j20315382s4461a37596b42427@mail.gmail.com> Message-ID: You don't normally call x::Int a computation of an Int because there's nothing that distinguishes the value of the x from what it was before you computed it. So I prefer to regard x as a value (in a domain, of course). But for x :: (Monad m) => m Int there is something else happening, so the word computation makes sense. This is just the terminology people use, not an absolute truth, so you're free to think it's wrong. :) BTW, if you regard non-termination as an effect then even x :: Int is a computation. -- Lennart On 8/14/07, Dan Piponi wrote: > > On 8/14/07, Jeff Polakow wrote: > > One general intuition about monads is that they represent computations > > rather than simple (already computed) values: > > > x :: Int -- x is an Int > > x :: Monad m => m Int -- x is a computation of an Int > > What's a "computation"? It seems to me that in a lazy language, x::Int > represents a computation of an int, not an "already computed" value. > x::[Int] is a computation that returns multiple values. x::(Int,Int) > is a computation that returns a pair of values. x::() is a computation > that returns nothing. x::Map a b is a computation that gives a way to > associate values of type a with values of type b. Some of these are > monads, some are not. What's the difference between them? Why are you > calling certain values "computations"? > -- > Dan > _______________________________________________ > 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/haskell-cafe/attachments/20070814/7fd50f28/attachment.htm From lanny at cisco.com Tue Aug 14 13:40:24 2007 From: lanny at cisco.com (Lanny Ripple) Date: Tue Aug 14 13:32:05 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <1187111238.5456.8.camel@derek-laptop> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <1187111238.5456.8.camel@derek-laptop> Message-ID: <46C1E908.3070401@cisco.com> Derek Elkins wrote: > What people need to do is stop reading two page blog posts by someone > who's "just got" monads and read the well-written peer-reviewed papers I have taught many people to program in group settings and individually in my career. I have referred them to many tutorials. I have used many examples from tutorials I thought were useful. I can't recall a single time I've ever turned to a beginner and said, "And you really should brush up on the peer-reviewed papers to learn this part." > by the people who clearly know what they are talking about. Luckily, > for monads applied to Haskell we have Wadler, a witty, enjoyable and > clear writer/speaker. All of Wadler's monad "introductions" are > readable by anyone with a basic grasp of Haskell. You certainly don't > need to be even remotely an academic to understand them. I'm willing to > bet that many people who say they don't understand monads and have read > "every tutorial about them" haven't read -any- of Wadler's papers. I'm confused. Are you praising Wadler or bashing the tutorials (or both)? *I* was carping about the tutorials (and even mentioned that Wadler was my breakthrough) so I suspect we are in violent agreement. -ljr -- Lanny Ripple ScmDB / Cisco Systems, Inc. From jeff.polakow at db.com Tue Aug 14 13:42:25 2007 From: jeff.polakow at db.com (Jeff Polakow) Date: Tue Aug 14 13:34:08 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <625b74080708140956j20315382s4461a37596b42427@mail.gmail.com> Message-ID: Hello, > On 8/14/07, Jeff Polakow wrote: > > One general intuition about monads is that they represent computations > > rather than simple (already computed) values: > > > x :: Int -- x is an Int > > x :: Monad m => m Int -- x is a computation of an Int > > What's a "computation"? It seems to me that in a lazy language, x::Int > represents a computation of an int, not an "already computed" value. > This intuition for monads as "computations" is independent of operational semantics. > x::[Int] is a computation that returns multiple values. x::(Int,Int) > is a computation that returns a pair of values. x::() is a computation > that returns nothing. x::Map a b is a computation that gives a way to > associate values of type a with values of type b. Some of these are > monads, some are not. What's the difference between them? Why are you > calling certain values "computations"? > Of course, the type [Int] denotes a value which is a list of Ints; additionally [Int] can be viewed as a value representing the nondeterministic computation of a single Int. Generally, the type Monad m => m Int can be viewed as a value representing the computation of an Int. However, I do not mean to imply that everything which can be viewed as a computation of something is a monad. In any case, this is only meant to be a general (i.e. high-level) intuition. BTW, this intuition was, more or less, the one used by Moggi when describing how monads can be used to describe denotational models for languages. -Jeff --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/9d72ce14/attachment.htm From brian at ithil.org Tue Aug 14 13:53:01 2007 From: brian at ithil.org (Brian Brunswick) Date: Tue Aug 14 13:44:40 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: References: <625b74080708140956j20315382s4461a37596b42427@mail.gmail.com> Message-ID: <6f680f6d0708141053u5d9eaa67h6879908dce2a3d84@mail.gmail.com> On 14/08/07, Jeff Polakow wrote: > > Of course, the type [Int] denotes a value which is a list of Ints; > additionally [Int] can be viewed as a value representing the > nondeterministic computation of a single Int. Generally, the type Monad m => > m Int can be viewed as a value representing the computation of an Int. But thats not really right. What exactly m Int does /depends/ on m. It might represent 0 or more computations of Int, or computations of Int carrying some extra stuff around, or complex control logic about what the computation does when. All that is really given, is that we can feed another 'Int->m a' thingy to it using bind, and get back an m a, and the thingy we fed in might even be used zero or more times while doing it. These 'thingy's are called Kleisli Arrows, by the way. -- Brian_Brunswick____brian@ithil.org____Wit____Disclaimer____!Shortsig_rules! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/8e478d64/attachment.htm From ithika at gmail.com Tue Aug 14 14:02:07 2007 From: ithika at gmail.com (Dougal Stanton) Date: Tue Aug 14 13:53:45 2007 Subject: [Haskell-cafe] Bathroom reading In-Reply-To: <22fcbd520708140924h493aa7a3m3499ed9d32cde4f6@mail.gmail.com> References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> <22fcbd520708140924h493aa7a3m3499ed9d32cde4f6@mail.gmail.com> Message-ID: <2d3641330708141102v59404f4cr92bbcfd3cfaeef9e@mail.gmail.com> On 14/08/07, Brent Yorgey wrote: > Clearly, we need to actually put together such a book! I'm imagining > something where you have two mostly blank facing pages, with the code by > itself in the middle of the right page; then the next 2-4 pages devoted to a > short discussion of the code, how it works, related issues and techniques, > and a list of references. All featuring beautiful typography and fantastic > writing, of course. =) Oh indeed! This wasn't *completely* idle chatter on my part. I used to work in a print shop and we did a lot of work for art and architecture students who would do this kind of thing all the time. Fantastic little notebook-style gifts of images and blank pages and elegant typography. It's just a shame so many of them were terrible at spelling! :-P It shouldn't be too difficult to use LaTeX to this end. Once a document class has been hammered out you can offer a range of different booklets! The "Evolution of a Haskell Programmer" series would be a good place to start. Bring it to your next job interview to whip out when someone points to that bit on your CV and says, "what's that?". Any skilled TeXers in the house? D. From dpiponi at gmail.com Tue Aug 14 14:08:36 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Tue Aug 14 14:00:16 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: References: <46C1C24F.1030905@cisco.com> <625b74080708140956j20315382s4461a37596b42427@mail.gmail.com> Message-ID: <625b74080708141108u7ed3810bjc80bfb70267170b9@mail.gmail.com> On 8/14/07, Lennart Augustsson wrote: > You don't normally call x::Int a computation of an Int because there's > nothing that distinguishes the value of the x from what it was before you > computed it. Can you spell out exactly what you mean by this? > So I prefer to regard x as a value (in a domain, of course). > But for x :: (Monad m) => m Int there is something else happening When someone uses the phrase "something else" it implies that we are talking about two things, a "something" and a disjoint "something else". For example, if x = [1,2,3] what is the "something" and what is the "something else"? What was the x "before [I] computed it" and how does it differ from its "value"? > This is just the terminology people use, not an absolute truth, so you're > free to think it's wrong. :) For something like this I prefer to think in terms of "useful" and "not useful". If you find the term "computation" useful, I might find it useful too. So I'm jealous as I can't figure out how to use it. :-) I'm not looking for a formal definition or anything like that. But I would like a reliable way to distinguish between things that are computations and things that are not. -- Dan From dpiponi at gmail.com Tue Aug 14 14:22:33 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Tue Aug 14 14:14:11 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> Message-ID: <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> On 8/14/07, Sebastian Sylvan wrote: > On 14/08/07, Dan Piponi wrote: > > Where do monads come in? > > Well I would try to distinguish between code that we write to compute > values, and values which represent monadic actions when coming up with > analogies. How would you make that distinction? At this point I can imagine students immediately thinking that my factorial program is a recipe and wondering why it doesn't involve monads. Either you distinguish between these things in a circular way using monads (no use when teaching monads in the first place) or you have some a priori distinction that you point out to students. -- Dan From sebastian.sylvan at gmail.com Tue Aug 14 14:33:14 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Tue Aug 14 14:24:53 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> Message-ID: <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> On 14/08/07, Dan Piponi wrote: > On 8/14/07, Sebastian Sylvan wrote: > > On 14/08/07, Dan Piponi wrote: > > > Where do monads come in? > > > > Well I would try to distinguish between code that we write to compute > > values, and values which represent monadic actions when coming up with > > analogies. > > How would you make that distinction? How can you *not* make a distinction? If you view source code as recipes, that's fine, but the *code* doesn't even exist in the program! You can't pass *code* around (unless you do it as String). Clearly there's a gulf of difference between the source code ASCII string that represent the factorial function, and a first class value that represents an action *in* the language. > At this point I can imagine > students immediately thinking that my factorial program is a recipe > and wondering why it doesn't involve monads. Well that's easy, don't use the recipe analogy to explain code, use it for monadic values exclusively, and you avoid the confusion entirely! I don't think it's that complicated. Monads have a monadic type. They represent an abstract form of an "action", which can be viewed as an analogy to real-world cooking recipes. As long as you don't deliberately confuse things by using the same analogy for two different things I don't see where confusion would set in. -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From byorgey at gmail.com Tue Aug 14 14:38:17 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Tue Aug 14 14:29:54 2007 Subject: [Haskell-cafe] Bathroom reading In-Reply-To: <2d3641330708141102v59404f4cr92bbcfd3cfaeef9e@mail.gmail.com> References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> <22fcbd520708140924h493aa7a3m3499ed9d32cde4f6@mail.gmail.com> <2d3641330708141102v59404f4cr92bbcfd3cfaeef9e@mail.gmail.com> Message-ID: <22fcbd520708141138yecb0d6cxed78262a171e657@mail.gmail.com> On 8/14/07, Dougal Stanton wrote: > > On 14/08/07, Brent Yorgey wrote: > > Clearly, we need to actually put together such a book! I'm imagining > > something where you have two mostly blank facing pages, with the code by > > itself in the middle of the right page; then the next 2-4 pages devoted > to a > > short discussion of the code, how it works, related issues and > techniques, > > and a list of references. All featuring beautiful typography and > fantastic > > writing, of course. =) > > Oh indeed! This wasn't *completely* idle chatter on my part. I used to > work in a print shop and we did a lot of work for art and architecture > students who would do this kind of thing all the time. Fantastic > little notebook-style gifts of images and blank pages and elegant > typography. It's just a shame so many of them were terrible at > spelling! :-P > > It shouldn't be too difficult to use LaTeX to this end. Once a > document class has been hammered out you can offer a range of > different booklets! The "Evolution of a Haskell Programmer" series > would be a good place to start. Bring it to your next job interview to > whip out when someone points to that bit on your CV and says, "what's > that?". > > Any skilled TeXers in the house? > > D. > Well, it wasn't completely idle chatter on my part, either! =) After spending the past year writing (and typesetting) a mathematics book in my spare time, I would consider myself an intermediate to advanced user of LaTeX, although I know much less about TeX itself than I would like (although I do intend to learn). Unfortunately, what with applying to grad school and other things, it probably wouldn't be wise for me to spearhead such a project at the moment, although I'd be excited about contributing. But I very well might pick it up at a later date if no one decides to run with it right now. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/ddc28b7b/attachment.htm From dpiponi at gmail.com Tue Aug 14 14:52:16 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Tue Aug 14 14:43:58 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> Message-ID: <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> On 8/14/07, Sebastian Sylvan wrote: > Well that's easy, don't use the recipe analogy to explain code, use it > for monadic values exclusively, and you avoid the confusion entirely! > > I don't think it's that complicated. It certainly is complicated. I think I have a good grasp of monads to the point where I can tease novel monads (and comonads) out from algorithms that people previously didn't see as monadic. And yet I still don't understand what you are saying (except with respect to one specific monad, IO, where I can interpret 'action' as meaning an I/O operation). > Monads have a monadic type. They > represent an abstract form of an "action", which can be viewed as an > analogy to real-world cooking recipes. All functions can be viewed as recipes. (+) is a recipe. Give me some ingredients (two numbers) and I'll use (+) to give you back their sum. > As long as you don't > deliberately confuse things by using the same analogy for two > different things I don't see where confusion would set in. If I was one of your students and you said that monads are recipes I would immediately ask you where the monads are in my factorial program regardless of whether you had introduced one or two different analogies for recipes. There are two sides to every analogy. If you have an analogy between A and B then you can use knowledge about A to understand B. But conversely, if you can't set up the same analogy between A and B then that tells you something useful about B also. As far as I can see, your description of a monad fits every computer program I have ever written, and as a result I don't see what it is that makes monads special. And monads are special. -- Dan From wnoise at ofb.net Tue Aug 14 14:52:41 2007 From: wnoise at ofb.net (Aaron Denney) Date: Tue Aug 14 14:44:28 2007 Subject: [Haskell-cafe] Re: Explaining monads References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> Message-ID: On 2007-08-14, Dan Piponi wrote: > On 8/14/07, Sebastian Sylvan wrote: >> I like the very light weight analogy (which works for most practical >> uses of monads) that a monadic action is a "recipe" > > Many introductory programming books present the idea of a program as a > recipe. Here's a recipe for computing factorials: > > fact 0 = 1 > fact n = n*fact (n-1) > > Where do monads come in? Playing the devil's advocate here: Recipe is a reasonable description for imperative code ... because it's all in the IO monad. Not such a good mapping for functional code. (I don't think recipe is a good analogy for, say, the List monad, reader monads, etc.) -- Aaron Denney -><- From jeff.polakow at db.com Tue Aug 14 14:57:46 2007 From: jeff.polakow at db.com (Jeff Polakow) Date: Tue Aug 14 14:49:31 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <6f680f6d0708141053u5d9eaa67h6879908dce2a3d84@mail.gmail.com> Message-ID: Hello, > On 14/08/07, Jeff Polakow wrote: > Of course, the type [Int] denotes a value which is a list of Ints; > additionally [Int] can be viewed as a value representing the > nondeterministic computation of a single Int. Generally, the type > Monad m => m Int can be viewed as a value representing the > computation of an Int. > > > But thats not really right. What exactly m Int does /depends/ on m. > It might represent 0 or more computations > of Int, or computations of Int carrying some extra stuff around, or > complex control logic about what the computation does > when. > Perhaps the confusion is in the word computation. I'm using the word in an abstract sense. I do not mean the actual execution of Haskell code to produce a value. Thus, under this intuition: The type Int represents a value which denotes an Int. The type m Int denotes a value which is a single computation (for an unspecified notion of computation) of an Int. A specific computation of an Int might result in several, or zero, actual Ints (the list monad); a String or an Int (the Either String monad); the constant () (the trivial monad); ... The type Monad m => m Int cannot represent multiple computations of an Int. The type Monad m => [m Int] represents multiple computations of an Int (of course, any container type can be used in place of list). -Jeff --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/0e28fd70/attachment-0001.htm From wnoise at ofb.net Tue Aug 14 14:57:52 2007 From: wnoise at ofb.net (Aaron Denney) Date: Tue Aug 14 14:49:41 2007 Subject: [Haskell-cafe] Re: Bathroom reading References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> <200708141031.51497.sjanssen@cse.unl.edu> Message-ID: On 2007-08-14, Spencer Janssen wrote: > On Tuesday 14 August 2007 10:17:53 Dougal Stanton wrote: >> I'm looking for cool but mind-bending examples of functional brilliance. >> >> Let us say, hypothetically, you had a bathroom without any reading >> material. And having read all the Dilbert and Garfield you could >> seriously stomach, decide you should educate yourself while "on the >> job". :-) >> >> So you decide to print up some "one-liner" style programs into a >> little booklet. Something between credit-card and postcard sized, with >> a neat but mind-bending program on it. Don Stewart occasionally swoops >> in with some fixpoint malarkey to defuse heated discussions. I mean >> that kind of thing, but with a slightly wider scope than just fibs... >> >> Suggestions, please! >> >> D. > > Here's a small puzzle: without using a Haskell interpreter, explain what > the 'foo' function does. > >> foo = filterM (const [True, False]) powerset. Very nice use of the list monad. -- Aaron Denney -><- From dellaq at ml1.net Tue Aug 14 14:55:05 2007 From: dellaq at ml1.net (John Dell'Aquila) Date: Tue Aug 14 14:56:43 2007 Subject: [Haskell-cafe] Error building takusen with Cabal-1.1.6.2 Message-ID: Setup.hs wants a module that Cabal hides. Am I doing something wrong (newbie :-) or should I try to fall back to Cabal-1.1.6.1? $ ghc --make -o setup Setup.hs Setup.hs:13:7: Could not find module `Distribution.Compat.FilePath': it is hidden (in package Cabal-1.1.6.2) From sebastian.sylvan at gmail.com Tue Aug 14 15:13:30 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Tue Aug 14 15:05:08 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> Message-ID: <3d96ac180708141213k33ac868bk766c673848f6a25d@mail.gmail.com> On 14/08/07, Dan Piponi wrote: > On 8/14/07, Sebastian Sylvan wrote: > > Well that's easy, don't use the recipe analogy to explain code, use it > > for monadic values exclusively, and you avoid the confusion entirely! > > > > I don't think it's that complicated. > > It certainly is complicated. I think I have a good grasp of monads to > the point where I can tease novel monads (and comonads) out from > algorithms that people previously didn't see as monadic. And yet I > still don't understand what you are saying (except with respect to one > specific monad, IO, where I can interpret 'action' as meaning an I/O > operation). > > > Monads have a monadic type. They > > represent an abstract form of an "action", which can be viewed as an > > analogy to real-world cooking recipes. > > All functions can be viewed as recipes. (+) is a recipe. Give me some > ingredients (two numbers) and I'll use (+) to give you back their sum. No, (+) is a function, not a "recipe". Again, you're introducing confusion because you use the same analogy for two *different* things. Use it for one of the things and you don't have that problem. I want to use "recipe" to mean "an abstraction for an action". It could litterally be a text string containing the C code required to do a particular IO action, for example. (+) isn't an abstraction in the same sense, it *is* the "action" itself. (+) is the actual value of the function that will add two numbers together. A monadic value is an abstract recipe that you can't actually use directly (you can only combine them, and if you're lucky you can "perform" them once you're done combining them, e.g. ST, but not IO). > > > As long as you don't > > deliberately confuse things by using the same analogy for two > > different things I don't see where confusion would set in. > > If I was one of your students and you said that monads are recipes I > would immediately ask you where the monads are in my factorial program > regardless of whether you had introduced one or two different > analogies for recipes. Why would you? I really don't see where you would get that idea? If I tell you that a function returns "a fruit", would you ask where the fruit in your factorial program is? Probably not. Why would you go off and take an analogy for monads and apply it to something completely different and still think the analogy holds? A function is *not* a recipe in this analogy, it's just a function (which you hopefully should've covered by the time you get to monads. Monadic values, and *only* monadic values (not functions!) are to be viewed as analogous to real world cooking recipes in this analogy. Functions shouldn't. If you start mixing things together it will get confused, so just don't! I don't think this is very difficult to understand, so if you still don't get it, I think you're just going to have to read it again because I can't explain it any better, and in my experience, newbies tend to understand this analogy within seconds (maybe that's the problem, you're not a newbie)... -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From ariep at xs4all.nl Tue Aug 14 15:15:45 2007 From: ariep at xs4all.nl (Arie Peterson) Date: Tue Aug 14 15:07:23 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <625b74080708141108u7ed3810bjc80bfb70267170b9@mail.gmail.com> References: <46C1C24F.1030905@cisco.com> <625b74080708140956j20315382s4461a37596b42427@mail.gmail.com> <625b74080708141108u7ed3810bjc80bfb70267170b9@mail.gmail.com> Message-ID: <5864.213.84.177.94.1187118945.squirrel@webmail.xs4all.nl> Dan Piponi wrote: | On 8/14/07, Lennart Augustsson wrote: | > You don't normally call x::Int a computation of an Int because there's | > nothing that distinguishes the value of the x from what it was before | > you computed it. | | Can you spell out exactly what you mean by this? Let's take a formal viewpoint: when writing a haskell program, you specify what properties your values must satisfy. So 'x = 6' means that I want 'x' to equal the value 6. To make solution of these equations tractable, we have agreed that we treat them as (recursive) definitions of the LHS. Now, the compiler may actually treat 'x = 6' as a specification of a computation. From this formal point of view, however, that is an implementation detail, and we don't need to speak about 'computations'. Does this help at all? | When someone uses the phrase "something else" it implies that we are | talking about two things, a "something" and a disjoint "something | else". For example, if x = [1,2,3] what is the "something" and what is | the "something else"? What was the x "before [I] computed it" and how | does it differ from its "value"? | || This is just the terminology people use, not an absolute truth, so || you're free to think it's wrong. :) | | For something like this I prefer to think in terms of "useful" and | "not useful". If you find the term "computation" useful, I might find | it useful too. So I'm jealous as I can't figure out how to use it. :-) | I'm not looking for a formal definition or anything like that. But I | would like a reliable way to distinguish between things that are | computations and things that are not. Well, it depends on the context really, and on how hard you squint. Sorry to disappoint you :-) (friendly apologetic smile, not an evil laugh). Instead of [1,2,3], let me underhandly take the list [False,True]. Nothing 'computational' about it, right? Just a basic list, with some boolean entries. But behold! In the context of the 'power set' function from the other thread: > power = filterM (const [False,True]) , this innocuous list suddenly reveals its monadic/computational character. In this context, you may interpret [False,True] as a 'multi-valued computation of a boolean', which yields both False and True. 'const [False,True]' is a monadic predicate, which yields both False and True on any element. filterM then applies this predicate to all elements of a list, sequencing the computational/multi-valued aspects. Greetings, Arie From malte at gmx-topmail.de Tue Aug 14 15:32:24 2007 From: malte at gmx-topmail.de (Malte Milatz) Date: Tue Aug 14 15:20:52 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> Message-ID: <20070814213224.671f65c5@aligatoro.ret> Dan Piponi, Tue, 14 Aug 2007 11:52:16 -0700: > All functions can be viewed as recipes. (+) is a recipe. Give me some > ingredients (two numbers) and I'll use (+) to give you back their sum. (+) is not a recipe, it is a chef. On the other hand, (return 5 :: State Integer) is a recipe. You need a chef, namely runState, to get your meal. Oh my, imagery can be so crazy. Malte From sebastian.sylvan at gmail.com Tue Aug 14 15:30:55 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Tue Aug 14 15:22:33 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <20070814213224.671f65c5@aligatoro.ret> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> <20070814213224.671f65c5@aligatoro.ret> Message-ID: <3d96ac180708141230k39505c10wb91eb93af7d08b1b@mail.gmail.com> On 14/08/07, Malte Milatz wrote: > Dan Piponi, Tue, 14 Aug 2007 11:52:16 -0700: > > All functions can be viewed as recipes. (+) is a recipe. Give me some > > ingredients (two numbers) and I'll use (+) to give you back their sum. > > (+) is not a recipe, it is a chef. On the other hand, > (return 5 :: State Integer) is a recipe. You need a > chef, namely runState, to get your meal. > > Oh my, imagery can be so crazy. Thank you! That does make sense. -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From bf3 at telenet.be Tue Aug 14 15:17:54 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Tue Aug 14 15:23:32 2007 Subject: [Haskell-cafe] Monad explanation from a newbie to newbies having C# (or other OO) experience Message-ID: <007201c7dea7$d0fa2e70$72ee8b50$@be> See attachment. This is an early draft, but I?m afraid it will just be another tutorial that does not solve anything, so I?ll better throw it in the arena for review right now, so I don't waste more time ;-) The idea of this tutorial is not explaining monads, bet getting to the monad concept step by step, and then finally in the end talking about the real monad abstraction. Note that I?m a self-made man, so much of the terminology and even approach could be wrong (I learned it adhoc). I also hardly have any Haskell experience (maybe 5 full days of writing example code now), but anyway, writing this tutorial was a good exercise. To make things even worse I?m also not a native English speaker, so it will most likely be some kind of Belgian English (without the chocolate) ;) So horror is coming your way! Any feedback is welcome! ? Cheers, Peter -------------- next part -------------- A non-text attachment was scrubbed... Name: monads2.hs Type: application/octet-stream Size: 15913 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/d1ee4e77/monads2-0001.obj From sethg at ropine.com Tue Aug 14 15:31:40 2007 From: sethg at ropine.com (Seth Gordon) Date: Tue Aug 14 15:29:47 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <3d96ac180708141213k33ac868bk766c673848f6a25d@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> <3d96ac180708141213k33ac868bk766c673848f6a25d@mail.gmail.com> Message-ID: <46C2031C.7070500@ropine.com> Sebastian Sylvan wrote: > On 14/08/07, Dan Piponi wrote: >> If I was one of your students and you said that monads are recipes I >> would immediately ask you where the monads are in my factorial program >> regardless of whether you had introduced one or two different >> analogies for recipes. > > Why would you? I really don't see where you would get that idea? If I > tell you that a function returns "a fruit", would you ask where the > fruit in your factorial program is? Probably not. Why would you go off > and take an analogy for monads and apply it to something completely > different and still think the analogy holds? > A function is *not* a recipe in this analogy, it's just a function > (which you hopefully should've covered by the time you get to monads. > Monadic values, and *only* monadic values (not functions!) are to be > viewed as analogous to real world cooking recipes in this analogy. > Functions shouldn't. If you start mixing things together it will get > confused, so just don't! As a mostly-newbie who is working on his own monad tutorial (bwah-hah-hah), I share Dan's confusion about your analogy. Teacher: "Monads are like recipes." Student: "Aren't functions like recipes, too?" Teacher: "Well, yes, but we're talking about monads now, not functions." That response doesn't help the student, because the student already knows about functions, and would probably understand monads a lot better if he or she knew how monads are *different from* functions. (Especially since, umm, isn't the ((->) a) data type a monad?) From benjamin.franksen at bessy.de Tue Aug 14 15:49:18 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Tue Aug 14 15:41:10 2007 Subject: [Haskell-cafe] Re: Error building takusen with Cabal-1.1.6.2 References: Message-ID: John Dell'Aquila wrote: > Setup.hs wants a module that Cabal hides. Am I doing something wrong (newbie :-) > or should I try to fall back to Cabal-1.1.6.1? > > $ ghc --make -o setup Setup.hs > > Setup.hs:13:7: > Could not find module `Distribution.Compat.FilePath': > it is hidden (in package Cabal-1.1.6.2) This is what I did to make takusen build with ghc-6.6.1: ben@sarun: .../haskell/takusen_0 > darcs whatsnew { hunk ./Setup.hs 13 -import Distribution.Compat.FilePath (splitFileName, joinPaths)^M$ +import System.FilePath (splitFileName, combine)^M$ hunk ./Setup.hs 124 - libDirs <- canonicalizePath (joinPaths path libDir)^M$ - includeDirs <- canonicalizePath (joinPaths path includeDir)^M$ + libDirs <- canonicalizePath (combine path libDir)^M$ + includeDirs <- canonicalizePath (combine path includeDir)^M$ } HTH Ben From sebastian.sylvan at gmail.com Tue Aug 14 15:50:47 2007 From: sebastian.sylvan at gmail.com (Sebastian Sylvan) Date: Tue Aug 14 15:42:25 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C2031C.7070500@ropine.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> <3d96ac180708141213k33ac868bk766c673848f6a25d@mail.gmail.com> <46C2031C.7070500@ropine.com> Message-ID: <3d96ac180708141250j5197c290k2866ab8820aa029c@mail.gmail.com> On 14/08/07, Seth Gordon wrote: > Sebastian Sylvan wrote: > > On 14/08/07, Dan Piponi wrote: > >> If I was one of your students and you said that monads are recipes I > >> would immediately ask you where the monads are in my factorial program > >> regardless of whether you had introduced one or two different > >> analogies for recipes. > > > > Why would you? I really don't see where you would get that idea? If I > > tell you that a function returns "a fruit", would you ask where the > > fruit in your factorial program is? Probably not. Why would you go off > > and take an analogy for monads and apply it to something completely > > different and still think the analogy holds? > > A function is *not* a recipe in this analogy, it's just a function > > (which you hopefully should've covered by the time you get to monads. > > Monadic values, and *only* monadic values (not functions!) are to be > > viewed as analogous to real world cooking recipes in this analogy. > > Functions shouldn't. If you start mixing things together it will get > > confused, so just don't! > > As a mostly-newbie who is working on his own monad tutorial > (bwah-hah-hah), I share Dan's confusion about your analogy. > > Teacher: "Monads are like recipes." > > Student: "Aren't functions like recipes, too?" > > Teacher: "Well, yes, but we're talking about monads now, not functions." > Teacher: No, functions are like chefs. They do things to their input. Monads are like recipes, they don't *do* anything at all, they just represent an action, they need chefs to interpret them. -- Sebastian Sylvan +44(0)7857-300802 UIN: 44640862 From alexteslin at yahoo.co.uk Tue Aug 14 15:51:54 2007 From: alexteslin at yahoo.co.uk (Alexteslin) Date: Tue Aug 14 15:43:31 2007 Subject: [Haskell-cafe] defining last using foldr Message-ID: <12151145.post@talk.nabble.com> Hi, I am trying to do the exercise which asks to define built-in functions 'last' and 'init' using 'foldr' function, such as last "Greggery Peccary" = 'y' the type for my function is: myLast :: [Char] -> Char I am not generalizing type so that make it less complicated. But what ever i am trying would not work. The only function type foldr takes as an argument is either (a->a->a) or (a->b->b) and none of the functions i found that would match this type from Char to Char. So in other words should be (Char->Char-Char). I can define the function without foldr but that misses the point of the exercise. Any hint will be appreciated, Thank you -- View this message in context: http://www.nabble.com/defining-last-using-foldr-tf4269357.html#a12151145 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From wnoise at ofb.net Tue Aug 14 16:05:19 2007 From: wnoise at ofb.net (Aaron Denney) Date: Tue Aug 14 15:57:24 2007 Subject: [Haskell-cafe] Re: defining last using foldr References: <12151145.post@talk.nabble.com> Message-ID: On 2007-08-14, Alexteslin wrote: > > Hi, > > I am trying to do the exercise which asks to define built-in functions > 'last' and 'init' using 'foldr' function, such as last "Greggery Peccary" = > 'y' > > the type for my function is: > > myLast :: [Char] -> Char > > I am not generalizing type so that make it less complicated. But what ever > i am trying would not work. The only function type foldr takes as an > argument is either (a->a->a) or (a->b->b) and none of the functions i found > that would match this type from Char to Char. So in other words should be > (Char->Char-Char). I can define the function without foldr but that misses > the point of the exercise. Folds replace the "cons" operator (:) with the function you pass it. If you want the tail of the list, you want what is on the right hand side of every cons (unless that's []). -- Aaron Denney -><- From overdrigzed at gmail.com Tue Aug 14 16:17:23 2007 From: overdrigzed at gmail.com (Rodrigo Queiro) Date: Tue Aug 14 16:09:01 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: <12151145.post@talk.nabble.com> References: <12151145.post@talk.nabble.com> Message-ID: <2eb8984a0708141317g120e377ci43ca7664d818347d@mail.gmail.com> I've found a way to do it, but it's not pretty. Hint: The function in the foldr first get the last value, and will need to keep it the whole way through. How can it tell if it is being given the last item or an earlier item? I'm generally not too good at the Socratic method, so feel free to email for some more help or my answer. On 14/08/07, Alexteslin wrote: > > Hi, > > I am trying to do the exercise which asks to define built-in functions > 'last' and 'init' using 'foldr' function, such as last "Greggery Peccary" = > 'y' > > the type for my function is: > > myLast :: [Char] -> Char > > I am not generalizing type so that make it less complicated. But what ever > i am trying would not work. The only function type foldr takes as an > argument is either (a->a->a) or (a->b->b) and none of the functions i found > that would match this type from Char to Char. So in other words should be > (Char->Char-Char). I can define the function without foldr but that misses > the point of the exercise. > > Any hint will be appreciated, > Thank you > -- > View this message in context: http://www.nabble.com/defining-last-using-foldr-tf4269357.html#a12151145 > Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From alexteslin at yahoo.co.uk Tue Aug 14 16:31:06 2007 From: alexteslin at yahoo.co.uk (Alexteslin) Date: Tue Aug 14 16:22:43 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> Message-ID: <12151694.post@talk.nabble.com> Well, i have tried cons (:) operator but when it passed to foldr doesn't work because cons operator operates first character and then the list but the foldr argument takes a function (a->a->a). Maybe i am missing the point here? Aaron Denney wrote: > > On 2007-08-14, Alexteslin wrote: >> >> Hi, >> >> I am trying to do the exercise which asks to define built-in functions >> 'last' and 'init' using 'foldr' function, such as last "Greggery Peccary" >> = >> 'y' >> >> the type for my function is: >> >> myLast :: [Char] -> Char >> >> I am not generalizing type so that make it less complicated. But what >> ever >> i am trying would not work. The only function type foldr takes as an >> argument is either (a->a->a) or (a->b->b) and none of the functions i >> found >> that would match this type from Char to Char. So in other words should >> be >> (Char->Char-Char). I can define the function without foldr but that >> misses >> the point of the exercise. > > Folds replace the "cons" operator (:) with the function you pass it. > If you want the tail of the list, you want what is on the right hand > side of every cons (unless that's []). > > -- > Aaron Denney > -><- > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > -- View this message in context: http://www.nabble.com/defining-last-using-foldr-tf4269357.html#a12151694 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From chaddai.fouche at gmail.com Tue Aug 14 17:16:01 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Tue Aug 14 17:07:38 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: <12151694.post@talk.nabble.com> References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> Message-ID: 2007/8/14, Alexteslin : > Well, i have tried cons (:) operator but when it passed to foldr doesn't work > because cons operator operates first character and then the list but the > foldr argument takes a function (a->a->a). Maybe i am missing the point > here? > What Aaron was saying was that in this list : 1 : 2 : 3 : 4 : [] A fold replaced the cons (:) by another function (and [] by another constant). Your problem isn't so easy to do with a foldr, a foldl would be easier and a foldr1 or foldl1 even better. Are you sure you can't use one of those other folds ? -- Jeda? From overdrigzed at gmail.com Tue Aug 14 17:16:25 2007 From: overdrigzed at gmail.com (Rodrigo Queiro) Date: Tue Aug 14 17:08:03 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: <12151694.post@talk.nabble.com> References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> Message-ID: <2eb8984a0708141416k5b8f2540n20200b87edc34607@mail.gmail.com> You can consider foldr to be continual modification of a state. The initial state is given as an argument, and then the (a -> b -> b) function is passed the next element of the list and the current state, and it returns the new state. foldr will then return the final state, from which the result can be extracted. Does that help? On 14/08/07, Alexteslin wrote: > > Well, i have tried cons (:) operator but when it passed to foldr doesn't work > because cons operator operates first character and then the list but the > foldr argument takes a function (a->a->a). Maybe i am missing the point > here? > > > Aaron Denney wrote: > > > > On 2007-08-14, Alexteslin wrote: > >> > >> Hi, > >> > >> I am trying to do the exercise which asks to define built-in functions > >> 'last' and 'init' using 'foldr' function, such as last "Greggery Peccary" > >> = > >> 'y' > >> > >> the type for my function is: > >> > >> myLast :: [Char] -> Char > >> > >> I am not generalizing type so that make it less complicated. But what > >> ever > >> i am trying would not work. The only function type foldr takes as an > >> argument is either (a->a->a) or (a->b->b) and none of the functions i > >> found > >> that would match this type from Char to Char. So in other words should > >> be > >> (Char->Char-Char). I can define the function without foldr but that > >> misses > >> the point of the exercise. > > > > Folds replace the "cons" operator (:) with the function you pass it. > > If you want the tail of the list, you want what is on the right hand > > side of every cons (unless that's []). > > > > -- > > Aaron Denney > > -><- > > > > _______________________________________________ > > Haskell-Cafe mailing list > > Haskell-Cafe@haskell.org > > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > > > > -- > View this message in context: http://www.nabble.com/defining-last-using-foldr-tf4269357.html#a12151694 > Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From wnoise at ofb.net Tue Aug 14 17:33:39 2007 From: wnoise at ofb.net (Aaron Denney) Date: Tue Aug 14 17:25:31 2007 Subject: [Haskell-cafe] Re: defining last using foldr References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> Message-ID: (Quoting reformatted. Try to have your responses below what you are responding to. It makes it easier to read as a conversation.) On 2007-08-14, Alexteslin wrote: > Aaron Denney wrote: >> Folds replace the "cons" operator (:) with the function you pass it. >> If you want the tail of the list, you want what is on the right hand >> side of every cons (unless that's []). > > Well, i have tried cons (:) operator but when it passed to foldr doesn't work > because cons operator operates first character and then the list but the > foldr argument takes a function (a->a->a). Maybe i am missing the point > here? I didn't say to use (:), I said foldr works by replacing (:) with some other function. foldr also takes a function of type (a -> b -> b). foldr f e replaces (first : (middle : (last : []))) with (first `f` (middle `f` (last `f` e))) You want last to be kept, so f x e = x this causes the overall pattern to reduce to (first `f` (middle `f` last)) This time you need f y last = last This means you need to discriminate between "e" and "last". If you make "e" the same type as last, you could accidentally compare them equal. So instead of using the same type, we want one with one more value. There is a standard one: "Maybe a", with constructors "Just a" and "Nothing". And you also need to promote last to this type with the constructor Just, because the result gets fed in on the right. -- Aaron Denney -><- From wnoise at ofb.net Tue Aug 14 17:52:25 2007 From: wnoise at ofb.net (Aaron Denney) Date: Tue Aug 14 17:44:21 2007 Subject: [Haskell-cafe] Re: defining last using foldr References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> Message-ID: On 2007-08-14, Chadda? Fouch? wrote: > 2007/8/14, Alexteslin : >> Well, i have tried cons (:) operator but when it passed to foldr doesn't work >> because cons operator operates first character and then the list but the >> foldr argument takes a function (a->a->a). Maybe i am missing the point >> here? >> > > What Aaron was saying was that in this list : > 1 : 2 : 3 : 4 : [] > A fold replaced the cons (:) by another function (and [] by another constant). > > Your problem isn't so easy to do with a foldr, a foldl would be easier > and a foldr1 or foldl1 even better. Are you sure you can't use one of > those other folds ? The problem with foldl is that you can't easily make it polymorphic because of how the null case is handled. foldl1 and foldr1 are trivial, true. -- Aaron Denney -><- From westondan at imageworks.com Tue Aug 14 18:16:54 2007 From: westondan at imageworks.com (Dan Weston) Date: Tue Aug 14 18:08:32 2007 Subject: [Haskell-cafe] Why monad tutorials don't work In-Reply-To: <46C1C24F.1030905@cisco.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> Message-ID: <46C229D6.7080804@imageworks.com> Conor McBride and Ross Paterson said it best in the introduction to their paper "Applicative programming with effects" [1]: "This is the story of a pattern that popped up time and again in our daily work,..., until the temptation to abstract it became irresistible. Let us illustrate with some examples." Translation: Unless you've broken your back hauling water by hand, you'll never truly "get" the utility (even joy) of installing plumbing. To help you speed through (but not skip over) this necessary hauling drudgery, we will show the movie of us doing it in fast forward, and ask you to make the leap of faith that the sweat dripping off our brows is real, not sprayed on to make us look impressive. The fatal flaw of all tutorials is that the easier they make things seem, the less visceral understanding of the importance and benefit the reader will have. So here's my 30-second monad meta-metaphor: Monads are like wrapping paper, so the surprise isn't spoiled before Christmas. Every present can be wrapped, the paper doesn't damage what it covers, and there's no need to wrap it twice, it's no more opaque than wrapping it once. But you know better! You don't want to bother wrapping your presents. Your children promise not to peek until Christmas day anyway. After first, you have plenty of time to watch them. But as the holidays approach, you get busier, and pretty soon you have to choreograph your entire day just to divert their attention. It only takes one slip-up to ruin the surprise, so you spend a great deal of effort making this happen. Your mother (who has been down this route before with you) knows from experience that it is just easier to use wrapping paper, but you don't believe her. She's so old-fashioned and dogmatic! In a misguided attempt to be helpful, she whips out the dreaded Monad Tutorial Book of All Human Wisdom and explains the concept of Present Wrapping. The authors have PhDs in the science of concealment and compare the common properties of paper, boxes, sleight-of-hand, and one-way mirrors, but your eyes glaze over because you don't care about mirrors, you just have a present. Helpful friends share their war stories, but as you're not a bad parent like they are, you don't fall for their arrogant attempts to educate you and you point out how in each case their experience doesn't fit your needs. The most amazing thing in this metaphor is the strangely irrepressible joy that those who've mastered the art of present wrapping have to share their discovery with others. I guess some things are just too good to keep to yourself! Sadly, these tend to be the things you can't even give away without getting flak for it... :( Dan Weston [1] http://www.soi.city.ac.uk/~ross/papers/Applicative.html Lanny Ripple wrote: > Having just gone through all the tutorials and things (again but this > time I think it stuck) the Haskell community is on the wrong track as > far as teaching Monads to new programmers. > > If I were teaching addition and multiplication to children I wouldn't > start with, "We'll begin by defining an algebraic structure named a > "Group". From there we'll expand our concept to a "Ring" and "Field". > A group is a set and a binary operator usually named "+" (or sometimes > "*") such that...". > > No no no. You start with, "You all know how to count from one to 10. > If we have 1 item and we 'add' another 1 item we have 2 items. We write > this 1+1=2." > > The tutorials seriously need to step back and start with something like, > "To enforce order of evaluation we evaluate closures* returning a > defined type. The first closure will feed its result to the second > which will in turn feed it's result to the third. Since the third > closure can't be evaluated without having the results from the second > and first (and thus they had to be evaluated earlier in time) we get a > defined evaluation sequence. Here are some examples..." > > (* Even using the word 'closure' is scary for those not familiar with > them.) > > Then, like "Monads For Functional Programming" (the paper that finally > clicked Monads for me) you point out that evaluating all these closures > returning a defined type in various ways form a structure (which you can > then explain) and we can use that structure and change out the > underlying effect(s) as needed. > > Now of course if your new programmer has the the necessary background > you can throw them in the deep end. But don't do that to someone coming > at the language from something like Java learned out of a business > degree course. (My background is a CS degree with math minor and it > still took two go-s at Haskell before I got as far as understanding what > folks were talking about with Monads. Wish I had found Wadler's MFFP > the first time around.) Where are the shallow end tutorials? (Don't > get me wrong. The tutorials are good but there is also a place for the > "learn-by-rote with lots of examples" ones too.) > > $0.02, > -ljr > > PS - Not so much directed at Ronald's post but his was convenient to get > me on my soapbox. > > Ronald Guida wrote: >> My present goal is to understand monads well enough to be able to >> explain them to others. I wonder if it's possible to create a >> tutorial that explains monads well enough so that they just "make >> sense" or "click" for people. From ithika at gmail.com Tue Aug 14 18:27:25 2007 From: ithika at gmail.com (Dougal Stanton) Date: Tue Aug 14 18:19:02 2007 Subject: [Haskell-cafe] Why monad tutorials don't work In-Reply-To: <46C229D6.7080804@imageworks.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> Message-ID: <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> On 14/08/07, Dan Weston wrote: [snips another metaphor for monadic programming] No offence to Dan, whose post I enjoyed. The concept of wrapping is as close a metaphor as we seem to get without disagreements. But this has brought me to a realisation, after Paul Erdos: The Haskell community is a machine for converting coffee to monad tutorials. In the spirit of the venture, I will now suggest that someone points out that they don't like coffee, and that I haven't allowed for arrow tutorials ;-) Cheers, D. From chaddai.fouche at gmail.com Tue Aug 14 18:39:19 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Tue Aug 14 18:30:56 2007 Subject: [Haskell-cafe] Re: defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> Message-ID: 2007/8/14, Aaron Denney : > The problem with foldl is that you can't easily make it polymorphic > because of how the null case is handled. foldl1 and foldr1 are trivial, > true. > The original "last" fail on empty list, it's far easier to obtain the same semantic with foldl than with foldr, in fact it isn't hard at all to make it polymorphic without hassle (contrary to the foldr case) _if_ you remember that there _is_ a value in Haskell wich belongs to every type. -- Jeda? From mvanier at cs.caltech.edu Tue Aug 14 18:40:31 2007 From: mvanier at cs.caltech.edu (Michael Vanier) Date: Tue Aug 14 18:32:19 2007 Subject: [Haskell-cafe] Why monad tutorials don't work In-Reply-To: <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> Message-ID: <46C22F5F.90101@cs.caltech.edu> As you know, an arrow tutorial is like a wrapper around a monad tutorial, sort of like a container around it that can do extra actions with sufficient lifting. The appropriate higher-order function to convert monad tutorials to arrow tutorials will be left as an exercise to the reader. I'm becoming more and more convinced that metaphors for monads do more harm than good. From now on I'm going to describe monads as purely abstract entities that obey certain laws, and that _in certain instances_ can be viewed to be like containers, or actions, or donuts, or whatever. In other words, a monad is an abstract thing that can generate things that we can metaphorize, but it's pointless (point-free?) to try to capture the entire concept in a single metaphor. I'm reminded of a physics teacher who was having a similar problem explaining the concept of tensors, until he said that "a tensor is something that transforms like a tensor does!". So a monad is something that behaves like a monad does. Mike (who obviously hasn't had nearly enough coffee today) Dougal Stanton wrote: > On 14/08/07, Dan Weston wrote: > > [snips another metaphor for monadic programming] > > No offence to Dan, whose post I enjoyed. The concept of wrapping is as > close a metaphor as we seem to get without disagreements. But this has > brought me to a realisation, after Paul Erdos: > > The Haskell community is a machine for converting coffee to monad tutorials. > > In the spirit of the venture, I will now suggest that someone points > out that they don't like coffee, and that I haven't allowed for arrow > tutorials ;-) > > Cheers, > > D. > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From wnoise at ofb.net Tue Aug 14 18:47:54 2007 From: wnoise at ofb.net (Aaron Denney) Date: Tue Aug 14 18:39:47 2007 Subject: [Haskell-cafe] Re: defining last using foldr References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> Message-ID: On 2007-08-14, Chadda? Fouch? wrote: > 2007/8/14, Aaron Denney : >> The problem with foldl is that you can't easily make it polymorphic >> because of how the null case is handled. foldl1 and foldr1 are trivial, >> true. >> > > The original "last" fail on empty list, it's far easier to obtain the > same semantic with foldl than with foldr, in fact it isn't hard at all > to make it polymorphic without hassle (contrary to the foldr case) > _if_ you remember that there _is_ a value in Haskell wich belongs to > every type. Hah. True. That does simplify things considerably. Still, I'd call that an infelicity in last (and head, for that matter), and would rather have such errors handled at the call site than making the entire program fall over. -- Aaron Denney -><- From dpiponi at gmail.com Tue Aug 14 19:02:31 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Tue Aug 14 18:54:08 2007 Subject: [Haskell-cafe] Why monad tutorials don't work In-Reply-To: <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> Message-ID: <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> On 8/14/07, Dan Weston wrote: > Conor McBride and Ross Paterson said it best in the introduction to > their paper "Applicative programming with effects" [1]: As von Neumann said: "Young man, in mathematics you don't understand things, you just get used to them." Getting used to something is, practically by definition, something that you can't do just by reading the ultimate tutorial. You just have to write the code, see the pattern happen again and again, and abstract it. There's no short cut. (Well...sometimes...) On 8/14/07, Michael Vanier wrote: > I'm reminded of > a physics teacher who was having a similar problem explaining the concept of tensors, until he said > that "a tensor is something that transforms like a tensor does!". Grrr...must...hold...my...tongue... -- Dan From derek.a.elkins at gmail.com Tue Aug 14 19:34:54 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Tue Aug 14 19:26:37 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C1E908.3070401@cisco.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <1187111238.5456.8.camel@derek-laptop> <46C1E908.3070401@cisco.com> Message-ID: <1187134495.5462.5.camel@derek-laptop> On Tue, 2007-08-14 at 12:40 -0500, Lanny Ripple wrote: > Derek Elkins wrote: > > What people need to do is stop reading two page blog posts by someone > > who's "just got" monads and read the well-written peer-reviewed papers > > I have taught many people to program in group settings and > individually in my career. I have referred them to many > tutorials. I have used many examples from tutorials I thought > were useful. I can't recall a single time I've ever turned to a > beginner and said, "And you really should brush up on the > peer-reviewed papers to learn this part." How about a book? You've never recommended a book? But even so, where did I say tutorial? The -are- good monad tutorials, they are just horribly out-weighed by bad ones. Further, having a tutorial as supplement to person-to-person education is totally different from trying to learn purely from tutorials. Also, what is wrong with papers or recommending them? Finally, how often have you been part of a community where the primary mode of documentation is a research paper... > > > by the people who clearly know what they are talking about. Luckily, > > for monads applied to Haskell we have Wadler, a witty, enjoyable and > > clear writer/speaker. All of Wadler's monad "introductions" are > > readable by anyone with a basic grasp of Haskell. You certainly don't > > need to be even remotely an academic to understand them. I'm willing to > > bet that many people who say they don't understand monads and have read > > "every tutorial about them" haven't read -any- of Wadler's papers. > I'm confused. Are you praising Wadler or bashing the tutorials > (or both)? *I* was carping about the tutorials (and even > mentioned that Wadler was my breakthrough) so I suspect we are in > violent agreement. I'm praising Wadler and bashing the good majority of monad tutorials, but not all of them. Mostly I'm pointing out an unreasonable aversion to reading papers, as if a paper couldn't possibly be understandable. From mage2k at gmail.com Tue Aug 14 19:42:13 2007 From: mage2k at gmail.com (Erik Jones) Date: Tue Aug 14 19:33:51 2007 Subject: [Haskell-cafe] Why monad tutorials don't work In-Reply-To: <46C22F5F.90101@cs.caltech.edu> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> Message-ID: <86ac1b9c0708141642o29abbb6dj32bebd67f5d7d268@mail.gmail.com> On 8/14/07, Michael Vanier wrote: I'm becoming more and more convinced that metaphors for monads do more harm > than good. From now on > I'm going to describe monads as purely abstract entities that obey certain > laws, and that _in > certain instances_ can be viewed to be like containers, or actions, or > donuts, or whatever. In > other words, a monad is an abstract thing that can generate things that we > can metaphorize, but it's > pointless (point-free?) to try to capture the entire concept in a single > metaphor. I'm reminded of > a physics teacher who was having a similar problem explaining the concept > of tensors, until he said > that "a tensor is something that transforms like a tensor does!". So a > monad is something that > behaves like a monad does. Nice. As a Haskell beginner (with previous imperative programming experience) I subscribed to this list today to say exactly that. I spent weeks reading different tutorials that attempted to enlighten by means of various abstractions before I finally found one that simply showed the mechanics of the required operators and rules (sounds less formal than laws) that they need to hold to. Even then I hadn't quite "got it" until I met SPJ at OSCON and heard myself saying, "All monads are are labels in front of values with specific operations defined on them." His reply was, "Yes! Very abstract isn't it?" Then I'd "got it", or realized that I had but hadn't realized it (if that makes any sense...), as that sequential exchange of ideas (hah!) brought me to the realization that the "abstractions" that monads are held to represent are solely in the usage semantics of aforesaid operations and, while technically the actual labels used don't matter, we pick labels whose meaning match those semantics. So, yes, don't start by giving any extra meaning to the basic monad operations than their mechanics. Then show how they can be use to "implement" abstractions like state, uncertainty, etc... Oh yeah, start with terms that programmers already know, e.g. encapsulation v. wrappers. Then switch. Don't start with terminology that's different and explain the mappings, start with the familiar than follow the mappings to the different. -- Erik Jones mage2k@gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/2e45befa/attachment.htm From mvanier at cs.caltech.edu Tue Aug 14 20:53:05 2007 From: mvanier at cs.caltech.edu (Michael Vanier) Date: Tue Aug 14 20:44:57 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <1187134495.5462.5.camel@derek-laptop> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <1187111238.5456.8.camel@derek-laptop> <46C1E908.3070401@cisco.com> <1187134495.5462.5.camel@derek-laptop> Message-ID: <46C24E71.6040705@cs.caltech.edu> For what it's worth, the nature of Haskell is such that you do (at least currently) have to spend a lot of time reading research papers to understand what's going on. Maybe that will change sometime, but probably not soon. This ties in to the open-endedness of Haskell; I sometimes think that really understanding all of Haskell is like really understanding all of mathematics. This is frustrating, but it's also what makes the language so rewarding. I guess what I'm saying is: get used to it, it's not so bad. Mike Derek Elkins wrote: > On Tue, 2007-08-14 at 12:40 -0500, Lanny Ripple wrote: >> Derek Elkins wrote: >>> What people need to do is stop reading two page blog posts by someone >>> who's "just got" monads and read the well-written peer-reviewed papers >> I have taught many people to program in group settings and >> individually in my career. I have referred them to many >> tutorials. I have used many examples from tutorials I thought >> were useful. I can't recall a single time I've ever turned to a >> beginner and said, "And you really should brush up on the >> peer-reviewed papers to learn this part." > > How about a book? You've never recommended a book? But even so, where > did I say tutorial? The -are- good monad tutorials, they are just > horribly out-weighed by bad ones. Further, having a tutorial as > supplement to person-to-person education is totally different from > trying to learn purely from tutorials. Also, what is wrong with papers > or recommending them? Finally, how often have you been part of a > community where the primary mode of documentation is a research paper... > >>> by the people who clearly know what they are talking about. Luckily, >>> for monads applied to Haskell we have Wadler, a witty, enjoyable and >>> clear writer/speaker. All of Wadler's monad "introductions" are >>> readable by anyone with a basic grasp of Haskell. You certainly don't >>> need to be even remotely an academic to understand them. I'm willing to >>> bet that many people who say they don't understand monads and have read >>> "every tutorial about them" haven't read -any- of Wadler's papers. > > >> I'm confused. Are you praising Wadler or bashing the tutorials >> (or both)? *I* was carping about the tutorials (and even >> mentioned that Wadler was my breakthrough) so I suspect we are in >> violent agreement. > > I'm praising Wadler and bashing the good majority of monad tutorials, > but not all of them. Mostly I'm pointing out an unreasonable aversion > to reading papers, as if a paper couldn't possibly be understandable. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From gregorypropf at yahoo.com Tue Aug 14 20:55:19 2007 From: gregorypropf at yahoo.com (Gregory Propf) Date: Tue Aug 14 20:46:56 2007 Subject: [Haskell-cafe] Re:Explaining monads Message-ID: <378301.94851.qm@web31401.mail.mud.yahoo.com> Sorry to spam you Jeff, again I sent my email to the poster rather than the list. I'm using Yahoo beta webmail and don't see a way to set it to reply to the list rather than the originator. Anyway, this was my post: Hence the need to perform a "run" operation like runIdentity, evalState or runParser (for Parsec) to get something useful to happen. Except for lists we don't seem to do this. I suppose lists are so simple that the operators :, ++ and the [] constructor do all we ever need with them. Finally there is no runIO because "main" is essentially that function in every real program? - Greg ----- Original Message ---- From: Jeff Polakow To: lanny@cisco.com Cc: haskell-cafe-bounces@haskell.org; Haskell-Cafe Sent: Tuesday, August 14, 2007 8:45:06 AM Subject: Re: [Haskell-cafe] Explaining monads One general intuition about monads is that they represent computations rather than simple (already computed) values: Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. ____________________________________________________________________________________ Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/d9cfa598/attachment.htm From brian at ithil.org Tue Aug 14 21:25:04 2007 From: brian at ithil.org (Brian Brunswick) Date: Tue Aug 14 21:16:42 2007 Subject: [Haskell-cafe] Re:Explaining monads In-Reply-To: <378301.94851.qm@web31401.mail.mud.yahoo.com> References: <378301.94851.qm@web31401.mail.mud.yahoo.com> Message-ID: <6f680f6d0708141825t54ecc22bv7c123efbd9b70e94@mail.gmail.com> On 15/08/07, Gregory Propf wrote: ----- Original Message ---- From: Jeff Polakow One general intuition about monads is that they represent computations rather than simple (already computed) values: I still want to re-iterate that they represent /complex/ computations - multiple, conditional results, extra stuff etc. Hence the need to perform a "run" operation like runIdentity, evalState or > runParser (for Parsec) to get something useful to happen. Except for lists > we don't seem to do this. I suppose lists are so simple that the operators > :, ++ and the [] constructor do all we ever need with them. Finally there > is no runIO because "main" is essentially that function in every real > program? - Greg > What the run functions do is unwrap the monad. They take apart the 'm a' and give you back whatever a's might be inside, and whatever extra stuff too. (Also feeding extra stuff in when m is like that) Doing that will involve actually evaluating the value, forcing all the data dependencies and making the 'actions' happen. If the monad type 'm a' is already a type we can take apart directly (list, maybe etc.) theres no need for a run function. Note that of course unsafePerformIO is runIO. Its just that it doesn't really nest safely, so we like to only use the top level one from main. -- Brian_Brunswick____brian@ithil.org____Wit____Disclaimer____!Shortsig_rules! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070815/d47b58b3/attachment-0001.htm From mattcbro at earthlink.net Tue Aug 14 21:54:04 2007 From: mattcbro at earthlink.net (SevenThunders) Date: Tue Aug 14 21:45:40 2007 Subject: [Haskell-cafe] GHC linking problems Message-ID: <12155220.post@talk.nabble.com> I have a large Haskell/C project that needs to be linked against an even larger set of C libraries and object files (OpNet) on a linux box (Fedora Core 7). So far I have been able to link my Haskell libraries to some C test code containing a main function without incident. However the link flags are very complex having been extracted from ghc. (e.g. it requires a host of -u flags and then a bunch of links to external C libraries including a long list of Haskell libraries.) Unfortunately control over the OpNet compilation and linking process is weak at best. Moreover it is not clear how the linking occurs and there is some suspicion that it ultimately creates a dynamic link library which it loads from some external process (the exact calls to gcc are hidden). During the OpNet build we get the following error /usr/lib/ghc-6.6.1/libHSrts.a(Main.o): In function `main': Main.c:(.text+0x22): undefined reference to `__stginit_ZCMain' Main.c:(.text+0x43): undefined reference to `ZCMain_main_closure' collect2: ld returned 1 exit status I do not get this error when statically linking my libraries to a standalone C function containing a main() function. What should I look for? Are there known work arounds to this problem? It's troubling that exporting Haskell to C should be this problematic. Unfortunately I can not use ghc to compile the OpNet code as you might imagine. -- View this message in context: http://www.nabble.com/GHC-linking-problems-tf4270650.html#a12155220 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From william.wood3 at comcast.net Tue Aug 14 23:46:39 2007 From: william.wood3 at comcast.net (Bill Wood) Date: Tue Aug 14 23:40:11 2007 Subject: [Haskell-cafe] Why monad tutorials don't work In-Reply-To: <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> Message-ID: <1187149599.24464.4.camel@localhost> On Tue, 2007-08-14 at 16:02 -0700, Dan Piponi wrote: . . . > On 8/14/07, Michael Vanier wrote: > > I'm reminded of > > a physics teacher who was having a similar problem explaining the concept of tensors, until he said > > that "a tensor is something that transforms like a tensor does!". > > Grrr...must...hold...my...tongue... Dan, as a former student of a clone of that physics teacher, I am really interested in what you will say when you fail to hold your tongue. -- Bill Wood From dellaq at ml1.net Wed Aug 15 00:04:02 2007 From: dellaq at ml1.net (John =?utf-8?b?RGVsbFwnQXF1aWxh?=) Date: Tue Aug 14 23:55:51 2007 Subject: [Haskell-cafe] Re: Error building takusen with Cabal-1.1.6.2 References: Message-ID: That fixed my problem. Thank you very much. Regards, John From mvanier at cs.caltech.edu Wed Aug 15 00:09:02 2007 From: mvanier at cs.caltech.edu (Michael Vanier) Date: Wed Aug 15 00:00:50 2007 Subject: [Haskell-cafe] Why monad tutorials don't work In-Reply-To: <1187149599.24464.4.camel@localhost> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> <1187149599.24464.4.camel@localhost> Message-ID: <46C27C5E.5020103@cs.caltech.edu> Bill Wood wrote: > On Tue, 2007-08-14 at 16:02 -0700, Dan Piponi wrote: > . . . >> On 8/14/07, Michael Vanier wrote: >>> I'm reminded of >>> a physics teacher who was having a similar problem explaining the concept of tensors, until he said >>> that "a tensor is something that transforms like a tensor does!". >> Grrr...must...hold...my...tongue... > > Dan, as a former student of a clone of that physics teacher, I am really > interested in what you will say when you fail to hold your tongue. > > -- Bill Wood > I have to admit I was wondering the same thing myself. Mike From alex at alexjacobson.com Wed Aug 15 00:29:53 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Wed Aug 15 00:21:37 2007 Subject: [Haskell-cafe] ANN: HAppS-Data 0.9: XML, Pairs, HList, deriveAll Message-ID: <46C28141.1000204@alexjacobson.com> We've refactored the happs repos and are now going to releasing components of HAppS as individual useful packages. HAppS-Data is the first one. Don't pull a tag, pull the most recent stuff in the repos. --- HAppS-Data v0.9: XML, Name/Value Pairs, HList, deriveAll * toXml and fromXml transform your haskell values to and from XML. Declare your own instances of class Xml to customize the Xml representation. * toPairs and fromPairs transform haskell values to and from name-value pairs (e.g. for url-encoded data). Pairs are converted between xpath expressions. Use toPairsX if you want a conversion without the top level constructor, fromPairs can handle that as long as your type has only one top level constructor. * toHTMLForms to produce an HTML forms representation of your data that can be consumed by fromPairs in a urldecoding context. toHTMLForms uses toPairsX for shorter input field names. * $(deriveAll) to batch derive Default and as well as the standard derivable without all the boring per data "deriving" declarations * Default missing values by declaring your own instances of class Default or have default values derived autotomatically. * Normalize your values by declaring your own instance of class Normalize. * Type safe easy-to-use heterogenous collections. t1 .&. t2 .&. t3 are a heterogenous lists of values. (HasT hlist t) is a class constraint to that the hlist contains a particular type. (x hlist)::t obtains a value of type t from inside the hlist. (u hlist v) updates the hlist with the value v if the hlist has type. x and u return compile time errors if the type is not inside the hlist. fromPairs is currently broken for hlist. darcs get http://happs.org/HAppS/HAppS-Data From asumu at cyberberry.com Wed Aug 15 00:58:22 2007 From: asumu at cyberberry.com (Asumu Takikawa) Date: Wed Aug 15 00:50:30 2007 Subject: [Haskell-cafe] ANNOUNCE: Guihaskell and PropLang 0.1 Message-ID: <20070815045822.GA5154@cyberberry.com> Hello Haskellers. I'm one of the Google Summer of Code students for '07 and I'd like to announce the project my mentor, Neil Mitchell, and I have been working on. == GuiHaskell Guihaskell is a graphical REPL using PropLang, a GUI combinator library built on top of Gtk2hs, which aims to be an IDE for Haskell written in Haskell. It's still rough around the edges, so think of this as an alpha release. As such, I'd appreciate any feedback very much! Here's a feature list for 0.1: * Support for GHCi (default) and Hugs * Quick switching between compilers * Simple one-click profiling * Command history This first release of Guihaskell is mostly infrastructure. For future releases I aim to integrate more tools like Cabal and make it easier to use with an editor. == PropLang PropLang is a GUI library built on Gtk2hs that allows for high level design. The GUI is expressed as a series of relationships between GUI elements and data sources. Here's a "Hello World" example: import PropLang.Gtk import PropLang.Event main = do initPropLang window <- getWindow "foobar.glade" "wndFoo" let tb = getCtrl window "button" :: ToolButton tb!onClicked += putStrLn "Hello World!" showWindowMain window This example prints "Hello World!" when the user presses a button defined in a Glade file. PropLang is used with glade to define the interface. You can define more complicated relationships using the combinators in PropLang.Variable. Here's a snippet from GuiHaskell: tie (txtSelect!text) filename (\t -> if null t then Nothing else Just t) (maybe "" id) "tie" takes two PropLang variables and relates them so that when one is updated, it will inject its value into another. It also takes two functions to run on the data before injection. This snippet is used to tie the representation of the currently selected file in GuiHaskell (a Maybe String) to Gtk's TextView buffer (a String). If you injected a new value into filename... filename -< Nothing then txtSelect's text buffer would be set to "". You can also build other behaviors into PropLang variables to do interesting things. GuiHaskell has a configuration API built around PropLang. Configuration items are defined as special PropLang variables: filename <- newVarWithName "selected_filename" (newConfValueWithDefault Nothing "selected_filename") "newVarWithName" in PropLang.Variable lets you make new variables with custom actions to retrieve and set values. "newConfValue" is defined in GuiHaskell to serialize configuration items to disk so they can be read back after closing the program. For more information you can generate the Proplang docs with haddock. == Install Get the packages here: http://hackage.haskell.org/packages/archive/GuiHaskell/0.1/GuiHaskell-0.1.tar.gz http://hackage.haskell.org/packages/archive/proplang/0.1/proplang-0.1.tar.gz Install with cabal: runhaskell Setup.lhs configure runhaskell Setup.lhs build runhaskell Setup.lhs install == You can send feedback to my e-mail, the list, or contact me on IRC (I'm Shimei on #haskell). Thanks. Cheers, Asumu Takikawa -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070814/df99216a/attachment.bin From miguelimo38 at yandex.ru Wed Aug 15 01:11:56 2007 From: miguelimo38 at yandex.ru (Miguel Mitrofanov) Date: Wed Aug 15 01:05:10 2007 Subject: [Haskell-cafe] Why monad tutorials don't work In-Reply-To: <46C27C5E.5020103@cs.caltech.edu> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> <1187149599.24464.4.camel@localhost> <46C27C5E.5020103@cs.caltech.edu> Message-ID: <1118701012.20070815091156@yandex.ru> >>> Grrr...must...hold...my...tongue... >> >> Dan, as a former student of a clone of that physics teacher, I am really >> interested in what you will say when you fail to hold your tongue. >> >> -- Bill Wood >> MV> I have to admit I was wondering the same thing myself. So was I. From ketil at ii.uib.no Wed Aug 15 03:50:48 2007 From: ketil at ii.uib.no (Ketil Malde) Date: Wed Aug 15 03:42:26 2007 Subject: [Haskell-cafe] Bathroom reading In-Reply-To: References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> Message-ID: <1187164248.6553.4.camel@nmd9999> On Tue, 2007-08-14 at 17:22 +0200, Bas van Dijk wrote: > On 8/14/07, Dougal Stanton wrote: > > I'm looking for cool but mind-bending examples of functional brilliance. > Maybe: > > http://www.haskell.org/haskellwiki/Blow_your_mind > http://haskell.org/haskellwiki/Research_papers/Functional_pearls The "Evolution of a Haskell Programmer" is cute: http://www.willamette.edu/~fruehr/haskell/evolution.html -k From ithika at gmail.com Wed Aug 15 05:11:02 2007 From: ithika at gmail.com (Dougal Stanton) Date: Wed Aug 15 05:02:40 2007 Subject: [Haskell-cafe] ANNOUNCE: Guihaskell and PropLang 0.1 In-Reply-To: <20070815045822.GA5154@cyberberry.com> References: <20070815045822.GA5154@cyberberry.com> Message-ID: <2d3641330708150211q48356a7ao7de9b5362825afa0@mail.gmail.com> On 15/08/07, Asumu Takikawa wrote: > == GuiHaskell > > Guihaskell is a graphical REPL using PropLang, a GUI combinator library > built on top of Gtk2hs, which aims to be an IDE for Haskell written in > Haskell. It's still rough around the edges, so think of this as an alpha > release. As such, I'd appreciate any feedback very much! Looks interesting. I couldn't see anywhere whether it has any OS dependencies. Is it cross platform? Cheers, D. From ndmitchell at gmail.com Wed Aug 15 08:23:41 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Wed Aug 15 08:15:23 2007 Subject: [Haskell-cafe] ANNOUNCE: Guihaskell and PropLang 0.1 In-Reply-To: <2d3641330708150211q48356a7ao7de9b5362825afa0@mail.gmail.com> References: <20070815045822.GA5154@cyberberry.com> <2d3641330708150211q48356a7ao7de9b5362825afa0@mail.gmail.com> Message-ID: <404396ef0708150523v243d35edw82807b74b8eb027b@mail.gmail.com> Hi Dougal, It's cross platform, and will use GHC and Hugs if they are already installed. Thanks Neil On 8/15/07, Dougal Stanton wrote: > On 15/08/07, Asumu Takikawa wrote: > > == GuiHaskell > > > > Guihaskell is a graphical REPL using PropLang, a GUI combinator library > > built on top of Gtk2hs, which aims to be an IDE for Haskell written in > > Haskell. It's still rough around the edges, so think of this as an alpha > > release. As such, I'd appreciate any feedback very much! > > Looks interesting. I couldn't see anywhere whether it has any OS > dependencies. Is it cross platform? > > Cheers, > > D. > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From dominic.steinitz at blueyonder.co.uk Wed Aug 15 08:50:42 2007 From: dominic.steinitz at blueyonder.co.uk (Dominic Steinitz) Date: Wed Aug 15 08:42:25 2007 Subject: [Haskell-cafe] Re: Re[2]: Why monad tutorials don't work References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> <1187149599.24464.4.camel@localhost> <46C27C5E.5020103@cs.caltech.edu> <1118701012.20070815091156@yandex.ru> Message-ID: Miguel Mitrofanov yandex.ru> writes: > > >>> Grrr...must...hold...my...tongue... > >> > >> Dan, as a former student of a clone of that physics teacher, I am really > >> interested in what you will say when you fail to hold your tongue. > >> > >> -- Bill Wood > >> > > MV> I have to admit I was wondering the same thing myself. > > So was I. > I'm guessing that Dan means that thinking of tensors as things that transform between co-ordinate systems in a certain way (e.g. via the Jacobian of the transition maps) isn't a terribly good way of thinking about them. Vector fields, co-vector fields and tensor fields are really co-ordinate independent notions and the transformation laws (if I may call them that) are a consequence of the way they transform under (smooth) maps. But perhaps this is better discussed on a differential geometry mailing list? Dominic. From A.M.Gimblett at swansea.ac.uk Wed Aug 15 08:58:15 2007 From: A.M.Gimblett at swansea.ac.uk (Andy Gimblett) Date: Wed Aug 15 08:49:51 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C24E71.6040705@cs.caltech.edu> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <1187111238.5456.8.camel@derek-laptop> <46C1E908.3070401@cisco.com> <1187134495.5462.5.camel@derek-laptop> <46C24E71.6040705@cs.caltech.edu> Message-ID: <20070815125815.GA10680@cspcag2.swan.ac.uk> On Tue, Aug 14, 2007 at 05:53:05PM -0700, Michael Vanier wrote: > > For what it's worth, the nature of Haskell is such that you do (at > least currently) have to spend a lot of time reading research papers > to understand what's going on. Maybe that will change sometime, but > probably not soon. This ties in to the open-endedness of Haskell; I > sometimes think that really understanding all of Haskell is like > really understanding all of mathematics. This is frustrating, but > it's also what makes the language so rewarding. I guess what I'm > saying is: get used to it, it's not so bad. At AngloHaskell, one of Phillipa's slides referred to Haskell as a "programming language theory gateway drug" - and was clearly of the opinion that this was A Good Thing. -- Andy Gimblett Computer Science Department University of Wales Swansea http://www.cs.swan.ac.uk/~csandy/ From loppermann at acm.org Wed Aug 15 09:04:16 2007 From: loppermann at acm.org (Lars Oppermann) Date: Wed Aug 15 08:55:52 2007 Subject: [Haskell-cafe] Haskell for the Enterprise (topic for a MSc dissertation?) Message-ID: Hi All, This is my first post here, so I'll start with a quick introduction... I live and work in Hamburg, Germany. My day job is as a software engineer at Sun Microsystems at the OpenOffice.org development team where I'm mostly doing XML (ODF) related things. Beside of that, I'm currently pursuing an M.Sc degree in software engineering in a part-time post graduate program where I am now nearing the phase where I have to develop a topic for my dissertation. Apart from a little dabbling with Miranda during my undergraduate CS days I haven't touched functional programming ever since and have been doing Java, C# and C++ most of the time. However, I have over the last few month "fallen in love" with the great expressiveness offered by Haskell and through that have gained some great new perspectives and discovered new ways to think when writing programs. Consequently, my idea to combine all of this into a topic for my dissertation is to write about the existing and potential benefits (and shortcomings) of a functional programming language for the development of typical enterprise applications (especially with regards to more and more concepts from functional programming being adopted in imperative languages). I would start off with an existing J2EE application, analyze the abstractions and patterns that it uses. I will then discuss similar and alternative abstractions and patterns available in functional programming which can be applied in order to solve the same problem in a functional setting, leveraging some existing infrastructure, such as HAppS. What would follow is a comparison of the two resulting applications from a software engineering standpoint: How maintainable are these implementations? How can they be tested? Can formal validation techniques be applied to parts of the functional implementation that can be used to establish its correctness. Maybe analysis of performance... One of my potential supervisors for the dissertation has already indicated some interest in the topic so it all looks quite well to me. The overview that I gave above obviously needs much more elaboration, but as I said, I have just started developing topics. I would love to hear your comments on this. Has this been done over and over already? Are there any source which you think of from the top of your head which I should check out? Books that you would want to recommend? As I wrote above, I'm quite new to Haskell. Thus if anyone wants to recommend some readings specifically on the aspect of modeling in a functional environment I'd be happy to hear about that too. All the best, Lars -- Lars Oppermann Hamburg, Germany -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070815/1bdd53bc/attachment.htm From A.M.Gimblett at swansea.ac.uk Wed Aug 15 09:05:04 2007 From: A.M.Gimblett at swansea.ac.uk (Andy Gimblett) Date: Wed Aug 15 08:56:40 2007 Subject: [Haskell-cafe] Re: Re[2]: Why monad tutorials don't work In-Reply-To: References: <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> <1187149599.24464.4.camel@localhost> <46C27C5E.5020103@cs.caltech.edu> <1118701012.20070815091156@yandex.ru> Message-ID: <20070815130504.GB10680@cspcag2.swan.ac.uk> On Wed, Aug 15, 2007 at 12:50:42PM +0000, Dominic Steinitz wrote: > Miguel Mitrofanov yandex.ru> writes: > > > >>> Grrr...must...hold...my...tongue... > > >> > > >> Dan, as a former student of a clone of that physics teacher, I am really > > >> interested in what you will say when you fail to hold your tongue. > > > > MV> I have to admit I was wondering the same thing myself. > > > > So was I. > > > I'm guessing that Dan means that thinking of tensors as things that transform > between co-ordinate systems in a certain way (e.g. via the Jacobian of the > transition maps) isn't a terribly good way of thinking about them. Vector > fields, co-vector fields and tensor fields are really co-ordinate independent > notions and the transformation laws (if I may call them that) are a > consequence of the way they transform under (smooth) maps. But perhaps this is > better discussed on a differential geometry mailing list? I assumed he was just trying not to sing the "Spider Pig" song. ( http://uk.youtube.com/watch?v=5XQ_GWKvDE0 ) ;-) -- Andy Gimblett Computer Science Department University of Wales Swansea http://www.cs.swan.ac.uk/~csandy/ From chaddai.fouche at gmail.com Wed Aug 15 09:30:59 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Wed Aug 15 09:22:33 2007 Subject: [Haskell-cafe] Re: defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> Message-ID: 2007/8/15, Aaron Denney : > > > > The original "last" fail on empty list, it's far easier to obtain the > > same semantic with foldl than with foldr, in fact it isn't hard at all > > to make it polymorphic without hassle (contrary to the foldr case) > > _if_ you remember that there _is_ a value in Haskell wich belongs to > > every type. > > Hah. True. That does simplify things considerably. Still, I'd call > that an infelicity in last (and head, for that matter), and would rather > have such errors handled at the call site than making the entire program > fall over. Control.Exception.catch (evaluate $ myLast []) print (in GHC it works) Still I don't see why foldl would make it harder to use Maybe than foldr (in fact it's easier). -- Jeda? From jeff.polakow at db.com Wed Aug 15 10:59:27 2007 From: jeff.polakow at db.com (Jeff Polakow) Date: Wed Aug 15 10:51:04 2007 Subject: [Haskell-cafe] Re:Explaining monads In-Reply-To: <378301.94851.qm@web31401.mail.mud.yahoo.com> Message-ID: Hello, > Hence the need to perform a "run" operation like runIdentity, > evalState or runParser (for Parsec) to get something useful to > happen. Except for lists we don't seem to do this. I suppose lists > are so simple that the operators :, ++ and the [] constructor do all > we ever need with them. Finally there is no runIO because "main" is > essentially that function in every real program? - Greg > For lists, head is probably the simplest "run" operation. As Brian noted earlier unsafePerformIO is a way to "run" IO computations within your code; but doing so breaks the abstraction of IO as being the outside world. -Jeff --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070815/8510cc85/attachment.htm From wnoise at ofb.net Wed Aug 15 11:01:26 2007 From: wnoise at ofb.net (Aaron Denney) Date: Wed Aug 15 10:53:13 2007 Subject: [Haskell-cafe] Re: defining last using foldr References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> Message-ID: On 2007-08-15, Chadda? Fouch? wrote: > Still I don't see why foldl would make it harder to use Maybe than > foldr (in fact it's easier). You're right. I just wasn't looking at it quite properly. -- Aaron Denney -><- From dpiponi at gmail.com Wed Aug 15 12:33:11 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Wed Aug 15 12:24:47 2007 Subject: [Haskell-cafe] Re: Re[2]: Why monad tutorials don't work In-Reply-To: <20070815130504.GB10680@cspcag2.swan.ac.uk> References: <46C1C24F.1030905@cisco.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> <1187149599.24464.4.camel@localhost> <46C27C5E.5020103@cs.caltech.edu> <1118701012.20070815091156@yandex.ru> <20070815130504.GB10680@cspcag2.swan.ac.uk> Message-ID: <625b74080708150933h2d2e8c1qb719f2b3fc427ae6@mail.gmail.com> On 8/15/07, Andy Gimblett wrote: > I assumed he was just trying not to sing the "Spider Pig" song. I've been banned from singing that around the house. And the cat version. But I was mainly thinking about how the physicist's definition of tensor needn't be accepted as an irreducible given, but is a consequence of the definition of tensor product through its universal property: http://planetmath.org/encyclopedia/TensorProduct.html Having said that, I still completely agree with Michael that tensors are a great analogy for monads because I found the concept of a universal property tricky in the same way that I subsequently found monads tricky. BTW I think the concept of a universal property is probably the single most useful idea from category theory that can be used in Haskell programming. I recommend it to everyone :-) -- Dan From brianh at metamilk.com Wed Aug 15 13:23:24 2007 From: brianh at metamilk.com (Brian Hulley) Date: Wed Aug 15 13:14:37 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" Message-ID: <46C3368C.4050302@metamilk.com> Hi, On http://hackage.haskell.org/trac/haskell-prime/wiki/LambdaCase the proposed syntax for lambda case is: case of alts but this has a really bad downside for interactive editors: it doesn't allow one to distinguish between an incomplete construct and a completed construct thus removing one opportunity for an editor to alert the user (eg by highlighting) that there is something missing in the program text. Therefore I propose: \of alts which doesn't suffer this problem since the keyword "of" can never follow a '\' in the existing grammar. However I can't edit the H' wiki, so if anyone agrees that the above syntax is better please could they add the above to the page. Thanks, Brian. From paul.hudak at yale.edu Wed Aug 15 13:26:07 2007 From: paul.hudak at yale.edu (Paul Hudak) Date: Wed Aug 15 13:17:44 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <3d96ac180708141213k33ac868bk766c673848f6a25d@mail.gmail.com> References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> <3d96ac180708141213k33ac868bk766c673848f6a25d@mail.gmail.com> Message-ID: <46C3372F.4010406@yale.edu> I've seen the analogy with "recipes" used before, but I think that you need to be careful when you try to distinguish the analogy to monads from the analogy to functions. The reason is that, in the one-of-many ways that I view monads, a monad is just a high-order /function /that abstracts away function composition. In particular, if I have an action f, and an action g, I can think of them as recipes, because I can combine them via f >>= g. It's only after I combine all of my actions together that I apply the result to my input (via "run"). Well, that's just like function composition. In particular, if I have a function f, and a function g, I can think of them as recipes, because I can combine them via f . g. It's only after I combine all of my functions together that I apply the result to my input. -Paul Sebastian Sylvan wrote: > On 14/08/07, Dan Piponi wrote: > >> On 8/14/07, Sebastian Sylvan wrote: >> >>> Well that's easy, don't use the recipe analogy to explain code, use it >>> for monadic values exclusively, and you avoid the confusion entirely! >>> >>> I don't think it's that complicated. >>> >> It certainly is complicated. I think I have a good grasp of monads to >> the point where I can tease novel monads (and comonads) out from >> algorithms that people previously didn't see as monadic. And yet I >> still don't understand what you are saying (except with respect to one >> specific monad, IO, where I can interpret 'action' as meaning an I/O >> operation). >> >> >>> Monads have a monadic type. They >>> represent an abstract form of an "action", which can be viewed as an >>> analogy to real-world cooking recipes. >>> >> All functions can be viewed as recipes. (+) is a recipe. Give me some >> ingredients (two numbers) and I'll use (+) to give you back their sum. >> > > No, (+) is a function, not a "recipe". Again, you're introducing > confusion because you use the same analogy for two *different* things. > Use it for one of the things and you don't have that problem. > I want to use "recipe" to mean "an abstraction for an action". It > could litterally be a text string containing the C code required to do > a particular IO action, for example. (+) isn't an abstraction in the > same sense, it *is* the "action" itself. (+) is the actual value of > the function that will add two numbers together. A monadic value is an > abstract recipe that you can't actually use directly (you can only > combine them, and if you're lucky you can "perform" them once you're > done combining them, e.g. ST, but not IO). > > > >>> As long as you don't >>> deliberately confuse things by using the same analogy for two >>> different things I don't see where confusion would set in. >>> >> If I was one of your students and you said that monads are recipes I >> would immediately ask you where the monads are in my factorial program >> regardless of whether you had introduced one or two different >> analogies for recipes. >> > > Why would you? I really don't see where you would get that idea? If I > tell you that a function returns "a fruit", would you ask where the > fruit in your factorial program is? Probably not. Why would you go off > and take an analogy for monads and apply it to something completely > different and still think the analogy holds? > A function is *not* a recipe in this analogy, it's just a function > (which you hopefully should've covered by the time you get to monads. > Monadic values, and *only* monadic values (not functions!) are to be > viewed as analogous to real world cooking recipes in this analogy. > Functions shouldn't. If you start mixing things together it will get > confused, so just don't! > > I don't think this is very difficult to understand, so if you still > don't get it, I think you're just going to have to read it again > because I can't explain it any better, and in my experience, newbies > tend to understand this analogy within seconds (maybe that's the > problem, you're not a newbie)... > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070815/1fa188c1/attachment.htm From mathiasch at gmail.com Wed Aug 15 13:32:17 2007 From: mathiasch at gmail.com (Mathias Biilmann Christensen) Date: Wed Aug 15 13:23:53 2007 Subject: [Haskell-cafe] Re: Hints for Euler Problem 11 In-Reply-To: <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> References: <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> Message-ID: <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> Spotted this thread as I was working on a Haskell solution for this one myself - here's the solution I came up with: module Main where import List raw_matrix = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 " ++ "49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 " ++ "81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 " ++ "52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 " ++ "22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 " ++ "24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 " ++ "32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 " ++ "67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 " ++ "24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 " ++ "21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 " ++ "78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 " ++ "16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 " ++ "86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 " ++ "19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 " ++ "04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 " ++ "88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 " ++ "04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 " ++ "20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 " ++ "20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 " ++ "01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 " matrix :: [Int] matrix = map read (words raw_matrix) rows = map (\i -> take 20 (drop (i * 20) matrix)) [0..19] cols = transpose rows diag m = (map (\i -> map (\p -> m !! p !! (i+p)) [0..(19-i)]) [0..19]) ++ (map (\i -> map (\p -> m !! (i+p) !! p) [0..(19-i)]) [0..19]) all_matrix_combinations = rows ++ cols ++ (diag rows) ++ (diag $ reverse rows) -- This function finds the maximum sequence of 4 in a given list find_max_product_of_4 l = find_max_4' 0 l where find_max_4' m [] = m find_max_4' m l = find_max_4' (max m (product $ take 4 l)) (tail l) all_maximums = map find_max_product_of_4 all_combinations max_product = maximum all_maximums main = putStrLn $ show max_product From chad.scherrer at gmail.com Wed Aug 15 13:33:52 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Wed Aug 15 13:25:31 2007 Subject: [Haskell-cafe] monte carlo trouble Message-ID: There's a problem I've been struggling with for a long time... I need to build a function buildSample :: [A] -> State StdGen [(A,B,C)] given lookup functions f :: A -> [B] g :: A -> [C] The idea is to first draw randomly form the [A], then apply each lookup function and draw randomly from the result of each. It's actually slightly more complicated than this, since for the real problem I start with type [[A]], and want to map buildSample over these, and sample from the results. There seem to be so many ways to deal with random numbers in Haskell. After some false starts, I ended up doing something like sample :: [a] -> State StdGen [a] sample [] = return [] sample xs = do g <- get let (g', g'') = split g bds = (1, length xs) xArr = listArray bds xs put g'' return . map (xArr !) $ randomRs bds g' buildSample xs = sample $ do x <- xs y <- f x z <- g x return (x,y,z) This is really bad, since it builds a huge array of all the possibilities and then draws from that. Memory is way leaky right now. I'd like to be able to just have it apply the lookup functions as needed. Also, I'm still using GHC 6.6, so I don't have Control.Monad.State.Strict. Not sure how much difference this makes, but I guess I could just copy the source for that module if I need to. Any help is greatly appreciated! -- Chad Scherrer "Time flies like an arrow; fruit flies like a banana" -- Groucho Marx From stefanor at cox.net Wed Aug 15 13:50:36 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 15 13:42:11 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <46C3368C.4050302@metamilk.com> References: <46C3368C.4050302@metamilk.com> Message-ID: <20070815175036.GA3020@localhost.localdomain> On Wed, Aug 15, 2007 at 06:23:24PM +0100, Brian Hulley wrote: > Hi, > On http://hackage.haskell.org/trac/haskell-prime/wiki/LambdaCase the > proposed syntax for lambda case is: > > case of > alts > > but this has a really bad downside for interactive editors: it doesn't > allow one to distinguish between an incomplete construct and a completed > construct thus removing one opportunity for an editor to alert the user (eg > by highlighting) that there is something missing in the program text. It's not like the current language has that property; consider (map myFunction) - is that an error or a partial application? I don't hold out much hope for context-free smart editors. You'll need a typechecker to do much of use, and that can easily distinguish lambda cases from regular cases... OTOH, your proposal provides (IMO) much more natural syntax for multi-pattern anonymous functions, especially if we stipulate that unlike a case (but like a lambda) you can have multiple arguments; then you could write stuff like: sumTo0 = foldr (\of 0 k -> 0 n k -> n + k) 0 Anyone else like this? Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070815/70e2e05b/attachment.bin From duncan.coutts at worc.ox.ac.uk Wed Aug 15 13:53:27 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 15 13:43:47 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <46C3368C.4050302@metamilk.com> References: <46C3368C.4050302@metamilk.com> Message-ID: <1187200407.24215.35.camel@localhost> On Wed, 2007-08-15 at 18:23 +0100, Brian Hulley wrote: > Therefore I propose: > > \of > alts > > which doesn't suffer this problem since the keyword "of" can never > follow a '\' in the existing grammar. Or how about: \case of alts which seems clearer to me. Similarly, the keyword "case" can never follow a '\' in the existing grammar. Mind you, this doesn't seem to save much over \x -> case x of alts It'd be more interesting if we could pattern match against multiple arguments with multiple alternatives like we can in a function definition. I've no idea what syntax for that should look like however. Duncan From p3k at iki.fi Wed Aug 15 13:53:06 2007 From: p3k at iki.fi (Pekka Karjalainen) Date: Wed Aug 15 13:44:41 2007 Subject: [Haskell-cafe] Re: Hints for Euler Problem 11 In-Reply-To: <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> References: <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> Message-ID: <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> On 8/15/07, Mathias Biilmann Christensen wrote: > Spotted this thread as I was working on a Haskell solution for this > one myself - here's the solution I came up with: > [ ... ] > raw_matrix = > "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 " ++ > "49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 " ++ > "81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 " ++ [ ... ] A little style issue here on the side, if I may. You don't need to use (++) to join multiline string literals. text = "If you want to have multiline string literals \ \in your source code, you can break them up with \ \backslashes. Any whitespace characters between \ \two backslashes will be ignored." (The Haskell 98 Report calls them backslants.) Pekka From dpiponi at gmail.com Wed Aug 15 13:56:44 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Wed Aug 15 13:48:18 2007 Subject: [Haskell-cafe] Bathroom reading In-Reply-To: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> Message-ID: <625b74080708151056i1fd9de26rf46b752c3f88704e@mail.gmail.com> On 8/14/07, Dougal Stanton wrote: > I'm looking for cool but mind-bending examples of functional brilliance. One of my favourite examples is: http://citeseer.ist.psu.edu/hinze99functional.html Anyone who studies binomial heaps is struck by the similarity to binary arithmetic. What Hinze does is formalise that similarity so that binomial heaps and binary numbers are instances of the same type class. Very pretty. -- Dan From duncan.coutts at worc.ox.ac.uk Wed Aug 15 13:58:40 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 15 13:49:00 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <20070815175036.GA3020@localhost.localdomain> References: <46C3368C.4050302@metamilk.com> <20070815175036.GA3020@localhost.localdomain> Message-ID: <1187200720.24215.39.camel@localhost> On Wed, 2007-08-15 at 10:50 -0700, Stefan O'Rear wrote: > OTOH, your proposal provides (IMO) much more natural syntax for > multi-pattern anonymous functions, especially if we stipulate that > unlike a case (but like a lambda) you can have multiple arguments; then > you could write stuff like: > > sumTo0 = foldr (\of 0 k -> 0 > n k -> n + k) 0 > > Anyone else like this? Why not just: sumTo0 = foldr (\0 k -> 0 n k -> n + k) 0 I find using "case" or "of" for multiple arg lambda pattern matches odd since "case foo of" is only used for single arg pattern matches. I suppose the equivalent explicit layout syntax would be: sumTo0 = foldr (\{ 0 k -> 0; n k -> n + k }) 0 Duncan From stefanor at cox.net Wed Aug 15 14:06:36 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 15 13:58:11 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <1187200720.24215.39.camel@localhost> References: <46C3368C.4050302@metamilk.com> <20070815175036.GA3020@localhost.localdomain> <1187200720.24215.39.camel@localhost> Message-ID: <20070815180636.GB3020@localhost.localdomain> On Wed, Aug 15, 2007 at 06:58:40PM +0100, Duncan Coutts wrote: > On Wed, 2007-08-15 at 10:50 -0700, Stefan O'Rear wrote: > > > OTOH, your proposal provides (IMO) much more natural syntax for > > multi-pattern anonymous functions, especially if we stipulate that > > unlike a case (but like a lambda) you can have multiple arguments; then > > you could write stuff like: > > > > sumTo0 = foldr (\of 0 k -> 0 > > n k -> n + k) 0 > > > > Anyone else like this? > > Why not just: > > sumTo0 = foldr (\0 k -> 0 > n k -> n + k) 0 Because it would break a very large amount of old code, and I think H' was supposed to be upward compatible: foo = getSomethingCPS $ \ arg -> moreStuff is now a syntax error (\ { varid -> } matches no productions). Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070815/3280322a/attachment.bin From wnoise at ofb.net Wed Aug 15 14:20:44 2007 From: wnoise at ofb.net (Aaron Denney) Date: Wed Aug 15 14:12:26 2007 Subject: [Haskell-cafe] Re: Why monad tutorials don't work References: <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <46C229D6.7080804@imageworks.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> Message-ID: On 2007-08-14, Michael Vanier wrote: > I'm reminded of a physics teacher who was having a similar problem > explaining the concept of tensors, until he said that "a tensor > is something that transforms like a tensor does!". Which is silly. A tensor is a linear function of vectors and linear functions of vectors. That has implications about its transformation properties, and anything with those transformation properties can be used as a tensor, but this formulation gives the flexibility to say what happens when you're using different bases for different "slots". -- Aaron Denney -><- From wnoise at ofb.net Wed Aug 15 14:22:35 2007 From: wnoise at ofb.net (Aaron Denney) Date: Wed Aug 15 14:16:38 2007 Subject: [Haskell-cafe] Re: Hints for Euler Problem 11 References: <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> Message-ID: On 2007-08-15, Pekka Karjalainen wrote: > On 8/15/07, Mathias Biilmann Christensen wrote: >> Spotted this thread as I was working on a Haskell solution for this >> one myself - here's the solution I came up with: >> [ ... ] >> raw_matrix = >> "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 " ++ >> "49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 " ++ >> "81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 " ++ > [ ... ] > > A little style issue here on the side, if I may. You don't need to use > (++) to join multiline string literals. > > text = "If you want to have multiline string literals \ > \in your source code, you can break them up with \ > \backslashes. Any whitespace characters between \ > \two backslashes will be ignored." I find the first far more readable. The compiler should be able to assemble it all at compile time, right? -- Aaron Denney -><- From paul at cogito.org.uk Wed Aug 15 14:38:37 2007 From: paul at cogito.org.uk (Paul Johnson) Date: Wed Aug 15 14:30:15 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: References: Message-ID: <46C3482D.8020200@cogito.org.uk> Chad Scherrer wrote: > There's a problem I've been struggling with for a long time... > > I need to build a function > buildSample :: [A] -> State StdGen [(A,B,C)] > > given lookup functions > f :: A -> [B] > g :: A -> [C] > > The idea is to first draw randomly form the [A], then apply each > lookup function and draw randomly from the result of each. > I don't understand why this returns a list of triples instead of a single triple. Your description below seems to imply the latter. You should probably look at the "Gen" monad in Test.QuickCheck, which is basically a nice implementation of what you are doing with "State StdGen" below. Its "elements" function gets a single random element, and you can combine it with replicateM to get a list of defined length. (BTW, are you sure want multiple random samples rather than a shuffle? A shuffle has each element exactly once whereas multiple random samples can pick any element an arbitrary number of times. I ask because shuffles are a more common requirement. For the code below I'll assume you meant what you said.) Using Test.QuickCheck I think you want something like this (which I have not tested): buildSample :: [A] -> Gen (A,B,C) buildSample xs = do x <- elements xs f1 <- elements $ f x g1 <- elements $ g x return If you want n such samples then I would suggest samples <- replicateM n $ buildSample xs > It's actually slightly more complicated than this, since for the real > problem I start with type [[A]], and want to map buildSample over > these, and sample from the results. > > There seem to be so many ways to deal with random numbers in Haskell. > Indeed. > After some false starts, I ended up doing something like > > sample :: [a] -> State StdGen [a] > sample [] = return [] > sample xs = do > g <- get > let (g', g'') = split g > bds = (1, length xs) > xArr = listArray bds xs > put g'' > return . map (xArr !) $ randomRs bds g' > Not bad, although you could instead have a sample function that returns a single element and then use replicateM to get a list. > buildSample xs = sample $ do > x <- xs > y <- f x > z <- g x > return (x,y,z) > > This is really bad, since it builds a huge array of all the > possibilities and then draws from that. Memory is way leaky right now. > I'd like to be able to just have it apply the lookup functions as > needed. > > Also, I'm still using GHC 6.6, so I don't have > Control.Monad.State.Strict. Not sure how much difference this makes, > but I guess I could just copy the source for that module if I need to. > Strictness won't help. In fact you would be better with laziness if that were possible (which it isn't here). The entire array has to be constructed before you can look up any elements in it. That forces the entire computation. But compare your implementation of buildSample to mine. Paul. From brianh at metamilk.com Wed Aug 15 14:40:07 2007 From: brianh at metamilk.com (Brian Hulley) Date: Wed Aug 15 14:31:18 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <20070815180636.GB3020@localhost.localdomain> References: <46C3368C.4050302@metamilk.com> <20070815175036.GA3020@localhost.localdomain> <1187200720.24215.39.camel@localhost> <20070815180636.GB3020@localhost.localdomain> Message-ID: <46C34887.3010101@metamilk.com> Stefan O'Rear wrote: > On Wed, Aug 15, 2007 at 06:58:40PM +0100, Duncan Coutts wrote: > >> On Wed, 2007-08-15 at 10:50 -0700, Stefan O'Rear wrote: >> >> >>> OTOH, your proposal provides (IMO) much more natural syntax for >>> multi-pattern anonymous functions, especially if we stipulate that >>> unlike a case (but like a lambda) you can have multiple arguments; then >>> you could write stuff like: >>> >>> sumTo0 = foldr (\of 0 k -> 0 >>> n k -> n + k) 0 >>> >> sumTo0 = foldr (\0 k -> 0 >> n k -> n + k) 0 >> > > foo = getSomethingCPS $ \ arg -> > moreStuff > > is now a syntax error (\ { varid -> } matches no productions). > A multi-way lambda could be introduced using \\ thus: sumTo0 = foldr (\\ 0 k -> 0; n k -> n + k) 0 [from a previous post] > It's not like the current language has that property; consider (map > myFunction) - is that an error or a partial application? By "construct" I meant only those grammatical elements involving keywords, and was thinking about situations where you might for example have various syntax templates bound to function keys eg in Haskell the following are incomplete: case of if then else data where deriving ("let in" could still be marked as incomplete even if it is ok according to the grammar since it would be weird to bother writing a let with no bindings.) There is a similar problem with the way template haskell uses unmatched quotes such as 'a so it's no longer possible to determine whether this should be marked as an incomplete character literal or a complete TH name. I suppose my main point is that it's useful for a syntax to have plenty of "unfilled gaps" that result in an error when written rather than filling all those gaps with different meanings... Brian. From brandon at heave.ugcs.caltech.edu Wed Aug 15 14:40:45 2007 From: brandon at heave.ugcs.caltech.edu (Brandon Michael Moore) Date: Wed Aug 15 14:32:20 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <20070815180636.GB3020@localhost.localdomain> References: <46C3368C.4050302@metamilk.com> <20070815175036.GA3020@localhost.localdomain> <1187200720.24215.39.camel@localhost> <20070815180636.GB3020@localhost.localdomain> Message-ID: <20070815184045.GA32605@heave.ugcs.caltech.edu> On Wed, Aug 15, 2007 at 11:06:36AM -0700, Stefan O'Rear wrote: > On Wed, Aug 15, 2007 at 06:58:40PM +0100, Duncan Coutts wrote: > > On Wed, 2007-08-15 at 10:50 -0700, Stefan O'Rear wrote: > > > > > OTOH, your proposal provides (IMO) much more natural syntax for > > > multi-pattern anonymous functions, especially if we stipulate that > > > unlike a case (but like a lambda) you can have multiple arguments; then > > > you could write stuff like: > > > > > > sumTo0 = foldr (\of 0 k -> 0 > > > n k -> n + k) 0 > > > > > > Anyone else like this? > > > > Why not just: > > > > sumTo0 = foldr (\0 k -> 0 > > n k -> n + k) 0 > > Because it would break a very large amount of old code, and I think H' > was supposed to be upward compatible: > > foo = getSomethingCPS $ \ arg -> > moreStuff > > is now a syntax error (\ { varid -> } matches no productions). I was going to say you could leave the other production, but layout is separated from parsing. It's not even simple to say "use nondeterminism", because of that rule about a layout level ending if there would otherwise be a parse error. If that parse error rule backtracks far enough, old lambdas could simply have the production \{} pat -> expr, if it's only one token of lookahed perhaps \ { pat } -> expr would be mostly backwards-compatible (but it would be very wierd to understand the errors when it wasn't). Lambdas with multiple arguments and pattern matching sound really nice, but "case of" and "\of" are both extremely ugly names. They only make sense if you are familiar with the rest of the language and think of this as shoehorning in some new kind of lambda with pattern matching (remember constructor classes, and how it's all just typeclasses now). What do the rest of you on the cafe think? If a different name is necessary, I'd prefer something like "fun" that just tries to imply this is a slighly heavier, more powerful kind of anonymous function. (plus it's a step towards rec-expressions) Brandon From duncan.coutts at worc.ox.ac.uk Wed Aug 15 14:49:49 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 15 14:40:10 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <20070815180636.GB3020@localhost.localdomain> References: <46C3368C.4050302@metamilk.com> <20070815175036.GA3020@localhost.localdomain> <1187200720.24215.39.camel@localhost> <20070815180636.GB3020@localhost.localdomain> Message-ID: <1187203789.24215.47.camel@localhost> On Wed, 2007-08-15 at 11:06 -0700, Stefan O'Rear wrote: > > Why not just: > > > > sumTo0 = foldr (\0 k -> 0 > > n k -> n + k) 0 > > Because it would break a very large amount of old code, and I think H' > was supposed to be upward compatible: Aye, that'd be bad. > foo = getSomethingCPS $ \ arg -> > moreStuff > > is now a syntax error (\ { varid -> } matches no productions). I'm not sure I follow. The patterns would have to match up in a column, so foo = getSomethingCPS $ \ arg -> moreStuff should be fine, to add another alternative it'd have to be: foo = getSomethingCPS $ \ Pat1 -> moreStuff Pat2 -> evenMoreStuff This case might be tricky though: foo = getSomethingCPS $ \ Pat1 -> foo moreStuff since we have to parse all of the moreStuff expression before discovering it has no following "->" and so it's party of the body of the first lambda alternative rather than a pattern starting a new alternative. I'm no parsing expert (especially when it comes to layout rules), perhaps this is all too tricky. Duncan From benjamin.franksen at bessy.de Wed Aug 15 14:51:57 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Wed Aug 15 14:43:40 2007 Subject: [Haskell-cafe] Re: Syntax for lambda case proposal could be "\of" References: <46C3368C.4050302@metamilk.com> <20070815175036.GA3020@localhost.localdomain> <1187200720.24215.39.camel@localhost> <20070815180636.GB3020@localhost.localdomain> <46C34887.3010101@metamilk.com> Message-ID: Brian Hulley wrote: > Stefan O'Rear wrote: >> On Wed, Aug 15, 2007 at 06:58:40PM +0100, Duncan Coutts wrote: >> >>> On Wed, 2007-08-15 at 10:50 -0700, Stefan O'Rear wrote: >>> >>> >>>> OTOH, your proposal provides (IMO) much more natural syntax for >>>> multi-pattern anonymous functions, especially if we stipulate that >>>> unlike a case (but like a lambda) you can have multiple arguments; then >>>> you could write stuff like: >>>> >>>> sumTo0 = foldr (\of 0 k -> 0 >>>> n k -> n + k) 0 >>>> >>> sumTo0 = foldr (\0 k -> 0 >>> n k -> n + k) 0 >>> >> >> foo = getSomethingCPS $ \ arg -> >> moreStuff >> >> is now a syntax error (\ { varid -> } matches no productions). >> > A multi-way lambda could be introduced using \\ thus: > > sumTo0 = foldr (\\ 0 k -> 0; n k -> n + k) 0 I like the idea, but unfortunately '\\' is currently a regular operator symbol. In fact it is used as (set or map) 'difference' operator (according to http://www.haskell.org/ghc/docs/latest/html/libraries/doc-index-92.html): \\ 1 (Function) Data.IntMap 2 (Function) Data.IntSet 3 (Function) Data.List 4 (Function) Data.Map 5 (Function) Data.Set Cheers Ben From paul at cogito.org.uk Wed Aug 15 14:53:47 2007 From: paul at cogito.org.uk (Paul Johnson) Date: Wed Aug 15 14:45:24 2007 Subject: [Haskell-cafe] Haskell for the Enterprise (topic for a MSc dissertation?) In-Reply-To: References: Message-ID: <46C34BBB.5040409@cogito.org.uk> Lars Oppermann wrote: > > I would love to hear your comments on this. Has this been done over > and over already? Are there any source which you think of from the top > of your head which I should check out? Books that you would want to > recommend? Sounds interesting. I for one would like to read a study along these lines. > > As I wrote above, I'm quite new to Haskell. Thus if anyone wants to > recommend some readings specifically on the aspect of modeling in a > functional environment I'd be happy to hear about that too. > I'm not sure what you mean by "modelling": functional programmers don't see modelling as separate from coding: the code is the model, and if thats not abstract enough then you didn't do it right. Take a look at some good examples of combinator libraries. Parsec and QuickCheck are good case studies. Examine the interfaces, and see how the model shines through. Understand how monads are used to model different ideas of control flow (especially the list monad, and also backtracking in Parsec). If you can get your head around it you might also look at the continuation monad and see how it can be used as the foundation for arbitrary flow of control concepts. Finally compare the use of monad transformers with "aspect oriented" programming. You might also read the "poor mans concurrency" paper http://www.cs.chalmers.se/~koen/pubs/jfp99-monad.ps. The dialect of Haskell is obsolete, but you'll get the idea. Don't get too hung up on monads. Also study applicative functors and arrows. Applicative functors are probably easier to figure out at first. Arrows are what you get when you cross applicative functors with monads (more or less). Paul. From thomas.hartman at db.com Wed Aug 15 14:52:51 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Wed Aug 15 14:46:27 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: <46C3482D.8020200@cogito.org.uk> Message-ID: have you looked at pfp, the haskell "probabilistic functional programming library "? http://web.engr.oregonstate.edu/~erwig/pfp/ the paper http://web.engr.oregonstate.edu/~erwig/papers/abstracts.html#JFP06a describes modeling various statisticy things this way, like tree growth and the monty hall problem, I think it's likely this is applicable to monte carlo processes as well. thomas. Paul Johnson Sent by: haskell-cafe-bounces@haskell.org 08/15/2007 02:38 PM To Chad Scherrer cc haskell-cafe@haskell.org Subject Re: [Haskell-cafe] monte carlo trouble Chad Scherrer wrote: > There's a problem I've been struggling with for a long time... > > I need to build a function > buildSample :: [A] -> State StdGen [(A,B,C)] > > given lookup functions > f :: A -> [B] > g :: A -> [C] > > The idea is to first draw randomly form the [A], then apply each > lookup function and draw randomly from the result of each. > I don't understand why this returns a list of triples instead of a single triple. Your description below seems to imply the latter. You should probably look at the "Gen" monad in Test.QuickCheck, which is basically a nice implementation of what you are doing with "State StdGen" below. Its "elements" function gets a single random element, and you can combine it with replicateM to get a list of defined length. (BTW, are you sure want multiple random samples rather than a shuffle? A shuffle has each element exactly once whereas multiple random samples can pick any element an arbitrary number of times. I ask because shuffles are a more common requirement. For the code below I'll assume you meant what you said.) Using Test.QuickCheck I think you want something like this (which I have not tested): buildSample :: [A] -> Gen (A,B,C) buildSample xs = do x <- elements xs f1 <- elements $ f x g1 <- elements $ g x return If you want n such samples then I would suggest samples <- replicateM n $ buildSample xs > It's actually slightly more complicated than this, since for the real > problem I start with type [[A]], and want to map buildSample over > these, and sample from the results. > > There seem to be so many ways to deal with random numbers in Haskell. > Indeed. > After some false starts, I ended up doing something like > > sample :: [a] -> State StdGen [a] > sample [] = return [] > sample xs = do > g <- get > let (g', g'') = split g > bds = (1, length xs) > xArr = listArray bds xs > put g'' > return . map (xArr !) $ randomRs bds g' > Not bad, although you could instead have a sample function that returns a single element and then use replicateM to get a list. > buildSample xs = sample $ do > x <- xs > y <- f x > z <- g x > return (x,y,z) > > This is really bad, since it builds a huge array of all the > possibilities and then draws from that. Memory is way leaky right now. > I'd like to be able to just have it apply the lookup functions as > needed. > > Also, I'm still using GHC 6.6, so I don't have > Control.Monad.State.Strict. Not sure how much difference this makes, > but I guess I could just copy the source for that module if I need to. > Strictness won't help. In fact you would be better with laziness if that were possible (which it isn't here). The entire array has to be constructed before you can look up any elements in it. That forces the entire computation. But compare your implementation of buildSample to mine. Paul. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070815/3ce9872a/attachment.htm From chad.scherrer at gmail.com Wed Aug 15 15:05:03 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Wed Aug 15 14:56:38 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: <46C3482D.8020200@cogito.org.uk> References: <46C3482D.8020200@cogito.org.uk> Message-ID: Thanks for your replies. I actually starting out returning a single element instead. But a given lookup might return [], and the only way I could think of to handle it in (State StdGen a) would be to fail in the monad. But that's not really the effect I want - I'd rather have it ignore that element. Another option was to wrap with Maybe, but then since I really want a sequence of them anyway, I decided to just wrap in a List instead. Is there a way Maybe would work out better? I've seen PFP, but I don't see where that would help here. I'd still end up with an enormous list of tuples. This could be generated lazily, but sampling with replacement (yes I want this, not a shuffle) would require forcing the whole list anyway, wouldn't it? Using my approach, even asking ghci for the length of the list ran for 30+ minutes. If there's a way to lazily sample with replacement from a list without even requiring the length of the list to be known in advance, that could lead to a solution. Thanks, Chad On 8/15/07, Paul Johnson wrote: > Chad Scherrer wrote: > > There's a problem I've been struggling with for a long time... > > > > I need to build a function > > buildSample :: [A] -> State StdGen [(A,B,C)] > > > > given lookup functions > > f :: A -> [B] > > g :: A -> [C] > > > > The idea is to first draw randomly form the [A], then apply each > > lookup function and draw randomly from the result of each. > > > I don't understand why this returns a list of triples instead of a > single triple. Your description below seems to imply the latter. > > You should probably look at the "Gen" monad in Test.QuickCheck, which is > basically a nice implementation of what you are doing with "State > StdGen" below. Its "elements" function gets a single random element, > and you can combine it with replicateM to get a list of defined length. > > (BTW, are you sure want multiple random samples rather than a shuffle? > A shuffle has each element exactly once whereas multiple random samples > can pick any element an arbitrary number of times. I ask because > shuffles are a more common requirement. For the code below I'll assume > you meant what you said.) > > Using Test.QuickCheck I think you want something like this (which I have > not tested): > > buildSample :: [A] -> Gen (A,B,C) > buildSample xs = do > x <- elements xs > f1 <- elements $ f x > g1 <- elements $ g x > return > > If you want n such samples then I would suggest > > samples <- replicateM n $ buildSample xs > > It's actually slightly more complicated than this, since for the real > > problem I start with type [[A]], and want to map buildSample over > > these, and sample from the results. > > > > There seem to be so many ways to deal with random numbers in Haskell. > > > Indeed. > > After some false starts, I ended up doing something like > > > > sample :: [a] -> State StdGen [a] > > sample [] = return [] > > sample xs = do > > g <- get > > let (g', g'') = split g > > bds = (1, length xs) > > xArr = listArray bds xs > > put g'' > > return . map (xArr !) $ randomRs bds g' > > > Not bad, although you could instead have a sample function that returns > a single element and then use replicateM to get a list. > > buildSample xs = sample $ do > > x <- xs > > y <- f x > > z <- g x > > return (x,y,z) > > > > This is really bad, since it builds a huge array of all the > > possibilities and then draws from that. Memory is way leaky right now. > > I'd like to be able to just have it apply the lookup functions as > > needed. > > > > Also, I'm still using GHC 6.6, so I don't have > > Control.Monad.State.Strict. Not sure how much difference this makes, > > but I guess I could just copy the source for that module if I need to. > > > Strictness won't help. In fact you would be better with laziness if > that were possible (which it isn't here). The entire array has to be > constructed before you can look up any elements in it. That forces the > entire computation. But compare your implementation of buildSample to > mine. > > Paul. > -- Chad Scherrer "Time flies like an arrow; fruit flies like a banana" -- Groucho Marx From thomas.hartman at db.com Wed Aug 15 15:13:53 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Wed Aug 15 15:06:46 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: Message-ID: >> I've seen PFP, but I don't see where that would help here. I'd still end up with an enormous list of tuples. I'm not sure I understand what you need, but did you read the bits about replacing a "pure" state expansion (all the possibile states) with an approximation using random/io ? the approximation of course used much less resources (orders of orders of magnitude :) ) , the more time the random process had to evolve the better the approximation matched the "pure" calculation. very wonderful. thomas. "Chad Scherrer" 08/15/2007 03:05 PM To "Paul Johnson" , Thomas Hartman/ext/dbcom@DBAmericas cc haskell-cafe@haskell.org Subject Re: [Haskell-cafe] monte carlo trouble Thanks for your replies. I actually starting out returning a single element instead. But a given lookup might return [], and the only way I could think of to handle it in (State StdGen a) would be to fail in the monad. But that's not really the effect I want - I'd rather have it ignore that element. Another option was to wrap with Maybe, but then since I really want a sequence of them anyway, I decided to just wrap in a List instead. Is there a way Maybe would work out better? I've seen PFP, but I don't see where that would help here. I'd still end up with an enormous list of tuples. This could be generated lazily, but sampling with replacement (yes I want this, not a shuffle) would require forcing the whole list anyway, wouldn't it? Using my approach, even asking ghci for the length of the list ran for 30+ minutes. If there's a way to lazily sample with replacement from a list without even requiring the length of the list to be known in advance, that could lead to a solution. Thanks, Chad On 8/15/07, Paul Johnson wrote: > Chad Scherrer wrote: > > There's a problem I've been struggling with for a long time... > > > > I need to build a function > > buildSample :: [A] -> State StdGen [(A,B,C)] > > > > given lookup functions > > f :: A -> [B] > > g :: A -> [C] > > > > The idea is to first draw randomly form the [A], then apply each > > lookup function and draw randomly from the result of each. > > > I don't understand why this returns a list of triples instead of a > single triple. Your description below seems to imply the latter. > > You should probably look at the "Gen" monad in Test.QuickCheck, which is > basically a nice implementation of what you are doing with "State > StdGen" below. Its "elements" function gets a single random element, > and you can combine it with replicateM to get a list of defined length. > > (BTW, are you sure want multiple random samples rather than a shuffle? > A shuffle has each element exactly once whereas multiple random samples > can pick any element an arbitrary number of times. I ask because > shuffles are a more common requirement. For the code below I'll assume > you meant what you said.) > > Using Test.QuickCheck I think you want something like this (which I have > not tested): > > buildSample :: [A] -> Gen (A,B,C) > buildSample xs = do > x <- elements xs > f1 <- elements $ f x > g1 <- elements $ g x > return > > If you want n such samples then I would suggest > > samples <- replicateM n $ buildSample xs > > It's actually slightly more complicated than this, since for the real > > problem I start with type [[A]], and want to map buildSample over > > these, and sample from the results. > > > > There seem to be so many ways to deal with random numbers in Haskell. > > > Indeed. > > After some false starts, I ended up doing something like > > > > sample :: [a] -> State StdGen [a] > > sample [] = return [] > > sample xs = do > > g <- get > > let (g', g'') = split g > > bds = (1, length xs) > > xArr = listArray bds xs > > put g'' > > return . map (xArr !) $ randomRs bds g' > > > Not bad, although you could instead have a sample function that returns > a single element and then use replicateM to get a list. > > buildSample xs = sample $ do > > x <- xs > > y <- f x > > z <- g x > > return (x,y,z) > > > > This is really bad, since it builds a huge array of all the > > possibilities and then draws from that. Memory is way leaky right now. > > I'd like to be able to just have it apply the lookup functions as > > needed. > > > > Also, I'm still using GHC 6.6, so I don't have > > Control.Monad.State.Strict. Not sure how much difference this makes, > > but I guess I could just copy the source for that module if I need to. > > > Strictness won't help. In fact you would be better with laziness if > that were possible (which it isn't here). The entire array has to be > constructed before you can look up any elements in it. That forces the > entire computation. But compare your implementation of buildSample to > mine. > > Paul. > -- Chad Scherrer "Time flies like an arrow; fruit flies like a banana" -- Groucho Marx --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070815/94f76245/attachment-0001.htm From loppermann at acm.org Wed Aug 15 15:38:38 2007 From: loppermann at acm.org (Lars Oppermann) Date: Wed Aug 15 15:30:12 2007 Subject: [Haskell-cafe] Haskell for the Enterprise (topic for a MSc dissertation?) In-Reply-To: <46C34BBB.5040409@cogito.org.uk> References: <46C34BBB.5040409@cogito.org.uk> Message-ID: On 8/15/07, Paul Johnson wrote: > I'm not sure what you mean by "modelling": functional programmers don't > see modelling as separate from coding: the code is the model, and if > thats not abstract enough then you didn't do it right. > [...] > With modeling I meant the process of arriving at the abstraction from the initial "business requirements". The concepts that you pointed out would then be the building blocks, from which the application model is derived. The fact, that that model is already the code would be a strong point for actually using FP for enterprise applications as you do not need to get into the whole "executable UML" business of which I am personally not very fond of. Another modeling approach might be to start with formal specification technique like Z and then implement that in Haskell. The code would be much closer to what you'd put down in the formal spec. On the other hand, it may be limiting in expressive power, thus the code may serve as the formal specification too, exampoles of this would be James Clark' RelaxNG validator in Haskell (http://www.thaiopensource.com/relaxng/derivative.html) or the TeX formula layout reimplementation/description in SML (http://rw4.cs.uni-sb.de/~heckmann/abstracts/neuform.html) Thanks a lot for all your suggestions... Lars -- Lars Oppermann Hamburg, Germany From westondan at imageworks.com Wed Aug 15 15:48:29 2007 From: westondan at imageworks.com (Dan Weston) Date: Wed Aug 15 15:40:07 2007 Subject: [Haskell-cafe] Re: Re[2]: Why monad tutorials don't work In-Reply-To: <625b74080708150933h2d2e8c1qb719f2b3fc427ae6@mail.gmail.com> References: <46C1C24F.1030905@cisco.com> <2d3641330708141527j38cb76b0gea133dff31476093@mail.gmail.com> <46C22F5F.90101@cs.caltech.edu> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> <1187149599.24464.4.camel@localhost> <46C27C5E.5020103@cs.caltech.edu> <1118701012.20070815091156@yandex.ru> <20070815130504.GB10680@cspcag2.swan.ac.uk> <625b74080708150933h2d2e8c1qb719f2b3fc427ae6@mail.gmail.com> Message-ID: <46C3588D.4060807@imageworks.com> Dan Piponi wrote: > But I was mainly thinking about how the physicist's definition of > tensor needn't be accepted as an irreducible given, but is a > consequence of the definition of tensor product through its universal > property: http://planetmath.org/encyclopedia/TensorProduct.html > > Having said that, I still completely agree with Michael that tensors > are a great analogy for monads because I found the concept of a > universal property tricky in the same way that I subsequently found > monads tricky. BTW I think the concept of a universal property is > probably the single most useful idea from category theory that can be > used in Haskell programming. I recommend it to everyone :-) If only my Linear Algebra professor had just uttered the magic words: "For all R-modules M, the functor (-) * M is left-adjoint to the functor Hom(M,-)" I could have just skipped out on the entire semester. Why are teachers always so long-winded? The above is so much clearer! That the above is "the single most useful idea from category theory that can be used in Haskell programming" is so obvious, it belongs in a tutorial titled "You too could have invented Universal Algebra and Category Theory". I nominate Dan Piponi to write it and eagerly await its release! Dan Weston From chad.scherrer at gmail.com Wed Aug 15 15:57:07 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Wed Aug 15 15:48:42 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: References: <46C3482D.8020200@cogito.org.uk> <46C35985.4010302@cogito.org.uk> Message-ID: Funny you should say that, I was just experimenting with generating one at a time using (StateT StdGen Maybe). If I get stuck (again) I'll check out ListT. Thanks! Chad On 8/15/07, Paul Johnson wrote: > Chad Scherrer wrote: > > Thanks for your replies. > > > > I actually starting out returning a single element instead. But a > > given lookup might return [], and the only way I could think of to > > handle it in (State StdGen a) would be to fail in the monad. But > > that's not really the effect I want - I'd rather have it ignore that > > element. Another option was to wrap with Maybe, but then since I > > really want a sequence of them anyway, I decided to just wrap in a > > List instead. Is there a way Maybe would work out better? > Ahh. How about using ListT Gen then? That (if I've got it the right > way round) works like the list monad (giving you non-determinism), but > has your random number generator embedded as well. Take a look at "All > About Monads" at http://www.haskell.org/all_about_monads/html/. Each > action in the monad may use a random number and produce zero or more > results. > > Paul. -- Chad Scherrer "Time flies like an arrow; fruit flies like a banana" -- Groucho Marx From dpiponi at gmail.com Wed Aug 15 16:12:42 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Wed Aug 15 16:04:16 2007 Subject: [Haskell-cafe] Re: Re[2]: Why monad tutorials don't work In-Reply-To: <46C3588D.4060807@imageworks.com> References: <46C1C24F.1030905@cisco.com> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> <1187149599.24464.4.camel@localhost> <46C27C5E.5020103@cs.caltech.edu> <1118701012.20070815091156@yandex.ru> <20070815130504.GB10680@cspcag2.swan.ac.uk> <625b74080708150933h2d2e8c1qb719f2b3fc427ae6@mail.gmail.com> <46C3588D.4060807@imageworks.com> Message-ID: <625b74080708151312y2f1161cdq6ca5c6a0e2e60526@mail.gmail.com> On 8/15/07, Dan Weston wrote: > "You too could have invented Universal Algebra and Category Theory". > I nominate Dan Piponi to write it and eagerly await its release! I've already started on it. Well, that's not the exact title and subject. And as an example I'll probably use the definition of tensor product that I linked to, not the even more compact and elegant one that you just gave. I'm a strong believer that lots of (but not all) tricky looking mathematics is just fancy language for intuitions that people already have. I suspect that most computer scientists already have much of the intuition behind the idea of a universal property, and that it is in fact easier to grasp for a computer scientist than a mathematician. :-) -- Dan From dipankar at jfet.net Wed Aug 15 16:23:55 2007 From: dipankar at jfet.net (Dipankar Ray) Date: Wed Aug 15 16:15:33 2007 Subject: [Haskell-cafe] Re: Re[2]: Why monad tutorials don't work In-Reply-To: <625b74080708151312y2f1161cdq6ca5c6a0e2e60526@mail.gmail.com> References: <46C1C24F.1030905@cisco.com> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> <1187149599.24464.4.camel@localhost> <46C27C5E.5020103@cs.caltech.edu> <1118701012.20070815091156@yandex.ru> <20070815130504.GB10680@cspcag2.swan.ac.uk> <625b74080708150933h2d2e8c1qb719f2b3fc427ae6@mail.gmail.com> <46C3588D.4060807@imageworks.com> <625b74080708151312y2f1161cdq6ca5c6a0e2e60526@mail.gmail.com> Message-ID: At this point I must mention that Tim Gowers has an excellent article on Tensor Products, entitled "How to lose your fear of tensor products": http://www.dpmms.cam.ac.uk/~wtg10/tensors3.html Tim Gowers is a pretty ok mathematician - worth taking tips from, I'd say ;) http://en.wikipedia.org/wiki/William_Timothy_Gowers On Wed, 15 Aug 2007, Dan Piponi wrote: > On 8/15/07, Dan Weston wrote: >> "You too could have invented Universal Algebra and Category Theory". >> I nominate Dan Piponi to write it and eagerly await its release! > > I've already started on it. Well, that's not the exact title and > subject. And as an example I'll probably use the definition of tensor > product that I linked to, not the even more compact and elegant one > that you just gave. > > I'm a strong believer that lots of (but not all) tricky looking > mathematics is just fancy language for intuitions that people already > have. I suspect that most computer scientists already have much of the > intuition behind the idea of a universal property, and that it is in > fact easier to grasp for a computer scientist than a mathematician. > > :-) > -- > Dan > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From alexteslin at yahoo.co.uk Wed Aug 15 16:24:52 2007 From: alexteslin at yahoo.co.uk (Alexteslin) Date: Wed Aug 15 16:16:25 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> Message-ID: <12169661.post@talk.nabble.com> Aaron Denney wrote: > > (Quoting reformatted. Try to have your responses below what you are > responding to. It makes it easier to read as a conversation.) > > On 2007-08-14, Alexteslin wrote: >> Aaron Denney wrote: >>> Folds replace the "cons" operator (:) with the function you pass it. >>> If you want the tail of the list, you want what is on the right hand >>> side of every cons (unless that's []). > >> >> Well, i have tried cons (:) operator but when it passed to foldr doesn't >> work >> because cons operator operates first character and then the list but the >> foldr argument takes a function (a->a->a). Maybe i am missing the point >> here? > > I didn't say to use (:), I said foldr works by replacing (:) with some > other function. > > foldr also takes a function of type (a -> b -> b). > > foldr f e > replaces > (first : (middle : (last : []))) > with > (first `f` (middle `f` (last `f` e))) > > You want last to be kept, so > f x e = x > > this causes the overall pattern to reduce to > (first `f` (middle `f` last)) > > This time you need > f y last = last > > This means you need to discriminate between "e" and "last". > > If you make "e" the same type as last, you could accidentally compare > them equal. So instead of using the same type, we want one with one > more value. There is a standard one: "Maybe a", with constructors > "Just a" and "Nothing". And you also need to promote last to this > type with the constructor Just, because the result gets fed in on the > right. > > -- > Aaron Denney > -><- > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > I am really sorry, but i still can't define the function. The chapter the exercise is in precedes algebraic types or Maybe a types. And is seems that must being easy to define. I answered some exercises on using foldr such as summing for example, but this one i am trying: myLast :: [Int] -> Int myLast (x:xs) = foldr (some function) x xs. With summing as i understood foldr goes through the list and sums up by (+) operator and one argument like 0. Like: foldr (+) 0 xs -- View this message in context: http://www.nabble.com/defining-last-using-foldr-tf4269357.html#a12169661 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From jon.fairbairn at cl.cam.ac.uk Wed Aug 15 16:42:45 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Wed Aug 15 16:34:37 2007 Subject: [Haskell-cafe] Re: defining last using foldr References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> Message-ID: Alexteslin writes: > I am really sorry, but i still can't define the function. The chapter the > exercise is in precedes algebraic types or Maybe a types. And is seems that > must being easy to define. > I answered some exercises on using foldr such as summing for example, but > this one i am trying: > > myLast :: [Int] -> Int > myLast (x:xs) = foldr (some function) x xs. > > With summing as i understood foldr goes through the list and sums up by (+) > operator and one argument like 0. Like: foldr (+) 0 xs You can think of foldr f e [a,b,c] as a `f` (b `f` (c `f` e)) so myLast [x,a,b,c] is going to be a `f` (b `f` (c `f` x)) so you need an f so that c `f` x is c (for any c and x) and yet (b `f` c) is c for any c and b -- this is impossible (or I'm asleep). So your skeleton above isn't going to work. You can do something like myLast l = unpick (foldr toLast [] l) where unpick ... toLast ... The above contains a strong hint as to the type of toLast (and hence unpick) -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From iand675 at gmail.com Wed Aug 15 16:45:00 2007 From: iand675 at gmail.com (Ian Duncan) Date: Wed Aug 15 16:37:08 2007 Subject: [Haskell-cafe] Pattern matching articles/explanations Message-ID: Hello everyone, I've been working on improving my Haskell knowledge, and in doing so, I have read a little about as-patterns as well as some form of pattern that uses "~" that I don't really understand. I suspect there are even more lesser-known pattern matching expressions than just these, but I don't have the stamina to decode the Haskell 98 Report. Are there any articles anyone is aware of, or anything in the Haskell wiki that covers the built-in pattern matching facilities pretty comprehensively? I've looked in the Haskell wiki myself, but information on different pattern matching abilities seems rather scattered and I'm not entirely sure what I should be looking for. Thanks, Ian Duncan From isaacdupree at charter.net Wed Aug 15 17:02:47 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Wed Aug 15 16:54:45 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <1187200407.24215.35.camel@localhost> References: <46C3368C.4050302@metamilk.com> <1187200407.24215.35.camel@localhost> Message-ID: <46C369F7.20300@charter.net> Duncan Coutts wrote: > On Wed, 2007-08-15 at 18:23 +0100, Brian Hulley wrote: > >> Therefore I propose: >> >> \of >> alts >> >> which doesn't suffer this problem since the keyword "of" can never >> follow a '\' in the existing grammar. > > Or how about: > > \case of > alts > > which seems clearer to me. > > Similarly, the keyword "case" can never follow a '\' in the existing > grammar. > > Mind you, this doesn't seem to save much over > > \x -> case x of > alts It saves the writer using an explicit name which must be unique and the reader determining that the name is not used deeper in the expressions. (and a "->"). I tend to find myself wanting this after already having written a 'case' and decided I don't need/want a name for the thing being 'cased'. I wouldn't mind "case of", "\of" or "\case of", for using it. Allowing multiple arguments - is syntactically difficult to reconcile with 'case' because it restricts what single-argument forms can be used? Such as: > case foo of Just n -> n is allowed but > f Just n = n isn't. Isaac From chaddai.fouche at gmail.com Wed Aug 15 17:29:51 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Wed Aug 15 17:21:33 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: <12169661.post@talk.nabble.com> References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> Message-ID: 2007/8/15, Alexteslin : > I am really sorry, but i still can't define the function. The chapter the > exercise is in precedes algebraic types or Maybe a types. And is seems that > must being easy to define. If you don't have Maybe, you still have it's older brother, namely lists (as strongly hinted by Jon Fairbairn). > so you need an f so that c `f` x is c (for any c and x) and > yet (b `f` c) is c for any c and b -- this is impossible (or > I'm asleep). Well, it isn't "impossible" but quite hard (and not even standard H98 if I'm not mistaken) and obviously not in the range of the possibilities here. Still you could "approximate" it, and in fact I believe the [Char] -> Char requirement is hinting at such a (arguably and IMO ugly) solution. For example you could assume there would be no "NUL" character in a string ([Char] is a synonym for String, or vice-versa), and then get a simple myLast for String in this restrictive case (and looking exactly like Alexteslin sample). -- Jeda? From westondan at imageworks.com Wed Aug 15 17:35:15 2007 From: westondan at imageworks.com (Dan Weston) Date: Wed Aug 15 17:26:51 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <46C369F7.20300@charter.net> References: <46C3368C.4050302@metamilk.com> <1187200407.24215.35.camel@localhost> <46C369F7.20300@charter.net> Message-ID: <46C37193.8020301@imageworks.com> I came really late to this discussion, so I assume someone has already proposed using (Control.Applicative.<|>) to select the first matching pattern of an unnamed cased object. Can someone point me to where that was proposed and why it was rejected? Dan Weston Isaac Dupree wrote: > Duncan Coutts wrote: >> On Wed, 2007-08-15 at 18:23 +0100, Brian Hulley wrote: >> >>> Therefore I propose: >>> >>> \of >>> alts >>> >>> which doesn't suffer this problem since the keyword "of" can never >>> follow a '\' in the existing grammar. >> >> Or how about: >> >> \case of >> alts >> >> which seems clearer to me. >> >> Similarly, the keyword "case" can never follow a '\' in the existing >> grammar. >> >> Mind you, this doesn't seem to save much over >> >> \x -> case x of >> alts > > It saves the writer using an explicit name which must be unique and the > reader determining that the name is not used deeper in the expressions. > (and a "->"). I tend to find myself wanting this after already having > written a 'case' and decided I don't need/want a name for the thing > being 'cased'. I wouldn't mind "case of", "\of" or "\case of", for > using it. > > Allowing multiple arguments - is syntactically difficult to reconcile > with 'case' because it restricts what single-argument forms can be used? > Such as: > > case foo of Just n -> n > is allowed but > > f Just n = n > isn't. > > > Isaac > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From mattcbro at earthlink.net Wed Aug 15 17:52:30 2007 From: mattcbro at earthlink.net (SevenThunders) Date: Wed Aug 15 17:44:03 2007 Subject: [Haskell-cafe] GHC linking problems In-Reply-To: <12155220.post@talk.nabble.com> References: <12155220.post@talk.nabble.com> Message-ID: <12171221.post@talk.nabble.com> SevenThunders wrote: > > I have a large Haskell/C project that needs to be linked against an even > larger set of C libraries and object files (OpNet) on a linux box (Fedora > Core 7). So far I have been able to link my Haskell libraries to some C > test code containing a main function without incident. However the link > flags are very complex having been extracted from ghc. (e.g. it requires > a host of -u flags and then a bunch of links to external C libraries > including a long list of Haskell libraries.) > > Unfortunately control over the OpNet compilation and linking process is > weak at best. Moreover it is not clear how the linking occurs and there > is some suspicion that it ultimately creates a dynamic link library which > it loads from some external process (the exact calls to gcc are hidden). > During the OpNet build we get the following error > > /usr/lib/ghc-6.6.1/libHSrts.a(Main.o): In function `main': > Main.c:(.text+0x22): undefined reference to `__stginit_ZCMain' > Main.c:(.text+0x43): undefined reference to `ZCMain_main_closure' > collect2: ld returned 1 exit status > > I do not get this error when statically linking my libraries to a > standalone C function containing a main() function. What should I look > for? Are there known work arounds to this problem? It's troubling that > exporting Haskell to C should be this problematic. Unfortunately I can > not use ghc to compile the OpNet code as you might imagine. > Does this error occur because of dynamic linking? That is if this were all packed into some library without a main function in C it would try to link to the Main.o object file in libHSrts.a, which has some unsatisfied links since there is no main function in the Haskell code. So does static linking always fix this? Is it possible to fix it by providing a dummy main function in a dynamic link library? I don't know if the latter is possible in linux. -- View this message in context: http://www.nabble.com/GHC-linking-problems-tf4270650.html#a12171221 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From dominic.steinitz at blueyonder.co.uk Wed Aug 15 17:55:45 2007 From: dominic.steinitz at blueyonder.co.uk (Dominic Steinitz) Date: Wed Aug 15 17:47:59 2007 Subject: [Haskell-cafe] Re: Re[2]: Why monad tutorials don't work References: <46C1C24F.1030905@cisco.com> <625b74080708141601h311dc08bpa0fbd50c306a66a7@mail.gmail.com> <625b74080708141602w64a4b565x76c65458e2ac1908@mail.gmail.com> <1187149599.24464.4.camel@localhost> <46C27C5E.5020103@cs.caltech.edu> <1118701012.20070815091156@yandex.ru> <20070815130504.GB10680@cspcag2.swan.ac.uk> <625b74080708150933h2d2e8c1qb719f2b3fc427ae6@mail.gmail.com> <46C3588D.4060807@imageworks.com> <625b74080708151312y2f1161cdq6ca5c6a0e2e60526@mail.gmail.com> Message-ID: Dan Piponi gmail.com> writes: > > On 8/15/07, Dan Weston imageworks.com> wrote: > > "You too could have invented Universal Algebra and Category Theory". > > I nominate Dan Piponi to write it and eagerly await its release! > > I've already started on it. Well, that's not the exact title and > subject. And as an example I'll probably use the definition of tensor > product that I linked to, not the even more compact and elegant one > that you just gave. > > I'm a strong believer that lots of (but not all) tricky looking > mathematics is just fancy language for intuitions that people already > have. I suspect that most computer scientists already have much of the > intuition behind the idea of a universal property, and that it is in > fact easier to grasp for a computer scientist than a mathematician. > > > -- > Dan > Some universal properties (initial algebras and final co-algebras) are covered in Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire (1991) (http://citeseer.ist.psu.edu/meijer91functional.html). And of course there's Wadler's Theorems for Free. Dominic. From chaddai.fouche at gmail.com Wed Aug 15 18:05:14 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Wed Aug 15 17:56:48 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: References: <46C3482D.8020200@cogito.org.uk> Message-ID: 2007/8/15, Chad Scherrer : > If there's a way to lazily sample with replacement from a list without > even requiring the length of the list to be known in advance, that > could lead to a solution. I'm not sure what you mean by "with replacement" but I think it don't change the fundamental problem. There is in fact a way to get a random sample from a list without getting it's length first, but it still require to look at the whole list so it shouldn't change anything anyway... except if you're dealing with data on disk (which the time for length() suggests... are you swapping and did you try to push your data out of RAM ?) where reading is expensive. Here it is : getRandomElt :: (RandomGen t) => [a] -> t -> a getRandomElt (x:xs) g = aux 2 g xs x where aux _ _ [] y = y aux i g (x:xs) y = let (r,ng) = randomR (1, i) g in if r == 1 then aux (i+1) ng xs x else aux (i+1) ng xs y There is an equiprobability that each element of the list is chosen. -- Jeda? From chad.scherrer at gmail.com Wed Aug 15 18:52:26 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Wed Aug 15 18:43:59 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: <46C37E1C.5020500@cogito.org.uk> References: <46C3482D.8020200@cogito.org.uk> <46C35985.4010302@cogito.org.uk> <46C37E1C.5020500@cogito.org.uk> Message-ID: Yeah, I did have troubles with (StateT StdGen Maybe). If it hits a "Nothing", I'd like it to skip that one and try again with the next state. But instead, Nothing is treated as a failure condition that makes the whole thing fail. I just found MaybeT on the wiki, which looks like it could work. I'll take a look at that and the ListT thing. I'm starting to think the power of abstraction is a blessing and a curse. Haskell's abstraction mechanisms are so powerful that it's generally possible to come up with a way to solve a given problem elegantly and efficiently. On the other hand, if a problem isn't so well studied, the bulk of the work is in finding the right abstraction, which forces generalization beyond what would otherwise be needed (though it'll be easier the next time!). On 8/15/07, Paul Johnson wrote: > Chad Scherrer wrote: > > Funny you should say that, I was just experimenting with generating > > one at a time using (StateT StdGen Maybe). If I get stuck (again) I'll > > check out ListT. Thanks! > > > > > You definitely want a list not a Maybe. List is for 0 or more results > whereas Maybe is for 0 or 1. Yes you can have a Maybe [a] with Nothing > instead of [], but its redundant. > > I'm fairly sure you need it the other way out too. All About Monads has > a demo of StateT s [a] where it is used to solve a logic problem. The > key point is that in the logic problem each possible result is > associated with a different state change. However here you want to have > a list of results and then a state change when you pick one (or a > subset, or whatever you want). So that would be ListT (StateT StdGen). > > Paul. > > -- Chad Scherrer "Time flies like an arrow; fruit flies like a banana" -- Groucho Marx From joelr1 at gmail.com Wed Aug 15 20:22:11 2007 From: joelr1 at gmail.com (Joel Reymont) Date: Wed Aug 15 20:14:01 2007 Subject: [Haskell-cafe] Erlang VM in Haskell Message-ID: Folks, I would like to write an Erlang VM in Haskell. I first thought of OCaml but Haskell has SMP and lazy evaluation may come in handy. Plus, I'll need help in this project like in no other and support from the Haskell community has always been outstanding. I'm doing this to learn more about the Erlang internals and to acquire some skills in the process. I'm also hoping to be at least as fast as the existing Erlang VM (written in C) and to be able to extend the VM in a functional language. With C you can implement a threaded VM using GCC labels or switch- style [1]. What is the most efficient approach in Haskell? I'm thinking using CPS and building up a chain of closures. Would this work well? Any other suggestions? The Haskell repo for the initial HEM (Haskell Erlang Machine) is at http://darcs.haskell.org/hem. A much improved HAW implementation will follow in the not so near future. Thanks, Joel [1] http://www.complang.tuwien.ac.at/forth/threaded-code.html -- http://wagerlabs.com From chaddai.fouche at gmail.com Wed Aug 15 20:36:08 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Wed Aug 15 20:27:45 2007 Subject: [Haskell-cafe] Erlang VM in Haskell In-Reply-To: References: Message-ID: 2007/8/16, Joel Reymont : > I'm doing this to learn more about the Erlang internals and to > acquire some skills in the process. I'm also hoping to be at least as > fast as the existing Erlang VM (written in C) That don't seem too realistic since the Erlang development team is big with much backing and very competent hacker behind it and C _is_ faster than Haskell if used properly (I guess you could make the difference with better algorithms and data structures but that's where the competence and size of the Erlang team makes it less likely). But still it seems like a _very_ interesting project and it would be awesome to have a fast (enough) VM for Erlang in Haskell ! ^^ Good luck ! -- Jeda? From steve at fenestra.com Wed Aug 15 21:31:25 2007 From: steve at fenestra.com (Steve Schafer) Date: Wed Aug 15 21:23:01 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: References: <46C 3482D.8020200@cogito.org.uk> Message-ID: <61a7c3pdrlkcqvc7qmbv8c4jb9balsq1ga@4ax.com> On Thu, 16 Aug 2007 00:05:14 +0200, you wrote: >I'm not sure what you mean by "with replacement" "With replacement" means that you select a value from the source, but you don't actually remove it. That way, it's still available to be selected again later. Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ From ok at cs.otago.ac.nz Thu Aug 16 01:33:25 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 16 01:25:02 2007 Subject: [Haskell-cafe] Problem installing GHC6.6 In-Reply-To: <12155220.post@talk.nabble.com> References: <12155220.post@talk.nabble.com> Message-ID: Trying to install GHC 6.6 on a Solaris 2.9 box (do I have the last 2.9 box in captivity? I've asked for 2.10, really and truly I have) I ran into two problems. (1) Somewhere it was assumed that only FreeBSD didn't have stdint.h. Solaris 2.9 doesn't have stdint.h. That was an easy patch. (2) In file included from Readline.hsc:16: include/HsReadline.h:5:31: readline/readline.h: No such file or dire.. include/HsReadline.h:6:30: readline/history.h: No such file or direc.. leading to a cascade of errors like Readline.hsc:570: error: `ISFUNC' undeclared Now I _have_ /usr/local/include/readline/*.h; if configure figured out that I have this library, why didn't it tell the C compiler where to look for the headers? The missing (undeclared) identifiers don't seem to be declared in those headers anyway. What to do? From loppermann at acm.org Thu Aug 16 02:59:14 2007 From: loppermann at acm.org (Lars Oppermann) Date: Thu Aug 16 02:50:48 2007 Subject: [Haskell-cafe] Problem installing GHC6.6 In-Reply-To: References: <12155220.post@talk.nabble.com> Message-ID: > Now I _have_ /usr/local/include/readline/*.h; if configure figured > out that I have this library, why didn't it tell the C compiler > where to look for the headers? > > The missing (undeclared) identifiers don't seem to be declared in > those headers anyway. It seemed to me that you need to specify the readline locations explicitly in order for them to be picked up by the readline module at build time. ./configure --with-readline-includes=/usr/local/include --with-readline-libraries=/usr/local/lib did the trick for me. Setting CPPFLAGS=-I/usr/local/include (and LDFLAGS respectively) didn't carry through to the build of the readline module. HTH Lars -- Lars Oppermann Hamburg, Germany From jon.fairbairn at cl.cam.ac.uk Thu Aug 16 05:11:24 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Thu Aug 16 05:03:11 2007 Subject: [Haskell-cafe] Re: defining last using foldr References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> Message-ID: "Chadda? Fouch?" writes: > > so you need an f so that c `f` x is c (for any c and x) and > > yet (b `f` c) is c for any c and b -- this is impossible (or > > I'm asleep). > > Well, it isn't "impossible" but quite hard (and not even standard H98 > if I'm not mistaken) If it is possible, I'm very sad that we've allowed things to get into the language that make that kind of reasoning faulty. > Still you could "approximate" it, and in fact I believe the [Char] -> > Char requirement is hinting at such a (arguably and IMO ugly) > solution. For example you could assume there would be no "NUL" > character in a string ([Char] is a synonym for String, or vice-versa), > and then get a simple myLast for String in this restrictive case (and > looking exactly like Alexteslin sample). I certainly wouldn't count such a thing as a valid solution. It's always amazed me that C uses as standard a mechanism of ending strings that is so obviously an error-prone hack. -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From chaddai.fouche at gmail.com Thu Aug 16 06:13:54 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Thu Aug 16 06:05:26 2007 Subject: [Haskell-cafe] Re: defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> Message-ID: 16 Aug 2007 10:11:24 +0100, Jon Fairbairn : > snip my quote > > I certainly wouldn't count such a thing as a valid > solution. It's always amazed me that C uses as standard a > mechanism of ending strings that is so obviously an > error-prone hack. I'm completely with you on that ! Which is why I don't like the suggestion of doing it only for Char... > > Well, it isn't "impossible" but quite hard (and not even standard H98 > > if I'm not mistaken) > > If it is possible, I'm very sad that we've allowed things to > get into the language that make that kind of reasoning > faulty. I spoke too fast on this one, it _is_ impossible (I think ?), but you can use the same trick as for Char to get a polymorphic function, arguably a little bit more useful than the Char one, since if you have a undefined as the last element of your list, there's a good chance anyway that your program is already in a bad state. Still it's an ugly hack altogether... Your suggestion is of course the right answer if there is an obligation to use a foldr and not just any fold. -- Jeda? From bertram.felgenhauer at googlemail.com Thu Aug 16 07:46:03 2007 From: bertram.felgenhauer at googlemail.com (Bertram Felgenhauer) Date: Thu Aug 16 07:37:40 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <1187203789.24215.47.camel@localhost> References: <46C3368C.4050302@metamilk.com> <20070815175036.GA3020@localhost.localdomain> <1187200720.24215.39.camel@localhost> <20070815180636.GB3020@localhost.localdomain> <1187203789.24215.47.camel@localhost> Message-ID: <20070816114603.GA4586@zombie.inf.tu-dresden.de> Duncan Coutts wrote: > On Wed, 2007-08-15 at 11:06 -0700, Stefan O'Rear wrote: > > > foo = getSomethingCPS $ \ arg -> > > moreStuff > > > > is now a syntax error (\ { varid -> } matches no productions). > > I'm not sure I follow. > > The patterns would have to match up in a column, so > > foo = getSomethingCPS $ \ arg -> > moreStuff > > should be fine, to add another alternative it'd have to be: > > foo = getSomethingCPS $ \ Pat1 -> > moreStuff > Pat2 -> > evenMoreStuff I don't like this - it's not in the spirit of the existing layout rule at all. You should have to indent 'moreStuff' deeper than Pat1 I think; > foo = getSomethingCPS $ \ Pat1 -> > moreStuff > Pat2 -> > evenMoreStuff would be (visually) ok. But then Stefan's point is valid. So there should be two productions, I think, one for non-case lambdas and one for case-lambdas, like this: non-case-lambda: '\' apat+ '->' expr case-lambda: '\' '{' ( apat+ '->' expr ';' )* '}' Unfortunately this naive approach would add another point of arbitrarily large look-ahead to the grammar. The easiest way to resolve this is to add some keyword before or after '\', bringing is back to the previous proposals. I like both \of x y z -> ... a b c -> ... and case \ of x y z -> ... a b c -> ... (I'd add the space here, viewing \ as a pseudo-expression) In the spirit of the \\ proposal, while \\ itself is an operator, \ \ x y z -> ... a b c -> ... is still available as a syntax, but may be confusing. I have little preference between these options. Bertram From hthiel.char at zonnet.nl Thu Aug 16 08:06:19 2007 From: hthiel.char at zonnet.nl (Hans van Thiel) Date: Thu Aug 16 07:56:42 2007 Subject: [Haskell-cafe] Haskell for the Enterprise (topic for a MSc dissertation?) In-Reply-To: References: Message-ID: <1187265979.3255.4.camel@localhost.localdomain> On Wed, 2007-08-15 at 15:04 +0200, Lars Oppermann wrote: > Hi All, > > This is my first post here, so I'll start with a quick introduction... > I live and work in Hamburg, Germany. My day job is as a software > engineer at Sun Microsystems at the OpenOffice.org development team > where I'm mostly doing XML (ODF) related things. Beside of that, I'm > currently pursuing an M.Sc degree in software engineering in a > part-time post graduate program where I am now nearing the phase where > I have to develop a topic for my dissertation. > > Apart from a little dabbling with Miranda during my undergraduate CS > days I haven't touched functional programming ever since and have been > doing Java, C# and C++ most of the time. However, I have over the last > few month "fallen in love" with the great expressiveness offered by > Haskell and through that have gained some great new perspectives and > discovered new ways to think when writing programs. > > Consequently, my idea to combine all of this into a topic for my > dissertation is to write about the existing and potential benefits > (and shortcomings) of a functional programming language for the > development of typical enterprise applications (especially with > regards to more and more concepts from functional programming being > adopted in imperative languages). I would start off with an existing > J2EE application, analyze the abstractions and patterns that it uses. > I will then discuss similar and alternative abstractions and patterns > available in functional programming which can be applied in order to > solve the same problem in a functional setting, leveraging some > existing infrastructure, such as HAppS. What would follow is a > comparison of the two resulting applications from a software > engineering standpoint: How maintainable are these implementations? > How can they be tested? Can formal validation techniques be applied to > parts of the functional implementation that can be used to establish > its correctness. Maybe analysis of performance... > > One of my potential supervisors for the dissertation has already > indicated some interest in the topic so it all looks quite well to me. > The overview that I gave above obviously needs much more elaboration, > but as I said, I have just started developing topics. > > I would love to hear your comments on this. Has this been done over > and over already? Are there any source which you think of from the top > of your head which I should check out? Books that you would want to > recommend? There is a lot of scientific literature, but not much has been done with actual engineering in mind. There is no Red Hat, no Suse, no MontaVista and there is no company sponsoring its development in a big way, like Sun. It's not supported by any business consortium or even standardized by any official group. But people are working on an O'Reilly book about Haskell in practice (Real World Haskell). You might also want to read the 'History of Haskell' which has a section on use in industry. Maybe you could talk to some of those people. What I know is that it is being deployed other than in open source, but that fact is not being advertised in the marketing. Maintainability should be excellent in Haskell, due to the fine grained modularity without side effects. Best Regards, Hans van Thiel > > > As I wrote above, I'm quite new to Haskell. Thus if anyone wants to > recommend some readings specifically on the aspect of modeling in a > functional environment I'd be happy to hear about that too. > > All the best, > Lars > > -- > Lars Oppermann > Hamburg, Germany From njbartlett at gmail.com Thu Aug 16 08:36:39 2007 From: njbartlett at gmail.com (Neil Bartlett) Date: Thu Aug 16 08:28:16 2007 Subject: [Haskell-cafe] Erlang VM in Haskell In-Reply-To: References: Message-ID: Joel, This sounds like an extremely interesting (but very ambitious!) project, which I would like to get involved with if I have the time. However, wouldn't it be rather difficult, given that there doesn't seem to be a publicly available specification for the Erlang VM or the BEAM file format -- according to this email thread on the erlang-questions list: http://www.nabble.com/VM---BEAM-Specs-t4215515.html Perhaps it would be interesting to look at a slightly more constrained problem: can Erlang's message passing model (including distributed messaging across a network) and process monitoring facilities be replicated in Haskell? In other words, can we build OTP in Haskell? Regards, Neil On 8/16/07, Joel Reymont wrote: > Folks, > > I would like to write an Erlang VM in Haskell. I first thought of > OCaml but Haskell has SMP and lazy evaluation may come in handy. > Plus, I'll need help in this project like in no other and support > from the Haskell community has always been outstanding. > > I'm doing this to learn more about the Erlang internals and to > acquire some skills in the process. I'm also hoping to be at least as > fast as the existing Erlang VM (written in C) and to be able to > extend the VM in a functional language. > > With C you can implement a threaded VM using GCC labels or switch- > style [1]. What is the most efficient approach in Haskell? > > I'm thinking using CPS and building up a chain of closures. Would > this work well? Any other suggestions? > > The Haskell repo for the initial HEM (Haskell Erlang Machine) is at > http://darcs.haskell.org/hem. A much improved HAW implementation will > follow in the not so near future. > > Thanks, Joel > > [1] http://www.complang.tuwien.ac.at/forth/threaded-code.html > > -- > http://wagerlabs.com > > > > > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From joelr1 at gmail.com Thu Aug 16 08:41:59 2007 From: joelr1 at gmail.com (Joel Reymont) Date: Thu Aug 16 08:33:52 2007 Subject: [Haskell-cafe] Erlang VM in Haskell In-Reply-To: References: Message-ID: On Aug 16, 2007, at 1:36 PM, Neil Bartlett wrote: > However, wouldn't it be rather difficult, given that there doesn't > seem to be a publicly available specification for the Erlang VM or the > BEAM file format Very difficult, correct. I use Erlang daily, in fact Erlang is what brings bread to my table. I want to learn more about the Erlang insides so I'll simply dig in. > Perhaps it would be interesting to look at a slightly more constrained > problem: can Erlang's message passing model (including distributed > messaging across a network) and process monitoring facilities be > replicated in Haskell? My ultimate goal is to have a version of the Erlang VM that's suitable for running trading systems, i.e. one that allows high-speed numerics. I don't have much interest in replicating OTP in Haskell and Haskell may ultimately not be the right choice for what I envision. Thanks, Joel -- http://wagerlabs.com From lennart at augustsson.net Thu Aug 16 09:00:58 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Thu Aug 16 08:52:30 2007 Subject: [Haskell-cafe] Erlang VM in Haskell In-Reply-To: References: Message-ID: I think Haskell is the right language to nail down the semantics of Erlang and to prototype an implementation. For performance, I think Haskell is probably not the right language, because you need high performing low level code. This isn't impossible in Haskell, but the implementations are not geared towards that. On 8/16/07, Joel Reymont wrote: > > > On Aug 16, 2007, at 1:36 PM, Neil Bartlett wrote: > > > However, wouldn't it be rather difficult, given that there doesn't > > seem to be a publicly available specification for the Erlang VM or the > > BEAM file format > > Very difficult, correct. I use Erlang daily, in fact Erlang is what > brings bread to my table. I want to learn more about the Erlang > insides so I'll simply dig in. > > > Perhaps it would be interesting to look at a slightly more constrained > > problem: can Erlang's message passing model (including distributed > > messaging across a network) and process monitoring facilities be > > replicated in Haskell? > > My ultimate goal is to have a version of the Erlang VM that's > suitable for running trading systems, i.e. one that allows high-speed > numerics. I don't have much interest in replicating OTP in Haskell > and Haskell may ultimately not be the right choice for what I envision. > > Thanks, Joel > > -- > http://wagerlabs.com > > > > > > _______________________________________________ > 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/haskell-cafe/attachments/20070816/74afbd0c/attachment.htm From thomas.hartman at db.com Thu Aug 16 09:39:54 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Thu Aug 16 09:31:16 2007 Subject: [Haskell-cafe] trouble building 6.7 on ubuntu In-Reply-To: Message-ID: I have gotten ghc 6.7 to compile, but not with extra libs. I'm on linux x86, ubuntu. Can someone suggest a download date that worked for them, or how to fix one or more of the problems described below? When I build from source (this is for august 2, unknown linux, as conal spoke well of it :) but I have tried with several other dates in august with the same result) I get Linux linuxpt 2.6.15-23-386 #1 PREEMPT Tue May 23 13:49:40 UTC 2006 i686 GNU/Linux The programs included with the Ubuntu system are free software; checking host system type... i686-pc-linux-gnu checking target system type... i686-pc-linux-gnu Which we'll further canonicalise into: i386-unknown-linux checking for path to top of build tree... ./configure: line 1433: cd: utils/pwd: No such file or directory ./configure: line 1438: -v0: command not found ./configure: line 1441: utils/pwd/pwd: No such file or directory configure: error: cannot determine current directory when I try unzip src and extralibs I get (aug 15... tail of a large out file after >1.5 hours of configure; make > out.txt) ...... make[1]: Leaving directory `/home/hartthoma/installs/ghc6.7/aug15/ghc-6.7.20070815/libraries' make -C libraries all make[1]: Entering directory `/home/hartthoma/installs/ghc6.7/aug15/ghc-6.7.20070815/libraries' rm -f -f stamp/configure.library.*.base base/unbuildable ( cd base && setup/Setup configure \ --enable-library-profiling --enable-split-objs \ --prefix='$topdir' \ --datadir='$prefix/share/ghc' \ --datasubdir='.' \ --libsubdir='$compiler/lib/$pkgid' \ --with-compiler=../../compiler/stage1/ghc-inplace\ --with-hc-pkg=../../utils/ghc-pkg/ghc-pkg-inplace\ --with-hsc2hs=../../utils/hsc2hs/hsc2hs-inplace \ --with-ld=/usr/bin/ld \ --haddock-args="--use-contents=../index.html \ --use-index=../doc-index.html" \ \ --configure-option=--with-cc=gcc ) \ && touch stamp/configure.library.build-profiling-splitting.base || touch base/unbuildable Setup: Warning: Unknown fields: nhc98-options (line 173) Fields allowed in this section: buildable, cc-options, ld-options, frameworks, c-sources, extensions, extra-libraries, extra-lib-dirs, includes, install-includes, include-dirs, hs-source-dirs, other-modules, ghc-prof-options, ghc-options, hugs-options, nhc-options, jhc-options, exposed-modules Setup: Warning: A package using section syntax should require "Cabal-Version: >= 1.2" or equivalent. HsColour 1.6 configure: Reading installed packages... Configuring base-2.1... configure: Flags chosen: isghc=True configure: Dependency rts-any: using rts-1.0 Setup: executing external program failed (exit 1) : /usr/local/bin/HsColour -version rm -f base/GNUmakefile cp Makefile.local base if ifBuildable/ifBuildable base; then \ cd base && setup/Setup makefile -f GNUmakefile; \ fi Setup: error reading dist/setup-config; run "setup configure" command? make[1]: *** [base/GNUmakefile] Error 1 make[1]: Leaving directory `/home/hartthoma/installs/ghc6.7/aug15/ghc-6.7.20070815/libraries' make: *** [stage1] Error 2 very weird error because when I execute /usr/local/bin/HsColour -version it doesn't fail but outputs 1.6. Can somebody suggest a download date known to compile (with extralibs) for ubuntu? Or suggest a fix? By the way I have also tried darcs get http://hackage.haskell.org/trac/ghc but this dies about halfway through (in the patch 10000s ) with libcurl error 18 or libcurl error 404 depending on the phase of the moon. I'm currently trying a build from darcs checkout with get --partial. If this is the preferred way of doing a checkout due to "crapping out halfway" issues maybe it should be said in the readme. (to be honest I forget what the difference between a partial darcs get and a complete get is.) Much obliged, thomas. "Conal Elliott" Sent by: cvs-ghc-bounces@haskell.org 08/15/2007 06:38 PM To cvs-ghc@haskell.org cc Subject Fwd: how to get packages for HEAD snapshot ? oops -- meant to cc cvs-ghc btw, 20070802 does run and does have libs included. ---------- Forwarded message ---------- From: Conal Elliott < conal@conal.net> Date: Aug 15, 2007 2:56 PM Subject: Re: how to get packages for HEAD snapshot ? To: Stefan O'Rear Thank Stefan, The latest mingw32 snapshot I see is 20070811. I installed it also, and when I run ghc, it just crashes (WinXP). Happens when I run it inside of emacs and also in a cygwin bash window. Is that a known problem? - Conal On 8/15/07, Stefan O'Rear < stefanor@cox.net> wrote: On Wed, Aug 15, 2007 at 02:20:53PM -0700, Conal Elliott wrote: > I installed ghc-6.7.20070810-i386-unknown-mingw32.exe. Though it runs, I > don't know how to get other packages installed, including Cabal. "ghc-pkg > list" tells me that I have only {ghc-6.7.20070810}, rts-1.0. > > Any suggestions? Upgrade GHC; Cabal should be installed but wasn't due to a bug in that snapshot. Stefan -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) iD8DBQFGw3AnFBz7OZ2P+dIRArOwAKCMEEzbB/JwEYnA21wZb4gf1rCoDQCeL1DG u5ljAbmfp5j0sd5X51nf3wk= =hewc -----END PGP SIGNATURE----- _______________________________________________ Cvs-ghc mailing list Cvs-ghc@haskell.org http://www.haskell.org/mailman/listinfo/cvs-ghc --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070816/16ef03d0/attachment.htm From Christian.Maeder at dfki.de Thu Aug 16 10:47:03 2007 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Thu Aug 16 10:38:54 2007 Subject: [Haskell-cafe] Re: Problem installing GHC6.6 In-Reply-To: References: <12155220.post@talk.nabble.com> Message-ID: <46C46367.8030206@dfki.de> ok wrote: > Trying to install GHC 6.6 on a Solaris 2.9 box (do I have the last > 2.9 box in captivity? I've asked for 2.10, really and truly I have) > I ran into two problems. Is it Solaris for Sparc or x86? Did you try to install one of the binary dists from the download pages? http://www.haskell.org/ghc/download_ghc_66.html#sparcsolaris Try to install ghc-6.6.1. (You need libreadline.so.5) http://www.haskell.org/ghc/download_ghc_661.html#sparcsolaris HTH Christian From a.biurvOir4 at asuhan.com Thu Aug 16 12:55:11 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Thu Aug 16 12:46:43 2007 Subject: [Haskell-cafe] Explaining monads In-Reply-To: <46C3372F.4010406@yale.edu> References: <6f680f6d0708091314x667996ackc42ae3ac56f83b3e@mail.gmail.com> <234992.65432.qm@web31410.mail.mud.yahoo.com> <46C1273D.50303@mindspring.com> <46C1C24F.1030905@cisco.com> <3d96ac180708140820v43414d07jee903bdcea33076b@mail.gmail.com> <625b74080708140959o3e0ac489q4b7ae29ed4ee7766@mail.gmail.com> <3d96ac180708141011j6c616613g6c1ba0ea4bfa62b7@mail.gmail.com> <625b74080708141122g12a7391fg5dc6469130414c32@mail.gmail.com> <3d96ac180708141133s74f9238aq622a926fbb935859@mail.gmail.com> <625b74080708141152t2557f605v2c65222c56972336@mail.gmail.com> <3d96ac180708141213k33ac868bk766c673848f6a25d@mail.gmail.com> <46C3372F.4010406@yale.edu> Message-ID: <12185261.post@talk.nabble.com> Paul Hudak wrote: > > [I]n the one-of-many ways that I view monads, a monad is just a high-order > function that abstracts away function composition. In particular, if I > have an action f, and an action g, I can think of them as recipes, because > I can combine them via f >>= g. It's only after I combine all of my > actions together that I apply the result to my input (via "run"). > > Well, that's just like function composition. In particular, if I have a > function f, and a function g, I can think of them as recipes, because I > can combine them via f . g. > First a nitpick: At the beginning of the thread I had pointed out how co/monadic co/bind generalizes function /application/, i.e. flip ($). Generalized function /composition/ on the other hand has a different type. For instance, in the case of monads it's \begin{code} (<.>) :: Monad m => (a -> m b) -> (c -> m a) -> (c -> m b) (<.>) f g c = (g c) >>= f \end{code} Function (<.>) is flip (>>>) in the instance of Monad m => Arrow (Kleisli m). (For a moment there I couldn't find it in the haskell libs. Would be nice if Hoogle could read instances such as these. I must not be using Hoogle right, I couldn't even locate (>>=) by type signature.) Returning to the main point, like you and Dan P, I also have my reservations explaining a monadified value as a recipe, although for arguably different reasons. It's too chef-centric for me, to continue with the original analogy. I have an allergic reaction to "run" functions, at least what they connote. I claim that in genuinely monadic programming, you never think about "run". Code that's genuinely monadic works for all monads. Code like that is what you want to write. Or put another way, you just program like before except lifting stuff into an arbitrary monad. You then write different monads to retrofit the various add-on computations you want performed. I thought this is well-known for over 15 years? -- View this message in context: http://www.nabble.com/Explaining-monads-tf4244948.html#a12185261 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From stefanor at cox.net Thu Aug 16 14:02:36 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 16 13:54:08 2007 Subject: [Haskell-cafe] Re: trouble building 6.7 on ubuntu In-Reply-To: References: Message-ID: <20070816180235.GA3084@localhost.localdomain> On Thu, Aug 16, 2007 at 01:01:12PM -0400, Thomas Hartman wrote: > I repeated the install attempt described below using darcs head, including > the extra libs. > > I got the exact same error as before. > > Setup: Warning: Unknown fields: nhc98-options (line 173) .... and then a > cryptic error involving HsColour I'm running a full get from 20070712 without problems. (admittedly not Ubuntu) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070816/d8428a70/attachment.bin From kelanslists at gmail.com Thu Aug 16 14:09:26 2007 From: kelanslists at gmail.com (Kurt Hutchinson) Date: Thu Aug 16 14:00:57 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: <12169661.post@talk.nabble.com> References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> Message-ID: On 8/15/07, Alexteslin wrote: > I am really sorry, but i still can't define the function. The chapter the > exercise is in precedes algebraic types or Maybe a types. And is seems that > must being easy to define. > I answered some exercises on using foldr such as summing for example, but > this one i am trying: > > myLast :: [Int] -> Int > myLast (x:xs) = foldr (some function) x xs. > > With summing as i understood foldr goes through the list and sums up by (+) > operator and one argument like 0. Like: foldr (+) 0 xs I don't think you can do it directly using just foldr. However, you can use foldr to build up a function that, when applied to the list, will evaluate to the last element. foldr will be acting like a function composition engine that evaluates to a function to process the list. I got the idea for this from the article titled "Getting a Fix from the Right Fold" in The Monad Read Issue 6 (http://www.haskell.org/sitewiki/images/1/14/TMR-Issue6.pdf). See if reading that article helps. In particular, Solution 2 described in the article is the one with the structure I'm talking about. (Solution 3 fixes a space leak in Solution 2, if you want a bit more complexity.) From afalloon at synopsys.com Thu Aug 16 14:34:29 2007 From: afalloon at synopsys.com (Al Falloon) Date: Thu Aug 16 14:26:17 2007 Subject: [Haskell-cafe] Re: defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> Message-ID: <46C498B5.7070006@synopsys.com> Kurt Hutchinson wrote: > On 8/15/07, Alexteslin wrote: >> I am really sorry, but i still can't define the function. The chapter the >> exercise is in precedes algebraic types or Maybe a types. And is seems that >> must being easy to define. >> I answered some exercises on using foldr such as summing for example, but >> this one i am trying: >> >> myLast :: [Int] -> Int >> myLast (x:xs) = foldr (some function) x xs. >> >> With summing as i understood foldr goes through the list and sums up by (+) >> operator and one argument like 0. Like: foldr (+) 0 xs > > I don't think you can do it directly using just foldr. However, you > can use foldr to build up a function that, when applied to the list, > will evaluate to the last element. foldr will be acting like a > function composition engine that evaluates to a function to process > the list. Something like this? (spoiler warning) http://hpaste.org/2283 From afalloon at synopsys.COM Thu Aug 16 14:34:29 2007 From: afalloon at synopsys.COM (Al Falloon) Date: Thu Aug 16 14:26:27 2007 Subject: [Haskell-cafe] Re: defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> Message-ID: <46C498B5.7070006@synopsys.com> Kurt Hutchinson wrote: > On 8/15/07, Alexteslin wrote: >> I am really sorry, but i still can't define the function. The chapter the >> exercise is in precedes algebraic types or Maybe a types. And is seems that >> must being easy to define. >> I answered some exercises on using foldr such as summing for example, but >> this one i am trying: >> >> myLast :: [Int] -> Int >> myLast (x:xs) = foldr (some function) x xs. >> >> With summing as i understood foldr goes through the list and sums up by (+) >> operator and one argument like 0. Like: foldr (+) 0 xs > > I don't think you can do it directly using just foldr. However, you > can use foldr to build up a function that, when applied to the list, > will evaluate to the last element. foldr will be acting like a > function composition engine that evaluates to a function to process > the list. Something like this? (spoiler warning) http://hpaste.org/2283 From afalloon at synopsys.COM Thu Aug 16 15:09:24 2007 From: afalloon at synopsys.COM (Al Falloon) Date: Thu Aug 16 15:01:11 2007 Subject: [Haskell-cafe] The problem with abstraction (Was: monte carlo trouble) In-Reply-To: References: <46C3482D.8020200@cogito.org.uk> <46C35985.4010302@cogito.org.uk> <46C37E1C.5020500@cogito.org.uk> Message-ID: <46C4A0E4.40104@synopsys.com> Chad Scherrer wrote: > I'm starting to think the power of abstraction is a blessing and a > curse. Haskell's abstraction mechanisms are so powerful that it's > generally possible to come up with a way to solve a given problem > elegantly and efficiently. On the other hand, if a problem isn't so > well studied, the bulk of the work is in finding the right > abstraction, which forces generalization beyond what would otherwise > be needed (though it'll be easier the next time!). I agree with you, which is why I especially liked this post[1] by Claus Reinke that shows how you work from the "obvious" brute-force code and apply small transformations to come up with the beautiful abstracted code. [1] http://permalink.gmane.org/gmane.comp.lang.haskell.cafe/26066 From afalloon at synopsys.com Thu Aug 16 15:09:24 2007 From: afalloon at synopsys.com (Al Falloon) Date: Thu Aug 16 15:01:28 2007 Subject: [Haskell-cafe] The problem with abstraction (Was: monte carlo trouble) In-Reply-To: References: <46C3482D.8020200@cogito.org.uk> <46C35985.4010302@cogito.org.uk> <46C37E1C.5020500@cogito.org.uk> Message-ID: <46C4A0E4.40104@synopsys.com> Chad Scherrer wrote: > I'm starting to think the power of abstraction is a blessing and a > curse. Haskell's abstraction mechanisms are so powerful that it's > generally possible to come up with a way to solve a given problem > elegantly and efficiently. On the other hand, if a problem isn't so > well studied, the bulk of the work is in finding the right > abstraction, which forces generalization beyond what would otherwise > be needed (though it'll be easier the next time!). I agree with you, which is why I especially liked this post[1] by Claus Reinke that shows how you work from the "obvious" brute-force code and apply small transformations to come up with the beautiful abstracted code. [1] http://permalink.gmane.org/gmane.comp.lang.haskell.cafe/26066 From eivuokko at gmail.com Thu Aug 16 15:22:45 2007 From: eivuokko at gmail.com (Esa Ilari Vuokko) Date: Thu Aug 16 15:14:21 2007 Subject: [Haskell-cafe] Re: trouble building 6.7 on ubuntu In-Reply-To: References: Message-ID: On 8/16/07, Thomas Hartman wrote: > > > I repeated the install attempt described below using darcs head, including > the extra libs. > > I got the exact same error as before. > > Setup: Warning: Unknown fields: nhc98-options (line 173) .... and then a > cryptic error involving HsColour > > I think you run into Cabal bug - you need to remove (or upgrade?) HsColour in your path, if that's the case. Best regards, Esa -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070816/e03ca10b/attachment.htm From afalloon at synopsys.COM Thu Aug 16 15:24:02 2007 From: afalloon at synopsys.COM (Al Falloon) Date: Thu Aug 16 15:15:39 2007 Subject: [Haskell-cafe] Re: Pattern matching articles/explanations In-Reply-To: References: Message-ID: <46C4A452.9000201@synopsys.com> Ian Duncan wrote: > Hello everyone, I've been working on improving my Haskell knowledge, and > in doing so, I have read a little about as-patterns as well as some form > of pattern that uses "~" that I don't really understand. I suspect there > are even more lesser-known pattern matching expressions than just these, > but I don't have the stamina to decode the Haskell 98 Report. Are there > any articles anyone is aware of, or anything in the Haskell wiki that > covers the built-in pattern matching facilities pretty comprehensively? > I've looked in the Haskell wiki myself, but information on different > pattern matching abilities seems rather scattered and I'm not entirely > sure what I should be looking for. http://haskell.org/tutorial/patterns.html That is the pattern section from "A Gentle Introduction to Haskell". It should be a lot more accessible than the report. As to the specific reference: the ~pat is called an "irrefutable" pattern, which is an odd name because its primary purpose is to make the pattern lazy. For instance: f ~(Just x) y z = if something_complicated y then x else z In this case, the first parameter is not evaluated until x is demanded. In particular, unless (something_complicated y) is true it will not be demanded at all. The reason is that its called irrefutable is that it always succeeds (which could lead to pattern match failure at run-time) because you can't check the pattern until you evaluate the parameter. For our particular example, that means that (f Nothing foo bar) will still match, and if (something_complicated foo) is true, then you will get a pattern match failure at runtime when x is demanded. However, this is really useful if you only have one constructor, because it lets you deconstruct the value via a pattern and preserve the laziness. As another piece of trivia. Let bound patterns are already lazy, so you never need ~ in an outer pattern of a let. I.e. let Just x = foo is the same as let ~(Just x) = foo From afalloon at synopsys.com Thu Aug 16 15:24:02 2007 From: afalloon at synopsys.com (Al Falloon) Date: Thu Aug 16 15:15:50 2007 Subject: [Haskell-cafe] Re: Pattern matching articles/explanations In-Reply-To: References: Message-ID: <46C4A452.9000201@synopsys.com> Ian Duncan wrote: > Hello everyone, I've been working on improving my Haskell knowledge, and > in doing so, I have read a little about as-patterns as well as some form > of pattern that uses "~" that I don't really understand. I suspect there > are even more lesser-known pattern matching expressions than just these, > but I don't have the stamina to decode the Haskell 98 Report. Are there > any articles anyone is aware of, or anything in the Haskell wiki that > covers the built-in pattern matching facilities pretty comprehensively? > I've looked in the Haskell wiki myself, but information on different > pattern matching abilities seems rather scattered and I'm not entirely > sure what I should be looking for. http://haskell.org/tutorial/patterns.html That is the pattern section from "A Gentle Introduction to Haskell". It should be a lot more accessible than the report. As to the specific reference: the ~pat is called an "irrefutable" pattern, which is an odd name because its primary purpose is to make the pattern lazy. For instance: f ~(Just x) y z = if something_complicated y then x else z In this case, the first parameter is not evaluated until x is demanded. In particular, unless (something_complicated y) is true it will not be demanded at all. The reason is that its called irrefutable is that it always succeeds (which could lead to pattern match failure at run-time) because you can't check the pattern until you evaluate the parameter. For our particular example, that means that (f Nothing foo bar) will still match, and if (something_complicated foo) is true, then you will get a pattern match failure at runtime when x is demanded. However, this is really useful if you only have one constructor, because it lets you deconstruct the value via a pattern and preserve the laziness. As another piece of trivia. Let bound patterns are already lazy, so you never need ~ in an outer pattern of a let. I.e. let Just x = foo is the same as let ~(Just x) = foo From chad.scherrer at gmail.com Thu Aug 16 15:30:47 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Thu Aug 16 15:22:18 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: <46C35985.4010302@cogito.org.uk> References: <46C3482D.8020200@cogito.org.uk> <46C35985.4010302@cogito.org.uk> Message-ID: I'm using ListT now, trying to do this: type Sample a = ListT (State StdGen) a randomStreamR :: (RandomGen g, Random a) => (a,a) -> g -> ([a], g) randomStreamR bds g =(randomRs bds g1, g2) where (g1,g2) = split g sample :: [a] -> Sample a sample [] = ListT (State f) where f s = case next s of (_,s') -> ([],s') sample xs = do let bds = (1, length xs) xArr = listArray bds xs i <- ListT . State $ randomStreamR bds return $ (xArr ! i) -- Simple example, for testing main = mapM_ print . flip evalState (mkStdGen 1) . runListT $ do x <- sample [1..100] y <- sample [1..x] return (x,y) The abstraction seems much better now, but even the simple little example blows up in memory. Here's a snippet from profiling with -auto-all -caf-all (after I interrupted it): CAF:lvl4 Main 261 1 0.0 0.0 100.0 100.0 main Main 273 0 0.0 0.0 100.0 100.0 sample Main 274 1 100.0 100.0 100.0 100.0 randomStreamR Main 276 1 0.0 0.0 0.0 0.0 I'm wondering if the bind for ListT is still effectively building every possibility behind the scenes, and sampling from that. I could redo the Sample monad by hand, if that could be the problem, but I'm not sure what changes would need to be made. Or maybe it's building lots of different arrays and holding them for too long from the GC. Or maybe it's a strictness/laziness issue I'm missing. Still not so sure when I need case vs let/where. How would you guys going about tracking down the problem? Thanks, Chad On 8/15/07, Paul Johnson wrote: > Chad Scherrer wrote: > > Thanks for your replies. > > > > I actually starting out returning a single element instead. But a > > given lookup might return [], and the only way I could think of to > > handle it in (State StdGen a) would be to fail in the monad. But > > that's not really the effect I want - I'd rather have it ignore that > > element. Another option was to wrap with Maybe, but then since I > > really want a sequence of them anyway, I decided to just wrap in a > > List instead. Is there a way Maybe would work out better? > Ahh. How about using ListT Gen then? That (if I've got it the right > way round) works like the list monad (giving you non-determinism), but > has your random number generator embedded as well. Take a look at "All > About Monads" at http://www.haskell.org/all_about_monads/html/. Each > action in the monad may use a random number and produce zero or more > results. > > Paul. > > > From a.biurvOir4 at asuhan.com Thu Aug 16 15:50:23 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Thu Aug 16 15:41:54 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> Message-ID: <12188224.post@talk.nabble.com> Aaron Denney wrote: > > On 2007-08-15, Pekka Karjalainen wrote: >> A little style issue here on the side, if I may. You don't need to use >> (++) to join multiline string literals. >> >> text = "If you want to have multiline string literals \ >> \in your source code, you can break them up with \ >> \backslashes. Any whitespace characters between \ >> \two backslashes will be ignored." > > I find the first far more readable. The compiler should be able to > assemble it all at compile time, right? > 'Course not. The (++) function like all Haskell functions is only a /promise/ to do its job. What does "assembling at compile time" mean here: s = "I will not write infinite loops " ++ s -- View this message in context: http://www.nabble.com/Hints-for-Euler-Problem-11-tf4114963.html#a12188224 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From lennart at augustsson.net Thu Aug 16 16:18:15 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Thu Aug 16 16:09:47 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: <12188224.post@talk.nabble.com> References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> Message-ID: But if the strings are all constant it's perfectly feasible to concatenate them at compile time. On 8/16/07, Kim-Ee Yeoh wrote: > > > > Aaron Denney wrote: > > > > On 2007-08-15, Pekka Karjalainen wrote: > >> A little style issue here on the side, if I may. You don't need to use > >> (++) to join multiline string literals. > >> > >> text = "If you want to have multiline string literals \ > >> \in your source code, you can break them up with \ > >> \backslashes. Any whitespace characters between \ > >> \two backslashes will be ignored." > > > > I find the first far more readable. The compiler should be able to > > assemble it all at compile time, right? > > > > 'Course not. The (++) function like all Haskell functions is only a > /promise/ to do its job. What does "assembling at compile time" > mean here: > > s = "I will not write infinite loops " ++ s > > -- > View this message in context: > http://www.nabble.com/Hints-for-Euler-Problem-11-tf4114963.html#a12188224 > Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. > > _______________________________________________ > 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/haskell-cafe/attachments/20070816/7cd90d9c/attachment.htm From peter at syncad.com Thu Aug 16 15:35:33 2007 From: peter at syncad.com (Peter Hercek) Date: Thu Aug 16 16:11:40 2007 Subject: [Haskell-cafe] Re: hyperlinked haskell 98 grammar In-Reply-To: <404396ef0708160612p518faf5di15335d89a6d124f4@mail.gmail.com> References: <404396ef0708160609v18b5b6d7s58c6ea43417d34c6@mail.gmail.com> <404396ef0708160612p518faf5di15335d89a6d124f4@mail.gmail.com> Message-ID: <46C4A705.4080703@syncad.com> Hi Neil, For haskell-cafe members: This is what we are talking about: http://www.hck.sk/users/peter/ I'm glad somebody liked it. I do not understand what you mean by the extension request. Would you want to see the number of references of a production head even without opening the popup list box? If you meant that the pop-up list box should always display all backward links directly (without a scroll bar) then it would not work for a very big number of such links (in theory there can be hundreds there). If you do not like the default of 5 then change the nMaxRowCount "constant". Anyway, if it is complicated to describe, let it be. I do not expect to play with the java script code much. Only the most trivial things have a chance to be implemented by me. I have written the java script code few years ago and I do not really like java script ... Just wanted to give back something to the community - so I added the Haskell specific data. As for as putting it on the Haskell org I do not mind if somebody else does it. Although I'm not that sure if it would require license change. If I would believe giving it into public domain would make more grammars browsable like this one then I would do it. I do not really expect heavy loads. From my experience most language users never ever look at the grammar nor they care about it. And those who consult it a lot will take a local copy and tweak it anyway. Looking at the munin server loads, looks like you and Esa are the only ones who actually checked it out :-D Anyway, sending this to haskell cafe too (as recommended). I expect a discussion (if any) will continue there. Sorry about GHC user list abuse. Peter Hercek. Neil Mitchell wrote: > Hi > > In addition, perhaps this should be relocated to haskell.org, if your > server is not suitable for a large volume of users. I think it should > also be integrated somewhere (perhaps a link from the HTML report, and > certainly on the wiki) > > Thanks > > Neil > > On 8/16/07, Neil Mitchell wrote: >> Hi Peter, >> >> A nice application. One suggestion: I would have implemented it so >> that a maximum on one backward hyperlink menu could be visible at once >> - try clicking on two RHS's and you'll get too "menus" visible at the >> same time. >> >> You also might want to mail this out on haskell-cafe - which is more >> appropriate for "general haskell" things, ghc-users is more for direct >> issues with GHC (although haskell-cafe can also be used for those) >> >> Thanks >> >> Neil >> >> On 8/16/07, Peter Hercek wrote: >>> Hi, >>> >>> I was improving my Haskell knowledge lately and I created a small dhtml application which allows browsing of >>> Haskell 98 grammar. I contains both forward and backward hyperlinks. By backward hyperlink I mean that you can >>> click on an a production head and you get a popup list box where you can navigate to any production using the >>> nonterminal. If you like it please save and use your local copy since the server cannot handle much load. >>> >>> http://www.hck.sk/users/peter/ >>> >>> Peter. >>> >>> _______________________________________________ >>> Glasgow-haskell-users mailing list >>> Glasgow-haskell-users@haskell.org >>> http://www.haskell.org/mailman/listinfo/glasgow-haskell-users >>> From wnoise at ofb.net Thu Aug 16 16:27:08 2007 From: wnoise at ofb.net (Aaron Denney) Date: Thu Aug 16 16:19:00 2007 Subject: [Haskell-cafe] Re: Hints for Euler Problem 11 References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> Message-ID: On 2007-08-16, Kim-Ee Yeoh wrote: > > > Aaron Denney wrote: >> >> On 2007-08-15, Pekka Karjalainen wrote: >>> A little style issue here on the side, if I may. You don't need to use >>> (++) to join multiline string literals. >>> >>> text = "If you want to have multiline string literals \ >>> \in your source code, you can break them up with \ >>> \backslashes. Any whitespace characters between \ >>> \two backslashes will be ignored." >> >> I find the first far more readable. The compiler should be able to >> assemble it all at compile time, right? >> > > 'Course not. The (++) function like all Haskell functions is only a > /promise/ to do its job. What does "assembling at compile time" > mean here: > > s = "I will not write infinite loops " ++ s It's a circular list of characters. Quite feasible to do at compile time. -- Aaron Denney -><- From bf3 at telenet.be Thu Aug 16 16:43:59 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Thu Aug 16 16:35:30 2007 Subject: [Haskell-cafe] Collada, FBX, XML schemas and Haskell? Message-ID: I wanted to do some experiments with HOpenGL, and one of the things I tried is importing 3D models. So I searched for a library that could do that, but besides Frag, who uses the limited MD3 format, I did not find anything useful. Has any work been done on supporting that? Maybe just converting the 3D format into a series of HOpenGL calls (tools like that exists for C)? It would be nice to support Collada, one of the two standards for 3D models in the game industry. It is fully open and has exporters for most major 3D modeling packages. See http://en.wikipedia.org/wiki/COLLADA. The other standard is FBX, but that's a proprietary format from Autodesk. Collada comes with a full XML schema. Is it possible to convert an XML schema into Haskell data/code that automatically handles reading documents that follow the schema, as is commonly done when using Java or .NET? I looked at some XML libraries for Haskell, but could not figure out if they supported something like that. I can find the tools I need for C# or Java in an instance, but when it comes to Haskell I have difficulties understanding even the basic descriptions of some of the libraries ;-) Of course, that is because I'm a newbie in Haskell land and don't have a PhD degree, but it does make development in Haskell very frustrating! ;-) Thanks, Peter From iand675 at gmail.com Thu Aug 16 17:19:12 2007 From: iand675 at gmail.com (Ian Duncan) Date: Thu Aug 16 17:10:36 2007 Subject: [Haskell-cafe] Pattern matching articles/explanations Message-ID: So what I noticed that "A Gentle Introduction to Haskell" mentioned that wild-cards are useful in constructors. For example: head (x:_) = x So, does that offer any performance benefits over: head (x:xs) = x Or is it primarily to indicate to the coder that xs is useless? I get the impression it has a very similar meaning to the irrefutable pattern in regards to not evaluating it when the function is called. Or am I way off? From ndmitchell at gmail.com Thu Aug 16 17:27:49 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Thu Aug 16 17:19:20 2007 Subject: [Haskell-cafe] Pattern matching articles/explanations In-Reply-To: References: Message-ID: <404396ef0708161427g618e374ei772b86b348605a60@mail.gmail.com> Hi > So what I noticed that "A Gentle Introduction to Haskell" mentioned > that wild-cards are useful in constructors. For example: > > head (x:_) = x > > So, does that offer any performance benefits over: > > head (x:xs) = x No. They are exactly the same. _ simply means "a new unique name". > Or is it primarily to indicate to the coder that xs is useless? Yes > I get > the impression it has a very similar meaning to the irrefutable > pattern in regards to not evaluating it when the function is called. > Or am I way off? Way off :-) Nothing to do with irrefutable patterns, or demand of evaluation, its got two uses: 1) Indicate to the reader that this argument is never used 2) Save you coming up with a name for the argument Thanks Neil From wnoise at ofb.net Thu Aug 16 17:29:37 2007 From: wnoise at ofb.net (Aaron Denney) Date: Thu Aug 16 17:21:25 2007 Subject: [Haskell-cafe] Re: Pattern matching articles/explanations References: <404396ef0708161427g618e374ei772b86b348605a60@mail.gmail.com> Message-ID: On 2007-08-16, Neil Mitchell wrote: > Hi > >> So what I noticed that "A Gentle Introduction to Haskell" mentioned >> that wild-cards are useful in constructors. For example: >> >> head (x:_) = x >> >> So, does that offer any performance benefits over: >> >> head (x:xs) = x > > No. They are exactly the same. _ simply means "a new unique name". > >> Or is it primarily to indicate to the coder that xs is useless? > > Yes And to the compiler that the name won't be used, so it needn't warn you about not using it. -- Aaron Denney -><- From nominolo at googlemail.com Thu Aug 16 17:31:12 2007 From: nominolo at googlemail.com (Thomas Schilling) Date: Thu Aug 16 17:22:46 2007 Subject: [Haskell-cafe] Syntax for lambda case proposal could be "\of" In-Reply-To: <20070816114603.GA4586@zombie.inf.tu-dresden.de> References: <46C3368C.4050302@metamilk.com> <20070815175036.GA3020@localhost.localdomain> <1187200720.24215.39.camel@localhost> <20070815180636.GB3020@localhost.localdomain> <1187203789.24215.47.camel@localhost> <20070816114603.GA4586@zombie.inf.tu-dresden.de> Message-ID: <0E59ED96-29CE-4170-B155-2534F67FA266@googlemail.com> On 16 aug 2007, at 13.46, Bertram Felgenhauer wrote: > Duncan Coutts wrote: >> On Wed, 2007-08-15 at 11:06 -0700, Stefan O'Rear wrote: >> >>> foo = getSomethingCPS $ \ arg -> >>> moreStuff >>> >>> is now a syntax error (\ { varid -> } matches no productions). >> >> I'm not sure I follow. >> >> The patterns would have to match up in a column, so >> >> foo = getSomethingCPS $ \ arg -> >> moreStuff >> >> should be fine, to add another alternative it'd have to be: >> >> foo = getSomethingCPS $ \ Pat1 -> >> moreStuff >> Pat2 -> >> evenMoreStuff > > I don't like this - it's not in the spirit of the existing layout > rule at all. You should have to indent 'moreStuff' deeper than > Pat1 I think; > >> foo = getSomethingCPS $ \ Pat1 -> >> moreStuff >> Pat2 -> >> evenMoreStuff > > would be (visually) ok. But then Stefan's point is valid. > > So there should be two productions, I think, one for non-case > lambdas and one for case-lambdas, like this: > > non-case-lambda: > '\' apat+ '->' expr > > case-lambda: > '\' '{' ( apat+ '->' expr ';' )* '}' > > Unfortunately this naive approach would add another point of > arbitrarily large look-ahead to the grammar. The easiest way to > resolve this is to add some keyword before or after '\', > bringing is back to the previous proposals. > > I like both > > \of x y z -> ... > a b c -> ... > > and > > case \ of x y z -> ... > a b c -> ... > > (I'd add the space here, viewing \ as a pseudo-expression) > > In the spirit of the \\ proposal, while \\ itself is an operator, > > \ \ x y z -> ... > a b c -> ... > > is still available as a syntax, but may be confusing. .\ x y z -> ... a b c -> ... or just require unicode \lambda ;) From jgbailey at gmail.com Thu Aug 16 18:59:32 2007 From: jgbailey at gmail.com (Justin Bailey) Date: Thu Aug 16 18:51:03 2007 Subject: [Haskell-cafe] Diagnosing stack overflow Message-ID: I am trying to determine why my stack overflows in my medium sized program (it has several modules but maybe only 1000 LOC total). On Windows, at least, the ghcprof visualization tool doesn't work. Any suggestions besides an output trace? It may be the function below, which tries to determine if a list of strict bytestrings is longer than the count given. I have tried to make it strict but am not sure if it's too lazy. Any hints are appreciated. -- Determines if the length of the strings in the list is longer than the given -- count. If not, amount the list falls short is returned. Otherwise, -- -1 indicates the prefix list is at least that long. If the count is zero and -- the list is empty or just null strings, -1 is also returned. prefixesAtLeast :: Int -> [S.ByteString] -> Int prefixesAtLeast !0 !ss | null ss = 0 | all S.null ss = 0 | otherwise = -1 prefixesAtLeast !n !ss = prefixesAtLeast' n ss where prefixesAtLeast' !n ss | n < 0 = -1 | null ss = n | otherwise = let (!s : (!rest)) = ss in prefixesAtLeast' (n - (S.length s)) rest From duncan.coutts at worc.ox.ac.uk Thu Aug 16 19:38:47 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Thu Aug 16 19:29:02 2007 Subject: [Haskell-cafe] Re: trouble building 6.7 on ubuntu In-Reply-To: References: Message-ID: <1187307527.24215.192.camel@localhost> On Thu, 2007-08-16 at 22:22 +0300, Esa Ilari Vuokko wrote: > On 8/16/07, Thomas Hartman wrote: > Setup: Warning: Unknown fields: nhc98-options (line 173) .... > and then a cryptic error involving HsColour > I think you run into Cabal bug - you need to remove (or upgrade?) > HsColour in your path, if that's the case. Thanks to Esa for tracking down this bug. Now fixed in Cabal. (or it will be shortly in the next batch of patches) Duncan From haskell at brecknell.org Thu Aug 16 19:52:42 2007 From: haskell at brecknell.org (Matthew Brecknell) Date: Thu Aug 16 19:44:12 2007 Subject: [Haskell-cafe] Diagnosing stack overflow In-Reply-To: References: Message-ID: <1187308362.8691.1205805295@webmail.messagingengine.com> Justin Bailey: > I am trying to determine why my stack overflows in my medium sized > program [...snip...] > > prefixesAtLeast :: Int -> [S.ByteString] -> Int > prefixesAtLeast !0 !ss > | null ss = 0 > | all S.null ss = 0 > | otherwise = -1 > prefixesAtLeast !n !ss = prefixesAtLeast' n ss > where > prefixesAtLeast' !n ss > | n < 0 = -1 > | null ss = n > | otherwise = > let (!s : (!rest)) = ss > in > prefixesAtLeast' (n - (S.length s)) rest Stack overflows often occur when you evaluate a "thunk" (unevaluated computation) which you have previously allowed to become deeply nested. The usual example is something like: print $ foldl (+) 0 [1..1000000] => print $ foldl (+) (0+1) [2..1000000] => print $ foldl (+) ((0+1)+2) [3..1000000] => print $ foldl (+) (((0+1)+2)+3) [4..1000000] => ... => print (...(((0+1)+2)+3)+...+1000000) => stack overflow The key point of the example is that foldl itself doesn't need any of the intermediate values of the accumulator, so these just build up into a deeply-nested unevaluated thunk. When print finally demands an integer, the run-time pushes a stack frame for each level of parentheses it enters as it tries to evaluate the thunk. Too many parentheses leads to a stack overflow. Of course, the solution to the example is to use foldl', whose implementation uses strictness annotations to force evaluation of the accumulator at each iteration. In your function, all the thunks you create will be evaluated in the next recursive call, so it's unlikely that prefixesAtLeast is *in itself* causing a stack overflow. However, it's possible that your use of this function is forcing evaluation of a deeply-nested thunk you've created somewhere else (as print does in the foldl example). So if your initial indications are that the stack overflow is occurring somewhere during the evaluation of prefixesAtLeast, you might want to try following the food-chain back through its suppliers (parameters) until you find something like the foldl example. By they way, your sprinkling of strictness annotations (a sure sign of stack-overflow desperation!) should not be necessary. Everything you have annotated should be forced anyway, either immediately or within one recursive call. In particular, !0 is entirely unnecessary, since matching against 0 does just as good a job of forcing the parameter value as the strictness annotation. From levi.stephen at optusnet.com.au Thu Aug 16 20:20:37 2007 From: levi.stephen at optusnet.com.au (Levi Stephen) Date: Thu Aug 16 20:12:17 2007 Subject: [Haskell-cafe] I'm stuck in my thought experiment Message-ID: <46C4E9D5.5090503@optusnet.com.au> Hi, Apologies for a long post that may not be totally clear. I was thinking through a problem and how the data might be represented in Haskell. I'm now stuck and frustrated. Now, I'm not even sure whether I'm on the right track (I might still be thinking too OO). Suggestions/ideas would be much appreciated. I was imagining a drag and drop web page designer. There are a bunch of Widgets (e.g., BlogWidget, TextWidget, MenuWidget, etc) that the user can place on the page. Along with these are layout/container widgets (e.g., ColumnLayoutWidget) that can contain other widgets. I'm looking at a data structure that would allow this to be represented in Haskell, so I'm keeping in mind that these won't be written in code, but generated on the fly somehow (e.g., from a database or file). So, my thoughts were along the lines of something like: class Widget a where render :: a -> Html -- A page has a title and a Widget. -- I know this isn't valid Haskell, but I'm not sure how to specify what I -- want here. (existential types?) data Page = Page String Widget data TextWidget = TextWidget String instance Widget TextWidget .... -- An example layout widget data ColumnLayoutWidget = ColumnLayoutWidget [Widget] instance Widget ColumnLayoutWidget ... etc... So, entire pages might be represented something like: Page "Main" (ColumnLayoutWidget [MenuWidget, TextWidget mainPageText]) Page "About" (ColumnLayoutWidget [MenuWidget, TextWidget aboutPageText]) Where I get stuck, is I want to extract layout information into a parent page. This would allow global changes such as adding a header image to the above pages to be done once only. So I want to be able to have something like: layout = Page "Main" (ColumnLayoutWidget [MenuWidget, ??? ]) mainPage = ChildPage layout [TextWidget mainPageText] aboutPage = ChildPage layout [TextWidget aboutPageText] So, each page is it's layout/parent page, with additional widgets inserted/added. The issue becomes, given a parent page and the customized content for the child page, what is the best way to insert the customized content at the right point? Might a tree like structure be useful? But, how do you work out where in the tree child content gets added? Store a traversal with each sub tree of child page content that basically says 'insert here'? It might be simple to have a PlaceHolderWidget. Then insertions of the child page content happens at each of those widgets. This just gets trickier if I start considering multiple extension points for child pages and what happens when the layout/parent page changes. This is why I'm thinking I may be going along a bad path here. Thanks, Levi lstephen.wordpress.com From iand675 at gmail.com Thu Aug 16 20:20:09 2007 From: iand675 at gmail.com (Ian Duncan) Date: Thu Aug 16 20:12:26 2007 Subject: [Haskell-cafe] Looking at program execution Message-ID: Is there any way to view the steps that a haskell program goes through step by step? I'm thinking something similar to what I've seen in things I've been reading. For example: foldl (+) 0 [1..10] => (0+1) => ((0+1)+2) => (((0+1)+2)+3) => etc. I've seen these sorts of line-by-line execution steps, but I was curious if there was any way to simply type in a function and its arguments and have ghci or hugs or something print out this sort of visual representation of what's going on. Anyone know of something like this? From byorgey at gmail.com Thu Aug 16 20:42:28 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Thu Aug 16 20:34:00 2007 Subject: [Haskell-cafe] Looking at program execution In-Reply-To: References: Message-ID: <22fcbd520708161742o1fbeda31y26e7f4034d5790a3@mail.gmail.com> On 8/16/07, Ian Duncan wrote: > > Is there any way to view the steps that a haskell program goes > through step by step? > I'm thinking something similar to what I've seen in things I've been > reading. For example: > foldl (+) 0 [1..10] > => (0+1) > => ((0+1)+2) > => (((0+1)+2)+3) > => etc. > I've seen these sorts of line-by-line execution steps, but I was > curious if there was any way to simply type in a function and its > arguments and have ghci or hugs or something print out this sort of > visual representation of what's going on. Anyone know of something > like this? You probably want to check out Hat: http://www.haskell.org/hat/ I've only used it a bit myself but I think it provides some of the features you're looking for. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070816/c06bab9f/attachment.htm From ok at cs.otago.ac.nz Thu Aug 16 20:43:12 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 16 20:34:46 2007 Subject: [Haskell-cafe] Re: Bathroom reading In-Reply-To: References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> <200708141031.51497.sjanssen@cse.unl.edu> Message-ID: Someone mentioned the "Blow your mind" page. One example there really caught my attention. "1234567" => ("1357","246") foldr (\a ~(x,y) -> (a:y,x)) ([],[]) I've known about lazy match since an early version of the Haskell report, but have never actually used it. Last night, looking at that example, the lights went on and I finally grokked why it's there and understood when/why I might use it myself. Oh, I knew perfectly well what it does. It just never made itself at home in my head. I'd like to recommend this example for some sort of prize, therefore. From ok at cs.otago.ac.nz Thu Aug 16 21:03:20 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 16 20:54:53 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> Message-ID: <641FEAB9-7063-4D81-9426-630E08439B6D@cs.otago.ac.nz> Let's start by reminding ourselves what foldr does. foldr f z [x1,x2,...,xn] = f x1 (f x2 ... (f xn z) ...) Now let's ask about last: last [] = error ... last [x1,...,xn] = xn We're going to have to keep track of whether we have a last element or not. The obvious candidate for this is Maybe x. Initially there is no element, Nothing. f x Empty = Just x f x (Just y) = Just y This picks up a new value (x) when there wasn't one (Nothing) and keeps the old last element (Just y) when there was one (Just y). But this gives us a Maybe x, when we want an x, so we'll have to finish off with a fromJust. last = fromJust . foldr f Nothing where f _ r@(Just _) = r f x Nothing = Just x From haskell at brecknell.org Thu Aug 16 21:45:15 2007 From: haskell at brecknell.org (Matthew Brecknell) Date: Thu Aug 16 21:36:45 2007 Subject: [Haskell-cafe] I'm stuck in my thought experiment In-Reply-To: <46C4E9D5.5090503@optusnet.com.au> References: <46C4E9D5.5090503@optusnet.com.au> Message-ID: <1187315115.25035.1205816103@webmail.messagingengine.com> Levi Stephen: > [...] > I was imagining a drag and drop web page designer. There are a bunch of > Widgets (e.g., BlogWidget, TextWidget, MenuWidget, etc) that the user can > place on the page. > [...] > > class Widget a where > render :: a -> Html > > -- A page has a title and a Widget. > -- I know this isn't valid Haskell, but I'm not sure how to specify what I > -- want here. (existential types?) > data Page = Page String Widget If you wanted to make Page an existential type, it would look like this: data Page = forall w . Widget w => Page String w However, you will probably find it much more useful to define a single existential wrapper for all widgets: data WidgetW = forall w . Widget w => WidgetW w Then, for example, you can construct polymorphic lists of widgets, as is necessary for the column layout: data Columns = Columns [WidgetW] -- hmm, needs spacing info. And now Page just adds a string to a WidgetW: data Page = Page String WidgetW See the GHC users guide for more on how to use existential types. > [...] > layout = Page "Main" (ColumnLayoutWidget [MenuWidget, ??? ]) > mainPage = ChildPage layout [TextWidget mainPageText] > aboutPage = ChildPage layout [TextWidget aboutPageText] Layout just looks like a function. Assuming an existing global menu definition: layout ws = WidgetW (Page "Main" (WidgetW (Columns (menu : ws)))) Note the type of layout: a function taking a list of widgets and returning a single widget. You'll find a number of similar types useful for structuring your code. For example, functions taking a single widget and returning a single (more complex) widget, functions taking a single widget and a list of functions each taking a widget and returning a widget, and returning a list of widgets, and so on. It's called functional programming for a reason. :-) > This just gets trickier if I start considering multiple extension points > for child pages and what happens when the layout/parent page changes. > This is why I'm thinking I may be going along a bad path here. Indeed, abstractions of this kind usually require a fair amount of thought and experiment. I haven't given it either of these, but hopefully the suggestions will help you become less stuck. From westondan at imageworks.com Thu Aug 16 21:51:15 2007 From: westondan at imageworks.com (Dan Weston) Date: Thu Aug 16 21:42:48 2007 Subject: [Haskell-cafe] Re: Bathroom reading In-Reply-To: References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> <200708141031.51497.sjanssen@cse.unl.edu> Message-ID: <46C4FF13.6090005@imageworks.com> I hate to be a party pooper, but isn't this just: > f = foldr (\a z -> (a:snd z,fst z)) ([],[]) This takes less time to grok and takes no longer to run. But why stop there? > import Control.Arrow > swap = snd &&& fst > f = foldr (\a -> swap >>> first (a:)) ([],[]) Just read this aloud to see what it does (without the tilde encryption algorithm at work!). More importantly, there is manifestly no pattern failure to check for here. It is fun that with ~p we don't need deconstructors for p (reminds me of Lisp's setf), but how many types have exported constructors with no deconstructors? And Arrow notation makes up for the loss of fun, so you don't feel cheated. :) Dan P.S. Either doesn't count, because you can easily roll your own deconstructors: getLeft = either id undefined getRight = either undefined id but I honestly don't know why these aren't in Data.Either. Or for that matter, why swap is not in Control.Arrow, since it comes in handy quite frequently with pointless programming. ok wrote: > Someone mentioned the "Blow your mind" page. > One example there really caught my attention. > "1234567" => ("1357","246") > foldr (\a ~(x,y) -> (a:y,x)) ([],[]) > > I've known about lazy match since an early version of the Haskell > report, but have never actually used it. Last night, looking at > that example, the lights went on and I finally grokked why it's > there and understood when/why I might use it myself. > > Oh, I knew perfectly well what it does. It just never made itself > at home in my head. > > I'd like to recommend this example for some sort of prize, therefore. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From igloo at earth.li Thu Aug 16 22:14:10 2007 From: igloo at earth.li (Ian Lynagh) Date: Thu Aug 16 22:05:43 2007 Subject: [Haskell-cafe] Re: trouble building 6.7 on ubuntu In-Reply-To: References: Message-ID: <20070817021410.GB18269@matrix.chaos.earth.li> On Thu, Aug 16, 2007 at 09:39:54AM -0400, Thomas Hartman wrote: > > The programs included with the Ubuntu system are free software; > checking host system type... i686-pc-linux-gnu > checking target system type... i686-pc-linux-gnu > Which we'll further canonicalise into: i386-unknown-linux > checking for path to top of build tree... ./configure: line 1433: cd: > utils/pwd: > No such file or directory > ./configure: line 1438: -v0: command not found > ./configure: line 1441: utils/pwd/pwd: No such file or directory > configure: error: cannot determine current directory What commands are you running? Is the above the complete output? > By the way I have also tried > > darcs get http://hackage.haskell.org/trac/ghc > > but this dies about halfway through (in the patch 10000s ) with libcurl > error 18 or libcurl error 404 depending on the phase of the moon. You're probably best off downloading and untarring: http://darcs.haskell.org/ghc-HEAD-2007-08-14-ghc-corelibs.tar.bz2 and then "./darcs-all pull -a" to get up-to-date. These are --complete repos. Unfortunately we don't have a tarball that includes the extralibs at the moment, so you'll still need to "./darcs-all --extralibs get" them (either partially or completely). > I'm currently trying a build from darcs checkout with get --partial. If > this is the preferred way of doing a checkout If you don't want to hack on it then --partial is prefered as it's quicker and takes up less disk space. > due to "crapping out halfway" issues I don't know what's going on there. Thanks Ian From bos at serpentine.com Thu Aug 16 23:02:59 2007 From: bos at serpentine.com (Bryan O'Sullivan) Date: Thu Aug 16 22:54:29 2007 Subject: [Haskell-cafe] Diagnosing stack overflow In-Reply-To: References: Message-ID: <46C50FE3.2050301@serpentine.com> Justin Bailey wrote: > I am trying to determine why my stack overflows in my medium sized > program (it has several modules but maybe only 1000 LOC total). On > Windows, at least, the ghcprof visualization tool doesn't work. Any > suggestions besides an output trace? You shouldn't need ghcprof. Just compiling with -prof -auto-all will be enough to get you able to use allocation profiling, then running with +RTS -p -RTS will generate an allocation profile as a fairly readable text file. > It may be the function below, which tries to determine if a list of > strict bytestrings is longer than the count given. Taking stabs in the dark is not a good idea, and sprinkling strictness annotations around in an undirected manner won't help, either, however much it might feel like doing something concrete. Start with looking at the profile output. You'll probably find it's a different part of your code entirely that's causing the problem. References: Message-ID: <9d55dbaf0708170000h1d9be0fdl4f2b3e318cc33b4d@mail.gmail.com> Hello, 2007/8/16, Peter Verswyvelen : > I wanted to do some experiments with HOpenGL, and one of the things I tried is importing 3D models. > > So I searched for a library that could do that, but besides Frag, who uses the limited MD3 format, I did not find anything useful. Has any work been done on supporting that? Maybe just converting the 3D format into a series of HOpenGL calls (tools like that exists for C)? Some time ago I tried to write 'importer' for (full) MD2 format and then MD5 format from Id Software. I gathered quite a bit information about it and it should not be very complicated to support these format (especially MD2). Unfortunatly I hadn't had time to do that plus I'm Haskell newbie but importing and animating MD5 models in Haskell has such a appeal to me! I really encourage you to browse through MD2 specification. It is really straightforward and ready to be rendered "out-of-the-box". http://tfc.duke.free.fr/old/models/md2.htm Plus many 3D software have exporter to MD2. Cheers, Radek. -- Codeside: http://codeside.org/ Przedszkole Miejskie nr 86 w Lodzi: http://www.pm86.pl/ From ketil at ii.uib.no Fri Aug 17 03:46:41 2007 From: ketil at ii.uib.no (Ketil Malde) Date: Fri Aug 17 03:38:11 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: <12188224.post@talk.nabble.com> References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> Message-ID: <1187336801.6553.125.camel@nmd9999> On Thu, 2007-08-16 at 12:50 -0700, Kim-Ee Yeoh wrote: > > Aaron Denney wrote: > > > > On 2007-08-15, Pekka Karjalainen wrote: > >> A little style issue here on the side, if I may. You don't need to use > >> (++) to join multiline string literals. > >> > >> text = "If you want to have multiline string literals \ > >> \in your source code, you can break them up with \ > >> \backslashes. Any whitespace characters between \ > >> \two backslashes will be ignored." > > > > I find the first far more readable. The compiler should be able to > > assemble it all at compile time, right? > > > > 'Course not. The (++) function like all Haskell functions is only a > /promise/ to do its job. What does "assembling at compile time" > mean here: > > s = "I will not write infinite loops " ++ s Let's check, shall we? I've never used core before, but there's a first time for everything: % cat C.hs module Test where x = "Foo" ++ "Bar" y = "Zot" ++ y % ghc -ddump-simpl C.hs ==================== Tidy Core ==================== Test.x :: [GHC.Base.Char] [GlobalId] [] Test.x = GHC.Base.++ @ GHC.Base.Char (GHC.Base.unpackCString# "Foo") (GHC.Base.unpackCString# "Bar") Rec { Test.y :: [GHC.Base.Char] [GlobalId] [] Test.y = GHC.Base.++ @ GHC.Base.Char (GHC.Base.unpackCString# "Zot") Test.y end Rec } If I interpret it correctly, the compiler does approximately nothing - reasonably enough, since we didn't ask for optimization. With -O: % ghc -ddump-simpl C.hs -O ==================== Tidy Core ==================== Rec { Test.y :: [GHC.Base.Char] [GlobalId] [Str: DmdType] Test.y = GHC.Base.unpackAppendCString# "Zot" Test.y end Rec } Test.x :: [GHC.Base.Char] [GlobalId] [Str: DmdType] Test.x = GHC.Base.unpackCString# "FooBar" y gets turned into an unpackAppendCString#, which I can only presume is a sensible way to represent a cyclic list, while x gets concatenated compile-time. -k From a.biurvOir4 at asuhan.com Fri Aug 17 03:49:20 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Fri Aug 17 03:40:49 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> Message-ID: <12195537.post@talk.nabble.com> Lennart Augustsson wrote: > > On 8/16/07, Kim-Ee Yeoh wrote: >> 'Course not. The (++) function like all Haskell functions is only a >> /promise/ to do its job. What does "assembling at compile time" >> mean here: >> >> s = "I will not write infinite loops " ++ s > > But if the strings are all constant it's perfectly feasible to concatenate > them at compile time. > It's feasible and I might add that it isn't worth it. Not for just concatenation. How much static evaluation do you want to see in Haskell? -- View this message in context: http://www.nabble.com/Hints-for-Euler-Problem-11-tf4114963.html#a12195537 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From apfelmus at quantentunnel.de Fri Aug 17 04:24:34 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Fri Aug 17 04:16:17 2007 Subject: [Haskell-cafe] Re: Diagnosing stack overflow In-Reply-To: References: Message-ID: Justin Bailey wrote: > -- Determines if the length of the strings in the list is longer than the given > -- count. If not, amount the list falls short is returned. Otherwise, > -- -1 indicates the prefix list is at least that long. If the count is zero and > -- the list is empty or just null strings, -1 is also returned. > > prefixesAtLeast :: Int -> [S.ByteString] -> Int While that doesn't help your stack overflow problem, it's not very haskellish to return magic numbers. A Maybe type is more appropriate here. > prefixesAtLeast !0 !ss > | null ss = 0 > | all S.null ss = 0 > | otherwise = -1 > prefixesAtLeast !n !ss = prefixesAtLeast' n ss > where > prefixesAtLeast' !n ss > | n < 0 = -1 > | null ss = n > | otherwise = > let (!s : (!rest)) = ss > in > prefixesAtLeast' (n - (S.length s)) rest Extracting the head and tail of ss with a let statement could lead to a huge unevaluated expression like rest = tail (tail (tail (...))) but the null test are likely to force it. Also note that the case n = 0 is quite rare. In any case, I'd write the function as lengthExcess :: Int -> [S.ByteString] -> Maybe Int lengthExcess n ss | n <= 0 = Nothing | otherwise = case ss of [] -> Just n (s:ss) -> lengthExcess (n - S.length s) ss Note the that the function name is chosen to mnemonically match the result type Maybe Int, i.e. "the excess is Just 5 characters" or "the excess is Nothing". Regards, apfelmus From lennart at augustsson.net Fri Aug 17 04:33:26 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Fri Aug 17 04:24:55 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: <12195537.post@talk.nabble.com> References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> <12195537.post@talk.nabble.com> Message-ID: It's very hard to tell if it's worth it or not. Concatenating constant strings will turn the string into WHNF, which might enable some other transformation. By having lots of little transformations that on their own look worthless you can make big improvements. I'd like to see as much static evaluation as is practically possible. And as a previous poster showed, ghc does concatenate strings. On 8/17/07, Kim-Ee Yeoh wrote: > > > > Lennart Augustsson wrote: > > > > On 8/16/07, Kim-Ee Yeoh wrote: > >> 'Course not. The (++) function like all Haskell functions is only a > >> /promise/ to do its job. What does "assembling at compile time" > >> mean here: > >> > >> s = "I will not write infinite loops " ++ s > > > > But if the strings are all constant it's perfectly feasible to > concatenate > > them at compile time. > > > > It's feasible and I might add that it isn't worth it. Not for just > concatenation. How much static evaluation do you want to see > in Haskell? > > -- > View this message in context: > http://www.nabble.com/Hints-for-Euler-Problem-11-tf4114963.html#a12195537 > Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. > > _______________________________________________ > 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/haskell-cafe/attachments/20070817/b49d8d67/attachment.htm From a.biurvOir4 at asuhan.com Fri Aug 17 04:38:49 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Fri Aug 17 04:30:18 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: <1187336801.6553.125.camel@nmd9999> References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> <1187336801.6553.125.camel@nmd9999> Message-ID: <12196104.post@talk.nabble.com> The compiler dumps are illuminating, thank you. I'm afraid I don't always compile under -O. In fact I never debug with -O. I see now what I'm missing. (Pain, grief, despair.) Ketil Malde wrote: > > On Thu, 2007-08-16 at 12:50 -0700, Kim-Ee Yeoh wrote: >> Aaron Denney wrote: >> > The compiler should be able to >> > assemble it all at compile time, right? >> >> 'Course not. The (++) function like all Haskell functions is only a >> /promise/ to do its job. What does "assembling at compile time" >> mean here: >> >> s = "I will not write infinite loops " ++ s > > % cat C.hs > > module Test where > > x = "Foo" ++ "Bar" > y = "Zot" ++ y > > % ghc -ddump-simpl C.hs > > ==================== Tidy Core ==================== > Test.x :: [GHC.Base.Char] > [GlobalId] > [] > Test.x = > GHC.Base.++ > @ GHC.Base.Char (GHC.Base.unpackCString# "Foo") > (GHC.Base.unpackCString# "Bar") > > Rec { > Test.y :: [GHC.Base.Char] > [GlobalId] > [] > Test.y = GHC.Base.++ @ GHC.Base.Char (GHC.Base.unpackCString# "Zot") > Test.y > end Rec } > > If I interpret it correctly, the compiler does approximately nothing - > reasonably enough, since we didn't ask for optimization. With -O: > > % ghc -ddump-simpl C.hs -O > > ==================== Tidy Core ==================== > Rec { > Test.y :: [GHC.Base.Char] > [GlobalId] > [Str: DmdType] > Test.y = GHC.Base.unpackAppendCString# "Zot" Test.y > end Rec } > > Test.x :: [GHC.Base.Char] > [GlobalId] > [Str: DmdType] > Test.x = GHC.Base.unpackCString# "FooBar" > > y gets turned into an unpackAppendCString#, which I can only presume is > a sensible way to represent a cyclic list, while x gets concatenated > compile-time. > -- View this message in context: http://www.nabble.com/Hints-for-Euler-Problem-11-tf4114963.html#a12196104 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From jon.fairbairn at cl.cam.ac.uk Fri Aug 17 04:57:41 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Fri Aug 17 04:49:18 2007 Subject: [Haskell-cafe] Re: Hints for Euler Problem 11 References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> Message-ID: Kim-Ee Yeoh writes: > Aaron Denney wrote: > > I find the first far more readable. The compiler should be able to > > assemble it all at compile time, right? > > > > 'Course not. The (++) function like all Haskell functions is only a > /promise/ to do its job. I find this comment rather strange. One of the beauties of a pure language (especially a lazy one) is that there is no requirement for evaluation to take place at at any particular time as long as it's done before it's needed. So the compile-time/run-time dichotomy is only relevant when a value depends on data only available at run-time. Given that "foo "++"bar" can be evaluated at compile time and there are advantages and no disadvantages, it should be evaluated at compile time. In general, I don't think we should clutter the language with syntax for things for which there has to be a more general mechanism; including string breaks in the language was a mistake. Compare "thing1\n\ \thing2\n\ \thing3\n"++ otherThing++ "penultimate thing\n\ \last thing\n" with "thing1\n"++ "thing2\n"++ "thing3\n"++ otherThing++ "penultimate thing\n"++ "last thing\n" What /is/ the advantage of the former? -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From jon.fairbairn at cl.cam.ac.uk Fri Aug 17 05:11:05 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Fri Aug 17 05:02:50 2007 Subject: [Haskell-cafe] Compile-time v run-time References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> Message-ID: I wrote: > the compile-time/run-time dichotomy is only relevant when a > value depends on data only available at run-time. Something I've wanted to experiment with for a long time and never got round to is writing CAFs back to the load module at the end of a run (if they're small enough or took a long time to evaluate). Has anyone tried this? (It would have a jolly entertaining effect on benchmark pages!). The logical extension of this would be that compiling a programme did the typechecking and then just wrote the binary equivalent of 'evaluate $ code-generate "...lambda expressions from programme text..."' into the load-module. If you never run the programme, this would be quicker. If you only run the programme once, it would take about the same time, and running it several times would be quicker -- very much so if it didn't depend on any run-time data. -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From a.biurvOir4 at asuhan.com Fri Aug 17 05:25:11 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Fri Aug 17 05:16:40 2007 Subject: [Haskell-cafe] Re: Bathroom reading In-Reply-To: References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> <200708141031.51497.sjanssen@cse.unl.edu> Message-ID: <12196642.post@talk.nabble.com> ok-4 wrote: > > Someone mentioned the "Blow your mind" page. > One example there really caught my attention. > "1234567" => ("1357","246") > foldr (\a ~(x,y) -> (a:y,x)) ([],[]) > > I've known about lazy match since an early version of the Haskell > report, but have never actually used it. Last night, looking at > that example, the lights went on and I finally grokked why it's > there and understood when/why I might use it myself. > Don't you want an infinite list to illustrate the necessity of laziness? -- View this message in context: http://www.nabble.com/Bathroom-reading-tf4267956.html#a12196642 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From leaveye.guo at gmail.com Fri Aug 17 05:53:17 2007 From: leaveye.guo at gmail.com (L.Guo) Date: Fri Aug 17 05:44:47 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 References: <46A02E6E.1040904@mindspring.com> Message-ID: <200708171753149086462@gmail.com> Hi. My plan is just add some *unusable* data to make diagonal grid normally. Here this is. p011_input = input ++ (transpose input) ++ diagInput ++ diagInputT where diagInput = p011_toDiag input diagInputT = p011_toDiag . (map reverse) $ input input = [ [08,02,22,97,38,15,00,40,00,75,04,05,07,78,52,12,50,77,91,08], [49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,04,56,62,00], ... , [01,70,54,71,83,51,54,69,16,92,33,48,61,43,52,01,89,19,67,48] ] p011_toDiag = (map remove) . transpose . (map append) . addIndex where addIndex = zip [0..] append (n,y) = replicate n (-1) ++ y ++ replicate (19-n) (-1) remove = filter (-1/=) p011_toGroups x = case x of (a:b:c:d:xs) -> [a,b,c,d] : p011_toGroups (b:c:d:xs) _ -> [] p011_solve = putStrLn . show $ (foldl1 max) . (map product) . concat . (map p011_toGroups) $ p011_input ------------------ L.Guo 2007-08-17 ------------------------------------------------------------- From: Ronald Guida At: 2007-07-20 11:39:50 Subject: [Haskell-cafe] Hints for Euler Problem 11 To handle the diagonals, my plan is to try to extract each diagonal as a list of elements and put all the diagonals into a list; then I can use maxHorizontal. I came up with this function to try to extract the main diagonal. > getDiag :: [[a]] -> [a] > getDiag = map (head . head) . iterate (tail . map tail) The problem is, this function doesn't work unless I have an infinite grid. From a.biurvOir4 at asuhan.com Fri Aug 17 06:20:37 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Fri Aug 17 06:12:05 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> <12195537.post@talk.nabble.com> Message-ID: <12197224.post@talk.nabble.com> Lennart Augustsson wrote: > > On 8/17/07, Kim-Ee Yeoh wrote: >> How much static evaluation do you want to see >> in Haskell? > > I'd like to see as much static evaluation as is practically possible. > Yes but not in (the language formally defined as) Haskell. Not even in {your favorite Haskell compiler/interpreter} without -O. With -O by all means let her rip. Incidentally, GHC's type checker is Turing complete. You already have as much static evaluation as is practically possible. You already knew that. Lennart Augustsson wrote: > > And as a previous poster showed, ghc does concatenate strings. > And Haskell (as in the current language definition) does not. I was talking about Haskell. Having said that, I'll concede there may be room for more than one language here. I want syntax transparently reflecting straightforward if slowpoke operational semantics. You want fast, tight programs. I want fast, tight programs too, but not by giving up the former. -- View this message in context: http://www.nabble.com/Hints-for-Euler-Problem-11-tf4114963.html#a12197224 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From a.biurvOir4 at asuhan.com Fri Aug 17 06:59:35 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Fri Aug 17 06:51:04 2007 Subject: [Haskell-cafe] Compile-time v run-time In-Reply-To: References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> Message-ID: <12197690.post@talk.nabble.com> If RAM was treated as an extension of non-volatile storage instead of the other way round, we'd already be there. Put another way, would "suspending" program to disk achieve the same results? Jon Fairbairn wrote: > > Something I've wanted to experiment with for a long time and > never got round to is writing CAFs back to the load module > at the end of a run (if they're small enough or took a long > time to evaluate). Has anyone tried this? (It would have a > jolly entertaining effect on benchmark pages!). > > The logical extension of this would be that compiling a > programme did the typechecking and then just wrote the > binary equivalent of 'evaluate $ code-generate "...lambda > expressions from programme text..."' into the load-module. > If you never run the programme, this would be quicker. If > you only run the programme once, it would take about the > same time, and running it several times would be quicker -- > very much so if it didn't depend on any run-time data. > -- View this message in context: http://www.nabble.com/Hints-for-Euler-Problem-11-tf4114963.html#a12197690 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From iand675 at gmail.com Fri Aug 17 07:50:02 2007 From: iand675 at gmail.com (Ian Duncan) Date: Fri Aug 17 07:42:22 2007 Subject: [Haskell-cafe] So far, so good! Until... (Haskell 98 Report questions) Message-ID: ... I hit Chapter 3 and started reading about expressions. *If you are able to answer any of these questions, please send me an email. I am very lost and confused in this section, so even one answered question may help greatly.* I actually decided to sit down and figure out the Haskell 98 Report today. Everything was going well until I began Chapter 3. Here's the section that has me baffled: "In the syntax that follows, there are some families of nonterminals indexed by precedence levels (written as superscript). Similarly, the nonterminals op, varop, and conop may have a double index: a letter l, r, or n for left-, right- or non-associativity and a precedence level. A precedence-level variable i ranges from 0 to 9; an associativity variable, a, varies over {l,r,n}. For example, aexp -> ( exp^(i+1) qop^(a,i) ) actually stands for 30 productions, with 10 substitutions for i and 3 for a." *note that the "^" was used to indicate superscript. So here's my list of questions so far: 1. What are nonterminals? 2. What are productions and substitutions? I tried the dictionary and wikipedia, but neither were very helpful in defining those terms. Next, it says: exp -> exp^0 :: [context=>] type (expression type signature) | exp^0 exp^i -> exp^(i+1) [qop^(n,i) exp^(i+1)] | lexp^i | rexp^i ... From there it continues with more syntax stuff, but I'll stop there for the sake of not typing too much. So here are some questions about this section: 1. What the heck is going on? 2. How is an expression with a precedence of i considered to be an expression of i+1? 3. Within the ... section it mentions lexp and rexp. Do those stand for left-associative expressions and right-associative expressions respectively? I understand the concept of fixity when I see it mentioned in code, but I truly have no idea what 3.0 is talking about. Can anyone shed some light on any of this? I'm still in high school, so if anyone could please explain it to me in layman's terms primarily, or provide some resources explaining more complex terms, It would be greatly appreciated. Thanks a bunch! Ian Duncan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/11125d9b/attachment.htm From A.M.Gimblett at swansea.ac.uk Fri Aug 17 08:05:49 2007 From: A.M.Gimblett at swansea.ac.uk (Andy Gimblett) Date: Fri Aug 17 07:57:18 2007 Subject: [Haskell-cafe] So far, so good! Until... (Haskell 98 Report questions) In-Reply-To: References: Message-ID: <20070817120549.GD10422@cspcag2.swan.ac.uk> On Fri, Aug 17, 2007 at 04:50:02AM -0700, Ian Duncan wrote: > > So here's my list of questions so far: > 1. What are nonterminals? > 2. What are productions and substitutions? > [snip] Sounds to me like you want a book on language design, grammars, parsing, etc. :-) There are many good ones out there, but a quite nice, free, and (as it happens, though it's irrelevant for this question) Haskellish example is "Grammars and Parsing" by Jeuring & Swierstra (PDF, 1.2MB): http://www.cs.uu.nl/docs/vakken/gont/diktaat.pdf (Ignore the Dutch foreword, the rest is in English). Chapter 2 answers the questions asked above, with copious examples and exercises. Hope this helps, -Andy -- Andy Gimblett Computer Science Department University of Wales Swansea http://www.cs.swan.ac.uk/~csandy/ From cconway at cs.nyu.edu Fri Aug 17 08:08:53 2007 From: cconway at cs.nyu.edu (Christopher L Conway) Date: Fri Aug 17 08:00:22 2007 Subject: [Haskell-cafe] So far, so good! Until... (Haskell 98 Report questions) In-Reply-To: References: Message-ID: <4a051d930708170508l51af5ffct52537d3ad412f089@mail.gmail.com> Ian, This is all programming language parsing jargon. If the Wikipedia doesn't help (try http://en.wikipedia.org/wiki/Formal_grammar), I recommend the first few chapters of Aho, Sethi, & Ullman's "Compilers: Principles, Techniques, and Tools" aka "the dragon book", or any good book on compilers, e.g., Andrew Appel's "Modern Compiler Implementation". Chris On 8/17/07, Ian Duncan wrote: > > ... I hit Chapter 3 and started reading about expressions. > > *If you are able to answer any of these questions, please send me an email. > I am very lost and confused in this section, so even one answered question > may help greatly.* > > I actually decided to sit down and figure out the Haskell 98 Report today. > Everything was going well until I began Chapter 3. Here's the section that > has me baffled: > "In the syntax that follows, there are some families of nonterminals > indexed by precedence levels (written as superscript). Similarly, the > nonterminals op, varop, and conop may have a double index: a letter l, r, or > n for left-, right- or non-associativity and a precedence level. A > precedence-level variable i ranges from 0 to 9; an associativity variable, > a, varies over {l,r,n}. For example, aexp -> ( exp^(i+1) qop^(a,i) ) > actually stands for 30 productions, with 10 substitutions for i and 3 for > a." *note that the "^" was used to indicate superscript. > > So here's my list of questions so far: > 1. What are nonterminals? > 2. What are productions and substitutions? > > I tried the dictionary and wikipedia, but neither were very helpful in > defining those terms. > > Next, it says: > exp -> exp^0 :: [context=>] type (expression type signature) > | exp^0 > exp^i -> exp^(i+1) [qop^(n,i) exp^(i+1)] > | lexp^i > | rexp^i > ... > From there it continues with more syntax stuff, but I'll stop there for the > sake of not typing too much. So here are some questions about this section: > 1. What the heck is going on? > 2. How is an expression with a precedence of i considered to be an > expression of i+1? > 3. Within the ... section it mentions lexp and rexp. Do those stand for > left-associative expressions and right-associative expressions respectively? > > I understand the concept of fixity when I see it mentioned in code, but I > truly have no idea what 3.0 is talking about. Can anyone shed some light on > any of this? I'm still in high school, so if anyone could please explain it > to me in layman's terms primarily, or provide some resources explaining more > complex terms, It would be greatly appreciated. > > Thanks a bunch! > Ian Duncan > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From rodrigo.bonifacio at uol.com.br Fri Aug 17 09:11:21 2007 From: rodrigo.bonifacio at uol.com.br (rodrigo.bonifacio) Date: Fri Aug 17 09:02:52 2007 Subject: [Haskell-cafe] Basic question.... Message-ID: Hi all. I want to create the following polymorphic type (EnvItem) that we can apply two functions (envKey and envValue). I tried the following: > type Key = String > data EnvItem a = EnvItem (Key, a) > envKey :: EnvItem (Key, a) -> String > envKey EnvItem (key, value) = key > envValue :: EnvValue(Key, a) -> a > envValue EnvItem (key, value) = value But this is resulting in the error: [Constructor "EnvItem" must have exactly 1 argument in pattern] I think this is a very basic problem, but I don't know what is wrong. Regards, Rodrigo. From allbery at ece.cmu.edu Fri Aug 17 09:15:00 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Fri Aug 17 09:06:31 2007 Subject: [Haskell-cafe] Basic question.... In-Reply-To: References: Message-ID: <0A3DD72D-8A89-4A8D-974A-355D2EE2AE35@ece.cmu.edu> On Aug 17, 2007, at 9:11 , rodrigo.bonifacio wrote: >> envKey :: EnvItem (Key, a) -> String >> envKey EnvItem (key, value) = key > >> envValue :: EnvValue(Key, a) -> a >> envValue EnvItem (key, value) = value > > But this is resulting in the error: [Constructor "EnvItem" must > have exactly 1 argument in pattern] You need to parenthesize the constructor. envValue (EnvItem (_,value)) = value (The _ indicates that you're not using that item, rather than giving it a name that won't be used.) Why do you need to do this? Because you can pass functions around, and a constructor is a function. But your type says you don't want a bare function there, so the compiler complains. -- 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 voigt at tcs.inf.tu-dresden.de Fri Aug 17 09:16:06 2007 From: voigt at tcs.inf.tu-dresden.de (Janis Voigtlaender) Date: Fri Aug 17 09:07:36 2007 Subject: [Haskell-cafe] Basic question.... Message-ID: ----- Urspr?ngliche Nachricht ----- Von: "rodrigo.bonifacio" Datum: Freitag, August 17, 2007 3:11 pm Betreff: [Haskell-cafe] Basic question.... > Hi all. > > I want to create the following polymorphic type (EnvItem) that we > can apply two functions (envKey and envValue). I tried the following: > > > type Key = String > > > data EnvItem a = EnvItem (Key, a) > > > envKey :: EnvItem (Key, a) -> String > > envKey EnvItem (key, value) = key > > > envValue :: EnvValue(Key, a) -> a > > envValue EnvItem (key, value) = value > > But this is resulting in the error: [Constructor "EnvItem" must > have exactly 1 argument in pattern] > > I think this is a very basic problem, but I don't know what is wrong. You are simply missing some brackets: > envKey :: EnvItem (Key, a) -> String > envKey (EnvItem (key, value)) = key > envValue :: EnvValue(Key, a) -> a > envValue (EnvItem (key, value)) = value Ciao, Janis. From afalloon at synopsys.com Fri Aug 17 09:17:16 2007 From: afalloon at synopsys.com (Al Falloon) Date: Fri Aug 17 09:09:04 2007 Subject: [Haskell-cafe] Re: I'm stuck in my thought experiment In-Reply-To: <46C4E9D5.5090503@optusnet.com.au> References: <46C4E9D5.5090503@optusnet.com.au> Message-ID: <46C59FDC.8060507@synopsys.com> Levi Stephen wrote: > Hi, > > Apologies for a long post that may not be totally clear. I was thinking > through > a problem and how the data might be represented in Haskell. I'm now > stuck and > frustrated. Now, I'm not even sure whether I'm on the right track (I might > still be thinking too OO). Suggestions/ideas would be much appreciated. > > I was imagining a drag and drop web page designer. There are a bunch of > Widgets (e.g., BlogWidget, TextWidget, MenuWidget, etc) that the user can > place on the page. > > Along with these are layout/container widgets (e.g., ColumnLayoutWidget) > that can contain > other widgets. > > I'm looking at a data structure that would allow this to be represented > in Haskell, > so I'm keeping in mind that these won't be written in code, but generated > on the fly somehow (e.g., from a database or file). Maybe I am misunderstanding your requirements, but it seems to me that the simplest solution would be best in this case: data Widget = BlogWidget [Article] | TextWidget String | MenuWiget Menu | Rows Spacing [Widget] | Columns Spacing [Widget] You can also add a type parameter if you want to be able to carry around extra metadata about pages, or you could even parameterize the Article and Menu types if you want to be able to extend them separately or if you want to ensure your layout algorithms don't depend on widget contents by keeping their type abstract. > So, my thoughts were along the lines of something like: > > class Widget a where > render :: a -> Html > > -- A page has a title and a Widget. > -- I know this isn't valid Haskell, but I'm not sure how to specify what I > -- want here. (existential types?) > data Page = Page String Widget > > data TextWidget = TextWidget String > instance Widget TextWidget .... > > -- An example layout widget > data ColumnLayoutWidget = ColumnLayoutWidget [Widget] > instance Widget ColumnLayoutWidget ... > etc... > > So, entire pages might be represented something like: > > Page "Main" (ColumnLayoutWidget [MenuWidget, TextWidget mainPageText]) > Page "About" (ColumnLayoutWidget [MenuWidget, TextWidget aboutPageText]) This code seems to indicate that you want to be able to extend the widget types without changing this source file. This is a good goal, but it may not be worth the extra complexity. Also, this looks a lot like the Composite pattern from OO. A rule of thumb that I use is: "if I would do this with inheritance in OO, I probably want a variant in FP". Since Composite depends on the inheritance of the composite object type, I would probably look to use a single data type with multiple constructors for the different compisites like the Widget type above. If I wanted to develop the widgets themselves separately from the layout, I would probably do something like this: class Widget a where render :: a -> Html bbox :: a -> Size type Layout = forall a. Widget a => Widget a | Rows Spacing [Layout] | Columns Spacing [Layout] | Grid Spacing [[Layout]] type Page = Page String Layout renderLayout :: Layout -> Html renderPage :: Page -> Html > Where I get stuck, is I want to extract layout information into a parent > page. > This would allow global changes such as adding a header image to the > above pages > to be done once only. By making the layout type separate from the widgets themselves, it allows you to examine the layout and do any transformations you want without having to know anything about the widgets. > So I want to be able to have something like: > > layout = Page "Main" (ColumnLayoutWidget [MenuWidget, ??? ]) > mainPage = ChildPage layout [TextWidget mainPageText] > aboutPage = ChildPage layout [TextWidget aboutPageText] > > So, each page is it's layout/parent page, with additional widgets > inserted/added. So you want some sort of wildcard element that can be substituted in later? Maybe I am misunderstanding your requirement, but if thats the behavior you want, you should check out the term-level evaluators for lambda calculus for inspiration on substitution, but I expect your requirement may be simpler than that. > > The issue becomes, given a parent page and the customized content for > the child page, > what is the best way to insert the customized content at the right point? > > Might a tree like structure be useful? But, how do you work out where in > the tree > child content gets added? Store a traversal with each sub tree of child > page content > that basically says 'insert here'? This is probably a good use for a zipper (a kind of functional iterator). http://en.wikibooks.org/wiki/Haskell/Zippers that way you can pass around a value that means "right here", and its clear where the substitution will happen. Another good zipper war story is from xmonad: http://cgi.cse.unsw.edu.au/~dons/blog/2007/05/17 > It might be simple to have a PlaceHolderWidget. Then insertions of the > child page > content happens at each of those widgets. > This just gets trickier if I start considering multiple extension points > for child > pages and what happens when the layout/parent page changes. This is why I'm > thinking I may be going along a bad path here. Exactly. With multiple substitutions you get into issues of naming, so thats why looking at lambda calculus evaluators would be the right inspiration, but I think it may be more complicated than you need. The zipper approach might be easier. From afalloon at synopsys.COM Fri Aug 17 09:17:16 2007 From: afalloon at synopsys.COM (Al Falloon) Date: Fri Aug 17 09:09:12 2007 Subject: [Haskell-cafe] Re: I'm stuck in my thought experiment In-Reply-To: <46C4E9D5.5090503@optusnet.com.au> References: <46C4E9D5.5090503@optusnet.com.au> Message-ID: <46C59FDC.8060507@synopsys.com> Levi Stephen wrote: > Hi, > > Apologies for a long post that may not be totally clear. I was thinking > through > a problem and how the data might be represented in Haskell. I'm now > stuck and > frustrated. Now, I'm not even sure whether I'm on the right track (I might > still be thinking too OO). Suggestions/ideas would be much appreciated. > > I was imagining a drag and drop web page designer. There are a bunch of > Widgets (e.g., BlogWidget, TextWidget, MenuWidget, etc) that the user can > place on the page. > > Along with these are layout/container widgets (e.g., ColumnLayoutWidget) > that can contain > other widgets. > > I'm looking at a data structure that would allow this to be represented > in Haskell, > so I'm keeping in mind that these won't be written in code, but generated > on the fly somehow (e.g., from a database or file). Maybe I am misunderstanding your requirements, but it seems to me that the simplest solution would be best in this case: data Widget = BlogWidget [Article] | TextWidget String | MenuWiget Menu | Rows Spacing [Widget] | Columns Spacing [Widget] You can also add a type parameter if you want to be able to carry around extra metadata about pages, or you could even parameterize the Article and Menu types if you want to be able to extend them separately or if you want to ensure your layout algorithms don't depend on widget contents by keeping their type abstract. > So, my thoughts were along the lines of something like: > > class Widget a where > render :: a -> Html > > -- A page has a title and a Widget. > -- I know this isn't valid Haskell, but I'm not sure how to specify what I > -- want here. (existential types?) > data Page = Page String Widget > > data TextWidget = TextWidget String > instance Widget TextWidget .... > > -- An example layout widget > data ColumnLayoutWidget = ColumnLayoutWidget [Widget] > instance Widget ColumnLayoutWidget ... > etc... > > So, entire pages might be represented something like: > > Page "Main" (ColumnLayoutWidget [MenuWidget, TextWidget mainPageText]) > Page "About" (ColumnLayoutWidget [MenuWidget, TextWidget aboutPageText]) This code seems to indicate that you want to be able to extend the widget types without changing this source file. This is a good goal, but it may not be worth the extra complexity. Also, this looks a lot like the Composite pattern from OO. A rule of thumb that I use is: "if I would do this with inheritance in OO, I probably want a variant in FP". Since Composite depends on the inheritance of the composite object type, I would probably look to use a single data type with multiple constructors for the different compisites like the Widget type above. If I wanted to develop the widgets themselves separately from the layout, I would probably do something like this: class Widget a where render :: a -> Html bbox :: a -> Size type Layout = forall a. Widget a => Widget a | Rows Spacing [Layout] | Columns Spacing [Layout] | Grid Spacing [[Layout]] type Page = Page String Layout renderLayout :: Layout -> Html renderPage :: Page -> Html > Where I get stuck, is I want to extract layout information into a parent > page. > This would allow global changes such as adding a header image to the > above pages > to be done once only. By making the layout type separate from the widgets themselves, it allows you to examine the layout and do any transformations you want without having to know anything about the widgets. > So I want to be able to have something like: > > layout = Page "Main" (ColumnLayoutWidget [MenuWidget, ??? ]) > mainPage = ChildPage layout [TextWidget mainPageText] > aboutPage = ChildPage layout [TextWidget aboutPageText] > > So, each page is it's layout/parent page, with additional widgets > inserted/added. So you want some sort of wildcard element that can be substituted in later? Maybe I am misunderstanding your requirement, but if thats the behavior you want, you should check out the term-level evaluators for lambda calculus for inspiration on substitution, but I expect your requirement may be simpler than that. > > The issue becomes, given a parent page and the customized content for > the child page, > what is the best way to insert the customized content at the right point? > > Might a tree like structure be useful? But, how do you work out where in > the tree > child content gets added? Store a traversal with each sub tree of child > page content > that basically says 'insert here'? This is probably a good use for a zipper (a kind of functional iterator). http://en.wikibooks.org/wiki/Haskell/Zippers that way you can pass around a value that means "right here", and its clear where the substitution will happen. Another good zipper war story is from xmonad: http://cgi.cse.unsw.edu.au/~dons/blog/2007/05/17 > It might be simple to have a PlaceHolderWidget. Then insertions of the > child page > content happens at each of those widgets. > This just gets trickier if I start considering multiple extension points > for child > pages and what happens when the layout/parent page changes. This is why I'm > thinking I may be going along a bad path here. Exactly. With multiple substitutions you get into issues of naming, so thats why looking at lambda calculus evaluators would be the right inspiration, but I think it may be more complicated than you need. The zipper approach might be easier. From chaddai.fouche at gmail.com Fri Aug 17 09:19:07 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Fri Aug 17 09:10:37 2007 Subject: [Haskell-cafe] Basic question.... In-Reply-To: References: Message-ID: Not only does you lack some parens around your patterns, your function types are wrong : type Key = String data EnvItem a = EnvItem (Key, a) envKey :: EnvItem a -> String envKey (EnvItem (key, value)) = key envValue :: EnvItem a -> a envValue (EnvItem (key, value)) = value -- Jeda? From jon.fairbairn at cl.cam.ac.uk Fri Aug 17 09:39:47 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Fri Aug 17 09:31:35 2007 Subject: [Haskell-cafe] Re: Compile-time v run-time References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> <12197690.post@talk.nabble.com> Message-ID: Kim-Ee Yeoh writes: > Jon Fairbairn wrote: > > Something I've wanted to experiment with for a long time and > > never got round to is writing CAFs back to the load module > > at the end of a run (if they're small enough or took a long > > time to evaluate). > If RAM was treated as an extension of non-volatile > storage instead of the other way round, we'd already > be there. Not exactly > Put another way, would "suspending" program to > disk achieve the same results? No, because the state in RAM includes not only CAFs but data that depends on the history of the present run. If you only write CAFs back, running the modified module gives the same effect as running the unmodified version. Resuming a suspended programme has the effect of continuing from where you left off. -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From jon.fairbairn at cl.cam.ac.uk Fri Aug 17 09:44:28 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Fri Aug 17 09:36:30 2007 Subject: [Haskell-cafe] Re: Basic question.... References: Message-ID: "Chadda? Fouch?" writes: > Not only does you lack some parens around your patterns, your function > types are wrong : > > type Key = String > > data EnvItem a = EnvItem (Key, a) > > envKey :: EnvItem a -> String > envKey (EnvItem (key, value)) = key > > envValue :: EnvItem a -> a > envValue (EnvItem (key, value)) = value Why not > data EnvItem a = EnvItem {key:: Key, value:: a} ? -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From chaddai.fouche at gmail.com Fri Aug 17 09:51:02 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Fri Aug 17 09:42:30 2007 Subject: [Haskell-cafe] Re: Basic question.... In-Reply-To: References: Message-ID: 17 Aug 2007 14:44:28 +0100, Jon Fairbairn : > Why not > > > data EnvItem a = EnvItem {key:: Key, value:: a} It's the real solution, but I feel it was worthwhile to underscore the other mistakes (often encountered by the newbies) in types and parameters. -- Jeda? From kelanslists at gmail.com Fri Aug 17 10:04:50 2007 From: kelanslists at gmail.com (Kurt Hutchinson) Date: Fri Aug 17 09:56:19 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: <641FEAB9-7063-4D81-9426-630E08439B6D@cs.otago.ac.nz> References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> <641FEAB9-7063-4D81-9426-630E08439B6D@cs.otago.ac.nz> Message-ID: On 8/16/07, ok wrote: > We're going to have to keep track of whether we have a last element > or not. The obvious candidate for this is Maybe x. Initially there > is no element, Nothing. > f x Empty = Just x > f x (Just y) = Just y > This picks up a new value (x) when there wasn't one (Nothing) and > keeps the old last element (Just y) when there was one (Just y). > But this gives us a Maybe x, when we want an x, so we'll have to finish > off with a fromJust. > > last = fromJust . foldr f Nothing > where f _ r@(Just _) = r > f x Nothing = Just x I had this idea as well, but the questioner said the chapter with the exercise preceded any use of Maybe, although I admit my suggestion of using foldr to compose a processing function is more complicated for a beginner. Here's a way to use the above idea without Maybe: myLast = head . foldr f [] where f x [] = [x] f _ [x] = [x] From thomas.hartman at db.com Fri Aug 17 10:52:43 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 17 10:44:18 2007 Subject: [Haskell-cafe] Looking at program execution In-Reply-To: Message-ID: hartthoma@linuxpt:~>cat test.hs import Debug.Trace foo = foldl (\first second -> (trace ( "first: " ++ ( show first) ) first) + (trace ( "second: " ++ (show second) ) second) ) 0 [1,2,3] bar = foldl (+) traceIt x = trace ("\nTraceIt:\n"++show x++"\n") x hartthoma@linuxpt:~>ghc -e foo test.hs first: 0 second: 1 first: 1 second: 2 first: 3 second: 3 6 hartthoma@linuxpt:~> hope this helps. Ian Duncan Sent by: haskell-cafe-bounces@haskell.org 08/16/2007 08:20 PM To haskell-cafe@haskell.org cc Subject [Haskell-cafe] Looking at program execution Is there any way to view the steps that a haskell program goes through step by step? I'm thinking something similar to what I've seen in things I've been reading. For example: foldl (+) 0 [1..10] => (0+1) => ((0+1)+2) => (((0+1)+2)+3) => etc. I've seen these sorts of line-by-line execution steps, but I was curious if there was any way to simply type in a function and its arguments and have ghci or hugs or something print out this sort of visual representation of what's going on. Anyone know of something like this? _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/57c2c7e6/attachment-0001.htm From haskell at list.mightyreason.com Fri Aug 17 10:55:46 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Fri Aug 17 10:48:27 2007 Subject: [Haskell-cafe] Very fast searching of byte strings Message-ID: Post the the library mailing list at [1] is the Boyer-Moore algorithm implemented for strict and lazy bytestrings (and combinations thereof). It finds all the overlapping instances of the pattern inside the target. I have performance tuned it. But the performance for searching a strict bytestring is better then for a lazy bytestring (even if they only had a single strict chunk), which almost certainly means I was not clever enough to get GHC to produce the optimal code. There is much more description in the module's haddock header. Hopefully Don or other ByteString experts/maintainers can tweak this even further. Also at [1] is a Knuth-Morris-Pratt module which find non-overlapping instances and is slightly slower on my benchmarks. Happy Searching, Chris Kuklewicz [1] http://www.haskell.org/pipermail/libraries/2007-August/007987.html From thomas.hartman at db.com Fri Aug 17 11:00:23 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 17 10:51:57 2007 Subject: [Haskell-cafe] Looking at program execution In-Reply-To: Message-ID: or actually just... hartthoma@linuxpt:~>cat test.hs import Debug.Trace foo = foldl (\first second -> trace ( ( show first) ++ ("+") ++ (show second ) ) ( first + second) ) 0 [1,2,3] hartthoma@linuxpt:~>ghc -e foo test.hs 0+1 1+2 3+3 6 hartthoma@linuxpt:~> is probably better Thomas Hartman Sent by: haskell-cafe-bounces@haskell.org 08/17/2007 10:52 AM To haskell-cafe@haskell.org, iand675@gmail.com cc Subject Re: [Haskell-cafe] Looking at program execution hartthoma@linuxpt:~>cat test.hs import Debug.Trace foo = foldl (\first second -> (trace ( "first: " ++ ( show first) ) first) + (trace ( "second: " ++ (show second) ) second) ) 0 [1,2,3] bar = foldl (+) traceIt x = trace ("\nTraceIt:\n"++show x++"\n") x hartthoma@linuxpt:~>ghc -e foo test.hs first: 0 second: 1 first: 1 second: 2 first: 3 second: 3 6 hartthoma@linuxpt:~> hope this helps. Ian Duncan Sent by: haskell-cafe-bounces@haskell.org 08/16/2007 08:20 PM To haskell-cafe@haskell.org cc Subject [Haskell-cafe] Looking at program execution Is there any way to view the steps that a haskell program goes through step by step? I'm thinking something similar to what I've seen in things I've been reading. For example: foldl (+) 0 [1..10] => (0+1) => ((0+1)+2) => (((0+1)+2)+3) => etc. I've seen these sorts of line-by-line execution steps, but I was curious if there was any way to simply type in a function and its arguments and have ghci or hugs or something print out this sort of visual representation of what's going on. Anyone know of something like this? _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/1c014baf/attachment.htm From byorgey at gmail.com Fri Aug 17 11:14:15 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Fri Aug 17 11:05:43 2007 Subject: [Haskell-cafe] Basic question.... In-Reply-To: References: Message-ID: <22fcbd520708170814h2a7e8a0arc9f38ffe766215db@mail.gmail.com> On 8/17/07, rodrigo.bonifacio wrote: > > Hi all. > > I want to create the following polymorphic type (EnvItem) that we can > apply two functions (envKey and envValue). I tried the following: > > > type Key = String > > > data EnvItem a = EnvItem (Key, a) > > > envKey :: EnvItem (Key, a) -> String > > envKey EnvItem (key, value) = key > > > envValue :: EnvValue(Key, a) -> a > > envValue EnvItem (key, value) = value > > But this is resulting in the error: [Constructor "EnvItem" must have > exactly 1 argument in pattern] > > I think this is a very basic problem, but I don't know what is wrong. > > Regards, > > Rodrigo. By the way, I would suggest giving the data type and constructor different names: data EnvItem a = EI (Key, a) You do often see people use the same name for both, but that can be confusing since they are really two different things. The envKey function (for example) would now be written like this: envKey :: EnvItem a -> Key envKey (EI (key, _)) = key The difference between the parameter type (EnvItem a) and a pattern to match the shape of such a value (EI (key, _)) is now much clearer: whatever is on the left side of the data declaration is the type, and goes in type signatures; whatever is on the right side describes the shape of values of that type, and is used to construct or deconstruct (through pattern-matching) such values. This way it is much harder to make mistakes like (for example) putting EnvItem (Key, a) in the type signature instead of EnvItem a. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/ddc03646/attachment.htm From jgbailey at gmail.com Fri Aug 17 11:17:56 2007 From: jgbailey at gmail.com (Justin Bailey) Date: Fri Aug 17 11:09:24 2007 Subject: [Haskell-cafe] Diagnosing stack overflow In-Reply-To: <1187308362.8691.1205805295@webmail.messagingengine.com> References: <1187308362.8691.1205805295@webmail.messagingengine.com> Message-ID: On 8/16/07, Matthew Brecknell wrote: > However, it's possible that your use of this function is forcing > evaluation of a deeply-nested thunk you've created somewhere else (as > print does in the foldl example). Thank you for the detailed and helpful reply. I was led to this function by the vanilla profiling, which showed that it had the highest percentage of allocations. Now I'm thinking I'll look at the functions up the call stack to see which might be building up the thunk. Would "retainer profiling" help me see what was building up this large thunk/closure? Justin From jgbailey at gmail.com Fri Aug 17 11:22:27 2007 From: jgbailey at gmail.com (Justin Bailey) Date: Fri Aug 17 11:13:54 2007 Subject: [Haskell-cafe] Re: Diagnosing stack overflow In-Reply-To: References: Message-ID: On 8/17/07, apfelmus wrote: > Extracting the head and tail of ss with a let statement could lead to > a huge unevaluated expression like > > rest = tail (tail (tail (...))) Even though they are probably forced, would breaking the head and tail apart via pattern-matching or a case statement avoid building up that unevaluated expression? Justin From apfelmus at quantentunnel.de Fri Aug 17 12:04:23 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Fri Aug 17 11:56:02 2007 Subject: [Haskell-cafe] Re: Diagnosing stack overflow In-Reply-To: References: Message-ID: Justin Bailey wrote: > apfelmus wrote: > >> Extracting the head and tail of ss with a let statement could lead to >> a huge unevaluated expression like >> >> rest = tail (tail (tail (...))) > > Even though they are probably forced, would breaking the head and tail > apart via pattern-matching or a case statement avoid building up that > unevaluated expression? Yes, absolutely, since pattern matching has to force the scrutinee in order to choose the matching case. In contrast, a let statement let (x:xs) = expr in ... simply assumes that expr is of the form (x:xs) but does not force it and check whether that's really the case. Of course, this may turn out as pattern match later on as soon as x is demanded but expr was initially the empty list. In your case, the test null ss forces ss and checks whether the let-pattern is ok. So, you basically end up doing what a case expression would do. In other words, the situation is more "they are most likely forced" than "they are probably forced" and it's just a matter of convenience to choose one over the other. But there are certain situations where you can check/prove differently that the let pattern never fails and where such a lazy pattern is wanted. Regards, apfelmus From bryan.burgers at gmail.com Fri Aug 17 13:24:01 2007 From: bryan.burgers at gmail.com (Bryan Burgers) Date: Fri Aug 17 13:15:29 2007 Subject: [Haskell-cafe] Basic question.... In-Reply-To: References: Message-ID: On 8/17/07, rodrigo.bonifacio wrote: > Hi all. > > I want to create the following polymorphic type (EnvItem) that we can apply two functions (envKey and envValue). I tried the following: > > > type Key = String > > > data EnvItem a = EnvItem (Key, a) > > > envKey :: EnvItem (Key, a) -> String > > envKey EnvItem (key, value) = key > > > envValue :: EnvValue(Key, a) -> a > > envValue EnvItem (key, value) = value > > But this is resulting in the error: [Constructor "EnvItem" must have exactly 1 argument in pattern] > > I think this is a very basic problem, but I don't know what is wrong. > > Regards, > > Rodrigo. In addition to what others have already said, I'd like to point out that you do not really need a tuple in your data item. > data EnvItem a = EI Key a > envKey :: EnvItem a -> Key > envKey (EI key _) = key > envValue :: EnvValue a -> a > envValue (EI _ value) = value Also, you made a distinction between 'Key' and 'String', which is good. But then in 'envKey', you used 'String' in the signature instead of 'Key'.That's a little confusing, and also should you ever want to change the representation of 'Key', you would then have to change the signature of envKey. Just my two cents, Bryan From thomas.hartman at db.com Fri Aug 17 14:40:33 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 17 14:32:08 2007 Subject: [Haskell-cafe] trouble building regex-base 0.91 on ghc 6.7 Message-ID: I'm trying to build the latest regex base, which is required for the other regex packages under ghc 6.7 It complains that it can't find Data.Sequence, because it's in a hidden module containers. I added containers to the cabal depends as can be seen in the grep below. And containers isn't hidden when I do ghc-pkg list. What gives? Still getting used to cabal... thomas. hartthoma@linuxpt:~/installs/regex-base-0.91>runghc Setup.hs build Preprocessing library regex-base-0.91... Building regex-base-0.91... Text/Regex/Base/RegexLike.hs:47:17: Could not find module `Data.Sequence': it is a member of package containers-0.1, which is hidden hartthoma@linuxpt:~/installs/regex-base-0.91>grep -i containers regex-base.cabal Build-Depends: base >= 2.0, mtl, containers hartthoma@linuxpt:~/installs/regex-base-0.91>ghc-pkg list /usr/local/lib/ghc-6.7.20070816/package.conf: Cabal-1.1.7, HUnit-1.1.1, QuickCheck-1.0.1, array-0.1, arrows-0.2.1, base-2.1, bytestring-0.1, cgi-3001.1.5, containers-0.1, directory-1.0, fgl-5.4.1, filepath-1.0, (ghc-6.7.20070816), haskell-src-1.0.1, haskell98-1.0, hpc-0.5, html-1.0.1, mtl-1.0.1, network-2.0.1, old-locale-1.0, old-time-1.0, packedstring-0.1, parallel-1.0, parsec-2.0, pretty-1.0, process-1.0, random-1.0, readline-1.0, regex-base-0.72, rts-1.0, stm-2.1, template-haskell-0.1, unix-2.0, xhtml-3000.0.2 --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/752186f7/attachment.htm From stefanor at cox.net Fri Aug 17 15:00:19 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 17 14:51:47 2007 Subject: [Haskell-cafe] trouble building regex-base 0.91 on ghc 6.7 In-Reply-To: References: Message-ID: <20070817190019.GB3189@localhost.localdomain> On Fri, Aug 17, 2007 at 02:40:33PM -0400, Thomas Hartman wrote: > I'm trying to build the latest regex base, which is required for the other > regex packages under ghc 6.7 > > It complains that it can't find Data.Sequence, because it's in a hidden > module containers. I added containers to the cabal depends as can be seen > in the grep below. > > And containers isn't hidden when I do ghc-pkg list. > > What gives? > > Still getting used to cabal... Did you re-run configure after changing the cabal file? Also, what ghc-pkg says has absolutely nothing to do with this; the options Cabal passes completely override the ghc-pkg exposure flags.I can hardly fault you for not knowing the answer to a Cabal FAQ, since Cabal doesn't actually have a FAQ list yet. You are running into the same problem as http://www.haskell.org/pipermail/haskell-cafe/2007-August/030276.html, and most of my explanation there applies here. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/3c812bfd/attachment.bin From andrewcoppin at btinternet.com Fri Aug 17 15:34:39 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 17 15:25:20 2007 Subject: [Haskell-cafe] Remember the future Message-ID: <46C5F84F.8020404@btinternet.com> I've seen comments in various places that monads allow you to "borrow things from the future". That sounds completely absurd to me... can anybody explain? From thomas.hartman at db.com Fri Aug 17 15:51:03 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 17 15:42:35 2007 Subject: [Haskell-cafe] trouble building regex-base 0.91 on ghc 6.7 In-Reply-To: <20070817190019.GB3189@localhost.localdomain> Message-ID: thanks stefan, I did remember that discussion (actually also an answer to a question I asked.) I got from that that previous help that I had to edit the cabal file. The problem here, as you say, is that I had not re-run runghc Setup.hs configure. thanks, thomas. "Stefan O'Rear" 08/17/2007 03:00 PM To Thomas Hartman/ext/dbcom@DBAmericas cc haskell-cafe Subject Re: [Haskell-cafe] trouble building regex-base 0.91 on ghc 6.7 On Fri, Aug 17, 2007 at 02:40:33PM -0400, Thomas Hartman wrote: > I'm trying to build the latest regex base, which is required for the other > regex packages under ghc 6.7 > > It complains that it can't find Data.Sequence, because it's in a hidden > module containers. I added containers to the cabal depends as can be seen > in the grep below. > > And containers isn't hidden when I do ghc-pkg list. > > What gives? > > Still getting used to cabal... Did you re-run configure after changing the cabal file? Also, what ghc-pkg says has absolutely nothing to do with this; the options Cabal passes completely override the ghc-pkg exposure flags.I can hardly fault you for not knowing the answer to a Cabal FAQ, since Cabal doesn't actually have a FAQ list yet. You are running into the same problem as http://www.haskell.org/pipermail/haskell-cafe/2007-August/030276.html, and most of my explanation there applies here. Stefan [attachment "signature.asc" deleted by Thomas Hartman/ext/dbcom] --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/bbf74b1c/attachment.htm From thomas.hartman at db.com Fri Aug 17 16:27:29 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 17 16:19:02 2007 Subject: [Haskell-cafe] trouble compiling "import GHC.Prim(MutableByteArray#, ....." (building regex-tdfa from darcs) -- what's that # sign doing? Message-ID: trying to compile regex-tdfa, I ran into another issue. (earlier I had a cabal problem but that's resolved.) there's a line that won't compile, neither for ghc 6.6.1 nor 6.7 import GHC.Prim(MutableByteArray#,RealWorld,Int#,sizeofMutableByteArray#,unsafeCoerce#) so the fresh darcs regex tdfa package won't build. This line (line 16 below) causes this error for ghc -e '' RunMutState.hs for both ghc 6.1 and 6.7 Much obliged for any help, Thomas. ********************************* hartthoma@linuxpt:~/installs/regex_darcs/regex-tdfa>runghc Setup.hs build Preprocessing library regex-tdfa-0.93... Building regex-tdfa-0.93... Text/Regex/TDFA/RunMutState.hs:16:32: parse error on input `#' hartthoma@linuxpt:~/installs/regex_darcs/regex-tdfa>head -n20 Text/Regex/TDFA/RunMutState.hs | cat -n 1 {-# LANGUAGE CPP #-} 2 module Text.Regex.TDFA.RunMutState(TagEngine(..),newTagEngine,newTagEngine2 3 ,newScratch,tagsToGroupsST 4 ,toInstructions,compareWith,resetScratch 5 ,SScratch(..),MScratch,WScratch) where 6 7 import Control.Monad(forM_,liftM,liftM2,liftM3,foldM) 8 --import Control.Monad.ST.Strict as S (ST) 9 --import qualified Control.Monad.ST.Lazy as L (ST) 10 import Control.Monad.State(MonadState(..),execState) 11 12 import Data.Array.Base(unsafeRead,unsafeWrite,STUArray(..)) 13 #ifdef __GLASGOW_HASKELL__ 14 import GHC.Arr(STArray(..)) 15 import GHC.ST(ST(..)) *** 16 import GHC.Prim(MutableByteArray#,RealWorld,Int#,sizeofMutableByteArray#,unsafeCoerce#) 17 #else 18 import Control.Monad(when) 19 import Control.Monad.ST(ST) 20 import Data.Array.ST(STArray) hartthoma@linuxpt:~/installs/regex_darcs/regex-tdfa> --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/97cda0bd/attachment.htm From mattcbro at earthlink.net Fri Aug 17 16:36:23 2007 From: mattcbro at earthlink.net (SevenThunders) Date: Fri Aug 17 16:27:50 2007 Subject: [Haskell-cafe] GHC linking problems In-Reply-To: <12155220.post@talk.nabble.com> References: <12155220.post@talk.nabble.com> Message-ID: <12206722.post@talk.nabble.com> Did I find a bug cabal? I have attempted to fix the problem Main.c:(.text+0x22): undefined reference to `__stginit_ZCMain' by compiling my Haskell library using the flag -no-hs-main. One would think that this would make sense if the library is to be used by an external C program. However I am using cabal to build the haskell library and I immediately run into a problem. My netsim.cabal file looks like Name: Netsim Version: 1.1 License: AllRightsReserved Exposed-modules: Matrix, Parsefile, PowCDF Build-Depends: base, regex-compat>=0.71, parsec>=2.0 Extensions: ForeignFunctionInterface Includes: matrixstack.h Install-includes: matrixstack.h, TunePerf.h Include-dirs: ../matrixstack, /usr/lib/ghc-6.6.1/include, . Extra-libraries: netsimc, matrixstack, lapack, ptcblas, atlas Extra-lib-dirs: /usr/local/atlas/lib, ., ./phymake,../matrixstack Ghc-options: -fglasgow-exts -O2 -no-hs-main My setup.hs file looks like: import Distribution.Simple main = defaultMainWithHooks defaultUserHooks When I build this using runhaskell Setup.hs build all the source files compile just fine, but then a screwy thing happens. Cabal attempts to build an executable called a.out. Moreover a.out has no main of course and it does not attempt to link to any of the libraries in the Extra-libraries field. This kills the cabal build. So trying to link a.out (which it shouldnt be doing) gives me the errors, Preprocessing library Netsim-1.1... Building Netsim-1.1... Linking a.out ... dist/build/Matrix.o: In function `Netsimzm1zi1_Matrix_zdwccall_info': ghc6835_0.hc:(.text+0x1ea9): undefined reference to `PmatC' dist/build/Matrix.o: In function `Netsimzm1zi1_Matrix_zdwccall1_info': ghc6835_0.hc:(.text+0x1f79): undefined reference to `Pmat' dist/build/Matrix.o: In function `Netsimzm1zi1_Matrix_zdwccall2_info': ... /usr/lib/ghc-6.6.1/libHSrts.a(Main.o): In function `main': Main.c:(.text+0x22): undefined reference to `__stginit_ZCMain' Main.c:(.text+0x43): undefined reference to `ZCMain_main_closure' If I eliminate the -no-hs-main flag in Ghc-options no attempt is made to creat a.out, which is as it should be and the library builds without complaint. This seems like a bug in cabal. -- View this message in context: http://www.nabble.com/GHC-linking-problems-tf4270650.html#a12206722 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From stefanor at cox.net Fri Aug 17 16:47:57 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 17 16:39:25 2007 Subject: [Haskell-cafe] trouble compiling "import GHC.Prim(MutableByteArray#, ....." (building regex-tdfa from darcs) -- what's that # sign doing? In-Reply-To: References: Message-ID: <20070817204757.GA3775@localhost.localdomain> On Fri, Aug 17, 2007 at 04:27:29PM -0400, Thomas Hartman wrote: > trying to compile regex-tdfa, I ran into another issue. (earlier I had a > cabal problem but that's resolved.) > > there's a line that won't compile, neither for ghc 6.6.1 nor 6.7 > > import > GHC.Prim(MutableByteArray#,RealWorld,Int#,sizeofMutableByteArray#,unsafeCoerce#) > > so the fresh darcs regex tdfa package won't build. > > This line (line 16 below) causes this error for > > ghc -e '' RunMutState.hs > > for both ghc 6.1 and 6.7 There are at least two things going on here. 1. GHC-specific unboxed identifiers have a # in the name. I think this is a relic from back when the only reasonable way to namespace was to modify your compiler to add extra identifier characters, and use them in all non-portable identifiers. In any case, you have to enable the -fglasgow-exts option (or -XMagicHash in recent 6.7) to allow imports of such identifiers. 2. Explicitly importing GHC.Prim has been discouraged for as long as I can remember, and GHC HQ has finally made good on the promise to make it impossible. Code which imports it has a bug already, which can be fixed by switching to GHC.Exts. (Why? GHC.Prim is wired into the compiler, while GHC.Exts is a normal Haskell module, so by using GHC.Exts you are insulated from questions of what is primitive and what is derived but still unportable. Yes, this does change.) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/7e20d7a3/attachment.bin From aspam at cox.net Fri Aug 17 10:32:27 2007 From: aspam at cox.net (Joe Buehler) Date: Fri Aug 17 17:31:40 2007 Subject: [Haskell-cafe] Re: Diagnosing stack overflow In-Reply-To: <1187308362.8691.1205805295@webmail.messagingengine.com> References: <1187308362.8691.1205805295@webmail.messagingengine.com> Message-ID: Matthew Brecknell wrote: > The key point of the example is that foldl itself doesn't need any of > the intermediate values of the accumulator, so these just build up into > a deeply-nested unevaluated thunk. When print finally demands an > integer, the run-time pushes a stack frame for each level of parentheses > it enters as it tries to evaluate the thunk. Too many parentheses leads > to a stack overflow. Of course, the solution to the example is to use What is the point in building this huge thunk if it can't be evaluated without a stack overflow? Could the runtime do partial evaluation to keep the thunk size down or would that cause semantic breakage? Joe Buehler From andrewcoppin at btinternet.com Fri Aug 17 17:50:51 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 17 17:41:32 2007 Subject: [Haskell-cafe] Remember the future In-Reply-To: <20070817233112.GA2785@localhost> References: <46C5F84F.8020404@btinternet.com> <20070817233112.GA2785@localhost> Message-ID: <46C6183B.609@btinternet.com> Gwern Branwen wrote: > On 0, Andrew Coppin scribbled: > >> I've seen comments in various places that monads allow you to "borrow >> things from the future". >> >> That sounds completely absurd to me... can anybody explain? >> > > Take a look at issue 6 of The Monad Reader; search for time travel. > Mmm... yes... I've read this before. It didn't make any sense then either. (The example is too big and complicated. It obscures the thing it's trying to illustrate...) From dpiponi at gmail.com Fri Aug 17 18:10:03 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Fri Aug 17 18:01:31 2007 Subject: [Haskell-cafe] Remember the future In-Reply-To: <46C5F84F.8020404@btinternet.com> References: <46C5F84F.8020404@btinternet.com> Message-ID: <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> On 8/17/07, Andrew Coppin wrote: > I've seen comments in various places that monads allow you to "borrow > things from the future". > > That sounds completely absurd to me... can anybody explain? Suppose you buy into the notion that monads sequence actions. Then consider the following code: > import Control.Monad.State > test = do > put $ x+1 > x <- return 1 > return undefined > go = execState test undefined execState runs a sequence of actions in the state monad, ignoring the returned value and simply giving you back the resulting state. So work through what this code does: It sets the value of the state to be 1+x. It then sets x to be 1. And then it returns undefined. We don't care about the return value, we just care about the state. And clearly the state is 2. But if you believe all that action sequencing stuff, we set the state using x before we actually set the value of x. So we're reading from the future. But you can breathe a sigh of relief because the above code doesn't compile and the laws of physics remain unharmed. Except...you can switch on ghc's special time travel features using the -fglasgow-exts flag. Use the time-travel compatible mdo instead of do and you'll find that this compiles and runs fine: > import Control.Monad.State > import Control.Monad.Fix > test = mdo > put $ x+1 > x <- return 1 > return undefined > go = execState test undefined -- Dan From dpiponi at gmail.com Fri Aug 17 18:43:16 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Fri Aug 17 18:34:43 2007 Subject: [Haskell-cafe] Remember the future In-Reply-To: <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> References: <46C5F84F.8020404@btinternet.com> <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> Message-ID: <625b74080708171543g3945b0cag3bf62ae610e8b016@mail.gmail.com> On 8/17/07, Dan Piponi wrote: > On 8/17/07, Andrew Coppin wrote: > > That sounds completely absurd to me... can anybody explain? > Except...you can switch on ghc's special time travel features... On reflection I decided my example isn't very convincing. For one thing, I've argued in another thread that monads aren't really about sequencing actions. But I concede that there is an exception: the IO monad. Because the IO monad has observable side effects you can actually see whether or not an action has taken place at a particular time, so it really does have to sequence actions. So now consider the following code: > import IO > import Control.Monad.Fix > test = mdo > z <- return $ x+y > print "Hello" > x <- readLn > y <- readLn > return z Evaluate test and you'll be prompted to enter a pair of numbers. You'll then be rewarded with their sum. But the "Hello" message is printed before the prompt for input so we know that's being executed first. And we can see clearly that the summation is performed before the "Hello" message. So clearly this program is computing its result before receiving the input. At this point your natural reaction should be to replace 'print "Hello"' with 'print z'... -- Dan From bos at serpentine.com Fri Aug 17 18:42:56 2007 From: bos at serpentine.com (Bryan O'Sullivan) Date: Fri Aug 17 18:37:48 2007 Subject: [Haskell-cafe] Re: Diagnosing stack overflow In-Reply-To: References: <1187308362.8691.1205805295@webmail.messagingengine.com> Message-ID: <46C62470.2060402@serpentine.com> Joe Buehler wrote: > What is the point in building this huge thunk if it can't be evaluated > without a stack overflow? It's not that there's a point to it, it's just the behaviour of foldl. Hence you shouldn't be using foldl. GHC's strictness analyser can sometimes save you from yourself if you're compiling with -O, but it's better to just avoid foldl and use foldr or Data.List.foldl' instead. The HsOpenSSL package[1] is good work, but the author doesn't respond to email(*). I've a bunch of darcs patches to add tests, DSA support and fast Integer <-> BIGNUM functions. Can I use my Hackage account to upload version 0.2 if someone else uploaded 0.1? It is reasonable? I'm guessing that this issue will start to occur more often now that we have Hackage. It's probably good to have some policy. Cheers, (*) It's been > 1 month, with emails from several different addresses. [1] http://hackage.haskell.org/cgi-bin/hackage-scripts/package/HsOpenSSL-0.1 -- Adam Langley agl@imperialviolet.org http://www.imperialviolet.org From chaddai.fouche at gmail.com Fri Aug 17 19:23:38 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Fri Aug 17 19:15:37 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> <641FEAB9-7063-4D81-9426-630E08439B6D@cs.otago.ac.nz> Message-ID: For a really good article to see how foldr is in fact very powerful and how you can make it do some funny tricks, see the Monad.Reader 6th issue : http://www.haskell.org/sitewiki/images/1/14/TMR-Issue6.pdf I'll point out that you can write a lazy dropWhile with foldr in the style of the first example of the article just by using a non-refutable pattern in the combine function : dWLazy p = snd . foldr (\a ~(x, y) -> if p a then (a : x, y) else (a : x, a : x)) ([], []) -- Jeda? From chaddai.fouche at gmail.com Fri Aug 17 19:26:11 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Fri Aug 17 19:17:38 2007 Subject: [Haskell-cafe] defining last using foldr In-Reply-To: References: <12151145.post@talk.nabble.com> <12151694.post@talk.nabble.com> <12169661.post@talk.nabble.com> <641FEAB9-7063-4D81-9426-630E08439B6D@cs.otago.ac.nz> Message-ID: 2007/8/18, Chadda? Fouch? : > For a really good article to see how foldr is in fact very powerful > and how you can make it do some funny tricks, see the Monad.Reader 6th > issue : > http://www.haskell.org/sitewiki/images/1/14/TMR-Issue6.pdf > I just saw this was already linked in this thread, sorry for the noise... -- Jeda? From paul at cogito.org.uk Fri Aug 17 19:56:00 2007 From: paul at cogito.org.uk (Paul Johnson) Date: Fri Aug 17 19:47:33 2007 Subject: [Haskell-cafe] monte carlo trouble In-Reply-To: References: <46C3482D.8020200@cogito.org.uk> <46C35985.4010302@cogito.org.uk> Message-ID: <46C63590.1020909@cogito.org.uk> I finally decided to actually solve the problem, and I'm sorry to say I was on the wrong track. ListT won't do it on its own: you actually need a custom monad that does the random pick in the bind operation. Attached are a module to solve the problem and a Main module that tests it. I hope this helps. Paul. -------------- next part -------------- A non-text attachment was scrubbed... Name: Main.hs Type: text/x-haskell Size: 659 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070818/d003aed9/Main-0001.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: MonteCarlo.hs Type: text/x-haskell Size: 1653 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070818/d003aed9/MonteCarlo-0001.bin From jerzy.karczmarczuk at info.unicaen.fr Fri Aug 17 20:00:25 2007 From: jerzy.karczmarczuk at info.unicaen.fr (jerzy.karczmarczuk@info.unicaen.fr) Date: Fri Aug 17 19:51:46 2007 Subject: [Haskell-cafe] Remember the future In-Reply-To: <46C5F84F.8020404@btinternet.com> References: <46C5F84F.8020404@btinternet.com> Message-ID: Andrew Coppin writes: > I've seen comments in various places that monads allow you to "borrow > things from the future". > > That sounds completely absurd to me... can anybody explain? Actually, "borrowing from the future" - in an interpretation which is close to my own interests - doesn't need monads, but *laziness*. If you find this absurd, I propose that you have a look on something a bit light, my paper on a quite crazy way to compute PI with a high precision. The algorithm (not mine, but of Bailey, Borwein and Plouffe) is a masterpiece of numerical math, but its implementation relies on a mad borrowing from the future. http://users.info.unicaen.fr/~karczma/arpap/lazypi.pdf If you don't choke, try another one, the reverse automatic differentiation algorithm, implemented using a variant of the Wadler's "counter-temporal" state monad. http://users.info.unicaen.fr/~karczma/arpap/revdf1.pdf It is quite serious, although inefficient, and has some affinities to the lazy processing of inherited attributes during parsing. More recently, Barak Pearlmutter and Jeff Siskind worked on similar issues, but I am not sure whether they submitted something ready for the audience. Please check it out. Jerzy Karczmarczuk From paul at cogito.org.uk Fri Aug 17 20:10:53 2007 From: paul at cogito.org.uk (Paul Johnson) Date: Fri Aug 17 20:02:22 2007 Subject: [Haskell-cafe] Remember the future In-Reply-To: References: <46C5F84F.8020404@btinternet.com> Message-ID: <46C6390D.3050804@cogito.org.uk> jerzy.karczmarczuk@info.unicaen.fr wrote: > Andrew Coppin writes: >> I've seen comments in various places that monads allow you to "borrow >> things from the future". >> That sounds completely absurd to me... can anybody explain? > > Actually, "borrowing from the future" - in an interpretation which is > close > to my own interests - doesn't need monads, but *laziness*. While this is true, the "mdo" and associated MonadFix class do implement it in a monadic framework where you can write things like mdo x <- f y y <- g x If you interpret do-notation as equivalent to imperative programming then this does indeed look like time travel. Under the covers its more equivalent to let x = f y y = g x which is also known as "tying the knot" or the "credit card transform" (both keywords worth looking up). However I can't say I really have my head around it properly. Paul. From thomas.hartman at db.com Fri Aug 17 20:13:55 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 17 20:05:26 2007 Subject: [Haskell-cafe] trouble compiling "import GHC.Prim(MutableByteArray#, ....." (building regex-tdfa from darcs) -- what's that # sign doing? In-Reply-To: <20070817204757.GA3775@localhost.localdomain> Message-ID: Thanks Stefan. I got regex tdfa to compile on 6.7. FWIW, here's a patch, generated with darcs whatsnew against a fresh unzip of regex tdfa 0.92 I didn't patch against the darcs head because this uses a "language" progma in {-# options #-} in some file*, which ghc 6.7 didn't know what to do with, nor I. *: Text/Regex/TDFA/RunMutState.hs: {-# LANGUAGE CPP #-} (in darcs head, which as I said, I did not patch against, rather I patched against 0.92 downloaded and unzipped.) If there is a better way than this to send patches please advise, as I don't do this terribly often. (Actually I have no idea how to apply the below patch... is there a way?) { hunk ./Data/IntMap/CharMap.hs 1 +{-# OPTIONS -XGeneralizedNewtypeDeriving #-} hunk ./Data/IntMap/EnumMap.hs 1 +{-# OPTIONS -XGeneralizedNewtypeDeriving #-} hunk ./Data/IntSet/EnumSet.hs 1 +{-# OPTIONS -XGeneralizedNewtypeDeriving #-} hunk ./Text/Regex/TDFA/ByteString/Lazy.hs 1 -{-# OPTIONS_GHC -fno-warn-orphans #-} +{-# OPTIONS_GHC -fno-warn-orphans -fglasgow-exts #-} hunk ./Text/Regex/TDFA/Common.hs 1 -{-# OPTIONS -funbox-strict-fields #-} +{-# OPTIONS -funbox-strict-fields -XGeneralizedNewtypeDeriving #-} hunk ./Text/Regex/TDFA/CorePattern.hs 1 +{-# OPTIONS -fglasgow-exts #-} hunk ./Text/Regex/TDFA/CorePattern.hs 38 +import Data.Monoid +import Control.Monad hunk ./Text/Regex/TDFA/RunMutState.hs 1 +{-# OPTIONS -fglasgow-exts #-} hunk ./Text/Regex/TDFA/String.hs 1 -{-# OPTIONS_GHC -fno-warn-orphans #-} +{-# OPTIONS_GHC -fno-warn-orphans -fglasgow-exts #-} hunk ./Text/Regex/TDFA/TDFA.hs 1 +{-# OPTIONS -fglasgow-exts #-} hunk ./Text/Regex/TDFA/TDFA.hs 12 -import Control.Monad.RWS +import Control.Monad (mplus) +--import Control.Monad.RWS hunk ./Text/Regex/TDFA/TDFA.hs 33 +import Data.Monoid + hunk ./Text/Regex/TDFA/TNFA.hs 1 -{-# OPTIONS_GHC -fno-warn-orphans #-} +{-# OPTIONS_GHC -fno-warn-orphans -fglasgow-exts #-} hunk ./Text/Regex/TDFA/Wrap.hs 1 -{-# OPTIONS -fno-warn-orphans #-} +{-# OPTIONS -fno-warn-orphans -fglasgow-exts #-} hunk ./Text/Regex/TDFA.hs 42 - ,module Text.Regex.TDFA.String - ,module Text.Regex.TDFA.ByteString - ,module Text.Regex.TDFA.ByteString.Lazy - ,module Text.Regex.TDFA.Sequence + --,module Text.Regex.TDFA.String + --,module Text.Regex.TDFA.ByteString + --,module Text.Regex.TDFA.ByteString.Lazy + --,module Text.Regex.TDFA.Sequence hunk ./regex-tdfa.cabal 16 -Build-Depends: regex-base >= 0.80, base >= 2.0, parsec, mtl +Build-Depends: regex-base >= 0.80, base >= 2.0, parsec, mtl, containers, array, bytestring } "Stefan O'Rear" 08/17/2007 04:47 PM To Thomas Hartman/ext/dbcom@DBAmericas cc haskell-cafe Subject Re: [Haskell-cafe] trouble compiling "import GHC.Prim(MutableByteArray#, ....." (building regex-tdfa from darcs) -- what's that # sign doing? On Fri, Aug 17, 2007 at 04:27:29PM -0400, Thomas Hartman wrote: > trying to compile regex-tdfa, I ran into another issue. (earlier I had a > cabal problem but that's resolved.) > > there's a line that won't compile, neither for ghc 6.6.1 nor 6.7 > > import > GHC.Prim(MutableByteArray#,RealWorld,Int#,sizeofMutableByteArray#,unsafeCoerce#) > > so the fresh darcs regex tdfa package won't build. > > This line (line 16 below) causes this error for > > ghc -e '' RunMutState.hs > > for both ghc 6.1 and 6.7 There are at least two things going on here. 1. GHC-specific unboxed identifiers have a # in the name. I think this is a relic from back when the only reasonable way to namespace was to modify your compiler to add extra identifier characters, and use them in all non-portable identifiers. In any case, you have to enable the -fglasgow-exts option (or -XMagicHash in recent 6.7) to allow imports of such identifiers. 2. Explicitly importing GHC.Prim has been discouraged for as long as I can remember, and GHC HQ has finally made good on the promise to make it impossible. Code which imports it has a bug already, which can be fixed by switching to GHC.Exts. (Why? GHC.Prim is wired into the compiler, while GHC.Exts is a normal Haskell module, so by using GHC.Exts you are insulated from questions of what is primitive and what is derived but still unportable. Yes, this does change.) Stefan [attachment "signature.asc" deleted by Thomas Hartman/ext/dbcom] --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/89f273e0/attachment.htm From stefanor at cox.net Fri Aug 17 20:38:02 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Fri Aug 17 20:29:29 2007 Subject: [Haskell-cafe] trouble compiling "import GHC.Prim(MutableByteArray#, ....." (building regex-tdfa from darcs) -- what's that # sign doing? In-Reply-To: References: <20070817204757.GA3775@localhost.localdomain> Message-ID: <20070818003802.GA4384@localhost.localdomain> On Fri, Aug 17, 2007 at 08:13:55PM -0400, Thomas Hartman wrote: > Thanks Stefan. I got regex tdfa to compile on 6.7. FWIW, here's a patch, > generated with darcs whatsnew against a fresh unzip of regex tdfa 0.92 > > I didn't patch against the darcs head because this uses a "language" > progma in {-# options #-} in some file*, which ghc 6.7 didn't know what to > do with, nor I. > > *: Text/Regex/TDFA/RunMutState.hs: {-# LANGUAGE CPP #-} (in darcs head, > which as I said, I did not patch against, rather I patched against 0.92 > downloaded and unzipped.) That's a bug, in either GHC 6.7.x (please specify the date if you can, 6.7 is a pretty wide range!) or regex-tdfa. Does {-# OPTIONS_GHC -cpp #-} (theoretically equivalent) work? What's the error message? > If there is a better way than this to send patches please advise, as I > don't do this terribly often. (Actually I have no idea how to apply the > below patch... is there a way?) $ mkdir ~/.darcs $ echo 'Thomas Hartman ' > ~/.darcs/author $ darcs record -a $ darcs send > [patch] > { > hunk ./Data/IntMap/CharMap.hs 1 > +{-# OPTIONS -XGeneralizedNewtypeDeriving #-} Ick. {-# OPTIONS is very strongly deprecated, since it doesn't specify a compiler but must use a compiler-specific syntax. Much better to use LANGUAGE: {-# LANGUAGE GeneralizedNewtypeDeriving #-} > +Build-Depends: regex-base >= 0.80, base >= 2.0, parsec, mtl, > containers, array, bytestring That won't work; you must indent continuation lines. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/cbc70616/attachment.bin From lennart at augustsson.net Fri Aug 17 20:59:32 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Fri Aug 17 20:50:59 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: <12197224.post@talk.nabble.com> References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> <12195537.post@talk.nabble.com> <12197224.post@talk.nabble.com> Message-ID: On 8/17/07, Kim-Ee Yeoh wrote: > > > > Lennart Augustsson wrote: > > > > And as a previous poster showed, ghc does concatenate strings. > > > > And Haskell (as in the current language definition) does not. > I was talking about Haskell. Haskell says nothing about compile time or run time in the language definition. Nor does it say exactly when things are evaluated. Even the tag line for Haskell says "non-strict" rather than lazy. So Haskell semantics allows many evaluation strategies, and evaluating terminating constant expression at compile time is certainly one of them. You don't have to, but it's permissible. -- Lennart -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070818/e0186b77/attachment-0001.htm From catamorphism at gmail.com Fri Aug 17 21:01:48 2007 From: catamorphism at gmail.com (Tim Chevalier) Date: Fri Aug 17 20:53:15 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: <12197224.post@talk.nabble.com> References: <46A02E6E.1040904@mindspring.com> <8246311.1184952552436.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> <12195537.post@talk.nabble.com> <12197224.post@talk.nabble.com> Message-ID: <4683d9370708171801t1a520749qd1202f7aba5e42f7@mail.gmail.com> On 8/17/07, Kim-Ee Yeoh wrote: > Incidentally, GHC's type checker is Turing complete. You > already have as much static evaluation as is practically possible. > You already knew that. > I don't see how the first statement implies the second. Cheers, Tim -- Tim Chevalier * catamorphism.org * Often in error, never in doubt "It's never too early to start drilling holes in your car." -- Tom Magliozzi From trebla at vex.net Fri Aug 17 21:59:26 2007 From: trebla at vex.net (Albert Y. C. Lai) Date: Fri Aug 17 21:50:58 2007 Subject: [Haskell-cafe] Re: Bathroom reading In-Reply-To: <46C4FF13.6090005@imageworks.com> References: <2d3641330708140817t256c936egd00c065a66a57cd6@mail.gmail.com> <200708141031.51497.sjanssen@cse.unl.edu> <46C4FF13.6090005@imageworks.com> Message-ID: <46C6527E.3000209@vex.net> Dan Weston wrote: > I hate to be a party pooper, but isn't this just: > > > f = foldr (\a z -> (a:snd z,fst z)) ([],[]) > > This takes less time to grok and takes no longer to run. For each type with exported constructors, one can always write deconstructors for it, if not already found in libraries. One may then argue that ~ is never necessary. Given f ( ~(Left (z0,_)) : Right ~(Just z1) : xs ) = (z0, z1, xs) you can always hand-compile to f (x0 : Right y1 : xs) = (fst (getLeft x0), fromJust y1, xs) But ~ is desirable: 0. Which version is easier to understand? That is a bit subjective, but I think it comes down to this. (As do all debates over whether concise notation is readable, really.) To a kid who has not learned the word "arctan", I have to say, "draw this right-angled triangle, with this side being length 3, that side being length 4, now measure this angle, that is what I mean by arctan(3/4)" - you know, all the details, step by step, hand in hand. To a learned adult, I can just say, "arctan". In fact, if I spelt out the details to the adult, step by step, hand in hand, he/she would think I'm condescending or counterproductive. Specifically in the case of ~, it makes transparent the structure of the data to be expected: By just reading one spot, you see it wants a list of two or more items, the first item is a Left, in which there is a tuple, the second item is a Right, in which there is a Just. That same information is torned apart without ~: part of the information is on the left, and the rest is hidden on the right to be recovered from the deconstructor calls and re-constructing the picture in your head. This is because it is more low-level. The "what" is encoded beneath the "how". You follow the code execution and then you reverse-engineer its purpose. It is quite attractive when you have no notation to denote the purpose. It is a poor choice when you have a notation to denote the purpose: "what" data parts are wanted, and "when" they are wanted, without reading a single function call, the "how". 1. Which version is easier to change strictness? Strictness and non-strictness are tricky to get right for performance or even mere feasibility. An important programming activity is investigating various levels of strictness. It is imperative to be able to change strictness efficiently. ~ is already a non-strictness annotation. Anyone who already understands the ! strictness annotation understands this one too. By just toggling ~'s you toggle non-strictness. It's that easy to change. Here is the function again. I'm going to change its strictness. f ( ~(Left (z0,_)) : Right ~(Just z1) : xs ) = (z0, z1, xs) I now want the second cons to be later, the Left to be earlier (at the same time as the first cons), the tuple to be later, the Right to be later (even later than the second cons), and the Just to be earlier (at the same time as the Right). I can do that by just toggling ~'s: f ( Left ~(z0,_) : ~(~(Right (Just z1)) : xs) ) = (z0, z1, xs) Without ~, much more change is necessary. Here is the non-~ code before change again: f (x0 : Right y1 : xs) = (fst (getLeft x0), fromJust y1, xs) The change is: f (Left y0 : xs) = (fst y0, fromJust (getRight (head xs)), tail xs) Both sides have to be changed. On the left, the data structure has to be changed. On the right, the function call structure has to be changed. You have to remove a constructor on the left and add a deconstructor on the right, or add a constructor on the left and remove a deconstructor on the right. This is a dream come true for IDE marketeers. This code manipulation is too annoying to be done by hand on a daily basis, yet mechanical enough to be done by software easily. A marketeer can sell an IDE plugin for this and garner much money and gratitude from unsuspecting programmers, capitalizing on the fact that some languages do not provide an annotation to trivialize this whole business, and in those that do, some programmers refuse to use it. From lennart at augustsson.net Sat Aug 18 04:39:08 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Sat Aug 18 04:30:35 2007 Subject: [Haskell-cafe] Hints for Euler Problem 11 In-Reply-To: <4683d9370708171801t1a520749qd1202f7aba5e42f7@mail.gmail.com> References: <46A02E6E.1040904@mindspring.com> <1c32de90708151032n29da9ebdwdcc0dcc78a135d0@mail.gmail.com> <233457100708151053y1df067a3ua705ef0f82564843@mail.gmail.com> <12188224.post@talk.nabble.com> <12195537.post@talk.nabble.com> <12197224.post@talk.nabble.com> <4683d9370708171801t1a520749qd1202f7aba5e42f7@mail.gmail.com> Message-ID: I agree. Computation on the type level does not imply computation on the value level. On 8/18/07, Tim Chevalier wrote: > > On 8/17/07, Kim-Ee Yeoh wrote: > > Incidentally, GHC's type checker is Turing complete. You > > already have as much static evaluation as is practically possible. > > You already knew that. > > > > I don't see how the first statement implies the second. > > Cheers, > Tim > > -- > Tim Chevalier * catamorphism.org * Often in error, never in doubt > "It's never too early to start drilling holes in your car." -- Tom > Magliozzi > _______________________________________________ > 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/haskell-cafe/attachments/20070818/f1f14e4c/attachment.htm From andrewcoppin at btinternet.com Sat Aug 18 05:07:48 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 18 04:58:27 2007 Subject: [Haskell-cafe] Remember the future In-Reply-To: <625b74080708171543g3945b0cag3bf62ae610e8b016@mail.gmail.com> References: <46C5F84F.8020404@btinternet.com> <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> <625b74080708171543g3945b0cag3bf62ae610e8b016@mail.gmail.com> Message-ID: <46C6B6E4.2060704@btinternet.com> Dan Piponi wrote: > On 8/17/07, Dan Piponi wrote: > >> On 8/17/07, Andrew Coppin wrote: >> >>> That sounds completely absurd to me... can anybody explain? >>> >> Except...you can switch on ghc's special time travel features... >> > > On reflection I decided my example isn't very convincing. For one > thing, I've argued in another thread that monads aren't really about > sequencing actions. But I concede that there is an exception: the IO > monad. Because the IO monad has observable side effects you can > actually see whether or not an action has taken place at a particular > time, so it really does have to sequence actions. So now consider the > following code: > > >> import IO >> import Control.Monad.Fix >> > > >> test = mdo >> z <- return $ x+y >> print "Hello" >> x <- readLn >> y <- readLn >> return z >> > > Evaluate test and you'll be prompted to enter a pair of numbers. > You'll then be rewarded with their sum. But the "Hello" message is > printed before the prompt for input so we know that's being executed > first. And we can see clearly that the summation is performed before > the "Hello" message. So clearly this program is computing its result > before receiving the input. > > At this point your natural reaction should be to replace 'print > "Hello"' with 'print z'... > Surely all this means is that the magical "mdo" keyword makes the compiler arbitrarily reorder the expression...? From haskell at brecknell.org Sat Aug 18 06:40:15 2007 From: haskell at brecknell.org (Matthew Brecknell) Date: Sat Aug 18 06:31:41 2007 Subject: [Haskell-cafe] Diagnosing stack overflow In-Reply-To: References: <1187308362.8691.1205805295@webmail.messagingengine.com> Message-ID: <1187433615.20252.1206016971@webmail.messagingengine.com> Justin Bailey: > Would "retainer profiling" help me see what was building up > this large thunk/closure? I'm not really familiar enough with GHC's profiling to answer that, but I'll take a guess. My guess is that profiling will only sometimes be useful in diagnosing stack overflows, because I suspect that memory stats reported by the profiler will usually be dominated by heap usage. So profiling *might* point you towards some big thunks on the heap which might cause a stack overflow on evaluation. If so, then you're in luck. But the problem is that you don't actually *need* a huge unevaluated thunk to cause a stack overflow. Sure, the foldl example had one, but consider what happens if we use foldr instead: print (foldr (+) 0 [1..]) => print (1+(foldr (+) 0 [2..])) => print (1+(2+(foldr (+) 0 [3..]))) => print (1+(2+(3+(foldr (+) 0 [4..])))) => ... => print (1+(2+(3+(...+(foldr (+) 0 [...])))) => stack overflow It's a bit more tricky to explain what's going on here, which may be one reason why foldr is not the usual stack overflow example. While the nested additions in the foldl example represented a long chain of unevaluated thunks on the heap, here they represent partially executed computations on the stack. There is no big thunk! But there are still many nested contexts on the stack, so we still get an overflow. Another way of contrasting the foldl and foldr examples is to realise that foldl always consumes its entire input list, while foldr only consumes as much as its asked to. In the former, foldl drives the process of thunk building. In the latter, it is the evaluation of the innermost (+) function that drives foldr to generate the next iteration. I suspect that explanation is not very clear, so I give a small experiment which will at least show that I'm not lying. :-) Run a basic GHC profile (without optimisations) on each of the following, and observe the total memory usage. With foldl, memory usage is very high, because the entire list is consumed to produce a huge thunk on the heap. With foldr, memory usage is only about 16M, just enough to blow the stack. -- trial 1: stack overflow, lots of memory consumed main = print (foldl (+) 0 [1..10000000] :: Int) -- trial 2: stack overflow, minimal memory consumption main = print (foldr (+) 0 [1..10000000] :: Int) In fact, we could give foldr an infinite list, and get exactly the same result. Curiously, if we give foldl an infinite list, we don't get a stack overflow, because we never get to the point of evaluating the thunk. Instead, we get heap exhaustion, because we just keep building thunks. -- trial 4: heap exhaustion, nasty main = print (foldl (+) 0 [1..] :: Int) -- trial 5: stack overflow, minimal memory consumption main = print (foldr (+) 0 [1..] :: Int) It's also instructive to run these tests with optimisations (no profiling), to see how they are affected by strictness analysis. Note that strictness analysis doesn't work for the default Integer type, so the Int type annotations are necessary. From benjamin.franksen at bessy.de Sat Aug 18 10:32:17 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Sat Aug 18 10:23:59 2007 Subject: [Haskell-cafe] Re: Remember the future References: <46C5F84F.8020404@btinternet.com> <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> <625b74080708171543g3945b0cag3bf62ae610e8b016@mail.gmail.com> <46C6B6E4.2060704@btinternet.com> Message-ID: Andrew Coppin wrote: > Surely all this means is that the magical "mdo" keyword makes the > compiler arbitrarily reorder the expression...? It is not magical but simple syntactic sugar. And no, the compiler does not 'arbitrarily reorder' anything, you do the same in any imperative language with pointers/references and mutation. >From the ghc manual: ----------- 7.3.3. The recursive do-notation ... The do-notation of Haskell does not allow recursive bindings, that is, the variables bound in a do-expression are visible only in the textually following code block. Compare this to a let-expression, where bound variables are visible in the entire binding group. It turns out that several applications can benefit from recursive bindings in the do-notation, and this extension provides the necessary syntactic support. Here is a simple (yet contrived) example: import Control.Monad.Fix justOnes = mdo xs <- Just (1:xs) return xs As you can guess justOnes will evaluate to Just [1,1,1,.... The Control.Monad.Fix library introduces the MonadFix class. It's definition is: class Monad m => MonadFix m where mfix :: (a -> m a) -> m a ----------- It is unfortunate that the manual does not give the translation rules, or at least the translation for the given example. If I understood things correctly, the example is translated to justOnes = mfix (\xs' -> do { xs <- Just (1:xs'); return xs } You can imagine what happens operationally by thinking of variables as pointers. As long as you don't de-reference them, you can use such pointers in expressions and statements even if the object behind them has not yet been initialized (=is undefined). The question is how the objects are eventually be initialized. In imperative languages this is done by mutation. In Haskell you employ lazy evaluation: the art of circular programming is to use not-yet-defined variables lazily, that is, you must never demand the object before the mdo block has been executed. A good example is http://www.cse.ogi.edu/PacSoft/projects/rmb/doubly.html which explains how to create a doubly linked circular list using mdo. Cheers Ben From dpiponi at gmail.com Sat Aug 18 11:19:49 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Sat Aug 18 11:11:17 2007 Subject: [Haskell-cafe] Remember the future In-Reply-To: <46C6B6E4.2060704@btinternet.com> References: <46C5F84F.8020404@btinternet.com> <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> <625b74080708171543g3945b0cag3bf62ae610e8b016@mail.gmail.com> <46C6B6E4.2060704@btinternet.com> Message-ID: <625b74080708180819g199ccaeci48007cb2ef2eacd4@mail.gmail.com> On 8/18/07, Andrew Coppin wrote: > Surely all this means is that the magical "mdo" keyword makes the > compiler arbitrarily reorder the expression...? What mdo actually does is described here: http://www.cse.ogi.edu/PacSoft/projects/rmb/mdo.pdf My last example desugars to: test = mfix ( \ ~(x,y,z,v) -> do z <- return $ x+y print "Hello" x <- readLn y <- readLn v <- return z return (x,y,z,v)) >>= \(x,y,z,v) -> return v So at core there really is a do-expression that's passing 'return $ x+y' into a print which in turn is passed into the 'readLn's. -- Dan From mfn-haskell-cafe at cs.york.ac.uk Sat Aug 18 12:07:06 2007 From: mfn-haskell-cafe at cs.york.ac.uk (Matthew Naylor) Date: Sat Aug 18 12:01:24 2007 Subject: [Haskell-cafe] Remember the future In-Reply-To: <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> References: <46C5F84F.8020404@btinternet.com> <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> Message-ID: <20070818160706.GA12590@venice.cs.york.ac.uk> Hi Dan, > > import Control.Monad.State > > > test = do > > put $ x+1 > > x <- return 1 > > return undefined > > > go = execState test undefined I'd just like to point out that you can do something similar without mdo. For example, you can define a monad with newVar, readVar, and writeVar such that running the following results in 2. test = do x <- newVar y <- newVar valx <- readVar x writeVar y (valx+1) writeVar x 1 valy <- readVar y return valy (As you probably know, the previous two Monad.Reader issues include two different examples -- assembler and circuit description -- of circular programming in a monad.) Matt. From newptcai at gmail.com Sat Aug 18 12:12:04 2007 From: newptcai at gmail.com (Peter Cai) Date: Sat Aug 18 12:03:29 2007 Subject: [Haskell-cafe] Parsing binary data. Message-ID: Hi all, Recently I am considering doing part of my job using Haskell. My duty is writing a network server which talks to another server through a binary based private protocol. As the old version of this component is written in C, it's very natural that this protocol is base on C structure definitions, which are, unfortunately, very complicated. And the worse is that every field in every structure must be converted to Network Endian. As I am a newbie to Haskell, I am not sure how to handle this problem with less work. Do you have any ideas about this problem? Thanks in advance! -- There is No CODE That is More Flexible Than NO Code! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070819/6f028bd2/attachment.htm From agl at imperialviolet.org Sat Aug 18 13:47:28 2007 From: agl at imperialviolet.org (Adam Langley) Date: Sat Aug 18 13:38:54 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: References: Message-ID: <396556a20708181047y3226f12am9f351421ad61dfd5@mail.gmail.com> On 8/18/07, Peter Cai wrote: > As the old version of this component is written in C, it's very natural that > this protocol is base on C structure definitions, which are, unfortunately, > very complicated. And the worse is that every field in every structure must > be converted to Network Endian. You could certainly try Data.Binary[1] for this. It has a nice Get monad with methods such as getWord32be which sounds like it might be what you want. One caveat is that it's fully lazy - you get the result immediately and parse errors can only be caught as exceptions when you actually come to using the result. This is perfect for very large messages, but might be slightly wrong for you. [1] http://hackage.haskell.org/cgi-bin/hackage-scripts/package/binary-0.3 -- Adam Langley agl@imperialviolet.org http://www.imperialviolet.org 650-283-9641 From wss at cs.nott.ac.uk Sat Aug 18 14:05:04 2007 From: wss at cs.nott.ac.uk (Wouter Swierstra) Date: Sat Aug 18 13:56:31 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <20070807021701.GN8756@cse.unsw.EDU.AU> References: <46B71D2B.8080504@inf.fu-berlin.de> <837db430708061619m37624ae4s5b221b73a17556b6@mail.gmail.com> <20070807020901.GK8756@cse.unsw.EDU.AU> <837db430708061913m1fe8c073u9238fe7f10f36798@mail.gmail.com> <20070807021701.GN8756@cse.unsw.EDU.AU> Message-ID: <800870BA-28F7-4778-B80B-2ED41B6A66AD@cs.nott.ac.uk> > I'm a little surprised no one's tried a parallel solution yet, > actually. > We've got an SMP runtime for a reason, people! I hacked up a parallel version of Richard Bird's function pearl solver: http://www.haskell.org/sitewiki/images/1/12/SudokuWss.hs It not really optimized, but there are a few neat tricks there. Rather than prune the search space by rows, boxes, and columns sequentially, it represents the sudoku grid by a [[TVar [Int]]], where every cell has a TVar [Int] corresponding to the list of possible integers that would 'fit' in that cell. When the search space is pruned, we can fork off separate threads to prune by columns, rows, and boxes -- the joy of STM! Wouter From marco-oweber at gmx.de Sat Aug 18 14:12:45 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Sat Aug 18 14:04:11 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: References: Message-ID: <20070818181245.GC20812@gmx.de> > As I am a newbie to Haskell, I am not sure how to handle this problem > with less work. Do you have any ideas about this problem? > Thanks in advance! Have a look at http://haskell.org/haskellwiki/Applications_and_libraries/Data_structures section 3 (IO) -> http://haskell.org/haskellwiki/Binary_IO Of course you can just use most different parser libraries as well, because most are not tight to one token type.. So you shouldn't have any trouble parsing a ByeSttring which is a char (8bit word) buffer. I'd recommend having a look at ParseP or happy/ alex .. if the binary libraries aren't suited for your task.. But to get the fastest/ whatsoever solution you should wait for different replies as I haven't used all those yet to parse binary data.. Sincerly Marc Weber From bf3 at telenet.be Sat Aug 18 14:35:18 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sat Aug 18 14:26:33 2007 Subject: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? Message-ID: <000101c7e1c6$8724d260$956e7720$@be> When reading an article about tail recursion (http://themechanicalbride.blogspot.com/2007/04/haskell-for-c-3-programmers. html) I came across the follow statements: "If you can write a non-recursive function that uses the colon syntax it is probably better than a tail recursive one that doesn't. This is because Haskell's lazy evaluation enabled you to use the non-tail recursive version on an infinite stream without getting a stack overflow. " and ""Unfortunately", laziness "gets in the way". While transforming non-tail-recursive code to a tail-recursive form is important and useful for functional programming in general, dealing with laziness requires a little more care, and often "non-tail-recursive" versions are preferrable. flatten is an example of this, the first version is better in many ways. While I don't believe it happens in this case, oftentimes naively writing code "tail-recursively" in Haskell will actually -make- it overflow the stack. Another (actual) benefit of the first version of flatten is that it will work on infinite lists. http://www.haskell.org/hawiki/StackOverflow gives a simple example and some explanation." Unfortunately I can't find the StackOverflow page anymore. Now if I understand this correctly, this just means that when writing something like: foo n = if n<0 then [] else n : foo (n-1) bar n = aux 0 [] where aux i xs = if i>n then xs else aux (i+1) (i:xs) that foo is more efficient than bar because lazy evaluation of foo just puts the delayed computation in the "cdr" of the list, while lazy evaluation of bar has to keep track of all aux calls (the "closures") which gives much more overhead, maybe even stack overflow? Something like that? Thanks, Peter From derek.a.elkins at gmail.com Sat Aug 18 14:54:27 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Sat Aug 18 14:45:57 2007 Subject: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <000101c7e1c6$8724d260$956e7720$@be> References: <000101c7e1c6$8724d260$956e7720$@be> Message-ID: <1187463267.5462.22.camel@derek-laptop> On Sat, 2007-08-18 at 20:35 +0200, Peter Verswyvelen wrote: > When reading an article about tail recursion > (http://themechanicalbride.blogspot.com/2007/04/haskell-for-c-3-programmers. > html) I came across the follow statements: > > "If you can write a non-recursive function that uses the colon syntax it is > probably better than a tail recursive one that doesn't. This is because > Haskell's lazy evaluation enabled you to use the non-tail recursive version > on an infinite stream without getting a stack overflow. " > > and > > ""Unfortunately", laziness "gets in the way". While transforming > non-tail-recursive code to a tail-recursive form is important and useful for > functional programming in general, dealing with laziness requires a little > more care, and often "non-tail-recursive" versions are preferrable. flatten > is an example of this, the first version is better in many ways. While I > don't believe it happens in this case, oftentimes naively writing code > "tail-recursively" in Haskell will actually -make- it overflow the stack. > Another (actual) benefit of the first version of flatten is that it will > work on infinite lists. http://www.haskell.org/hawiki/StackOverflow gives a > simple example and some explanation." That page was migrated here: http://www.haskell.org/haskellwiki/Stack_overflow From wagner.andrew at gmail.com Sat Aug 18 14:55:52 2007 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Sat Aug 18 14:47:17 2007 Subject: [Haskell-cafe] Chessboard-building in Haskell Message-ID: I've started a blog series on writing a chess engine in Haskell. I just posted the second blog entry today: http://sequence.complete.org/node/361 I suspect there's more work to be done on that function, though. It seems like there should be a nice way to remove that flip in apply. Any thoughts? From hjgtuyl at chello.nl Sat Aug 18 15:10:10 2007 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Sat Aug 18 15:01:28 2007 Subject: [Haskell-cafe] Old editions of The Monad.Reader lost Message-ID: L.S., Now that all hawiki pages have been removed, we have lost some valuable information. For example The Monad.Reader; on http://www.haskell.org/haskellwiki/The_Monad.Reader it says: Older editions can be found on the old Haskell wiki ? they haven't been included here for licensing reasons. The page it links to, a hawiki page, has dissappeared. I propose to bring at least the The Monad.Reader pages back. Backups of these pages can be found at the Wayback Machine, but there is no guarantee that will always be there. -- Met vriendelijke groet, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- From twanvl at gmail.com Sat Aug 18 15:23:35 2007 From: twanvl at gmail.com (Twan van Laarhoven) Date: Sat Aug 18 15:14:55 2007 Subject: [Haskell-cafe] Chessboard-building in Haskell In-Reply-To: References: Message-ID: <46C74737.8090002@gmail.com> Andrew Wagner wrote: > I've started a blog series on writing a chess engine in Haskell. I > just posted the second blog entry today: > http://sequence.complete.org/node/361 > > I suspect there's more work to be done on that function, though. It > seems like there should be a nice way to remove that flip in apply. > Any thoughts? The trick is that you should always prefer zipWith over zip if you have the chanse, tuples make life harder. Let's use some equational reasoning: foldl apply emptyGameState (zip funcs fields) = {- fill in 'apply' -} foldl (flip (ap fst snd)) emptyGS (zip funcs fields) = {- write it as a lambda function to make it clearer -} foldl (\y (f,x) -> f x y) emptyGS (zip funcs fields) = {- split fold into a fold and a map -} foldl (\y fx -> fx y) emptyGS $ map (\(f,x) -> f x) $ (zip funcs fields) = {- map . zip --> zipWith -} foldl (\y fx -> fx y) emptyGS $ zipWith (\f x -> f x) funcs fields = {- use prelude functions -} foldl (flip ($)) emptyGS $ zipWith ($) funcs fields ~= {- now, do you really want a foldl or will foldr do? -} foldr ($) emptyGS $ zipWith ($) funcs fields You can now also write the function in pointfree style: > loadFEN = foldr ($) emptyGameState > . zipWith ($) funcs > . words > where funcs = [parseBoard, parseCastleStatus] Twan From polyomino at f2s.com Sat Aug 18 15:26:08 2007 From: polyomino at f2s.com (DavidA) Date: Sat Aug 18 15:17:50 2007 Subject: [Haskell-cafe] How do I simulate dependent types using phantom types? Message-ID: Hi, I am trying to implement quadratic fields Q(sqrt d). These are numbers of the form a + b sqrt d, where a and b are rationals, and d is an integer. In an earlier attempt, I tried data QF = QF Integer Rational Rational (see http://www.polyomino.f2s.com/david/haskell/hs/QuadraticField.hs.txt) The problem with this approach is that it's not really type-safe: I can attempt to add a + b sqrt 2 to c + d sqrt 3, whereas this should be a type error because 2 /= 3. So I thought I'd have a go at doing it with phantom types. In effect I'd be using phantom types to simulate dependent types. Here's the code: {-# OPTIONS_GHC -fglasgow-exts #-} import Data.Ratio class IntegerType a where value :: Integer data Two instance IntegerType Two where value = 2 data Three instance IntegerType Three where value = 3 data QF d = QF Rational Rational deriving (Eq) instance IntegerType d => Show (QF d) where show (QF a b) = show a ++ " + " ++ show b ++ " sqrt " ++ show value instance IntegerType d => Num (QF d) where QF a b + QF a' b' = QF (a+a') (b+b') negate (QF a b) = QF (-a) (-b) QF a b * QF c d = QF (a*c + b*d*value) (a*d + b*c) fromInteger n = QF (fromInteger n) 0 The problem is, this doesn't work. GHC complains: The class method `value' mentions none of the type variables of the class IntegerType a When checking the class method: value :: Integer In the class declaration for `IntegerType' Is what I'm trying to do reasonable? If no, what should I be doing instead? If yes, why doesn't GHC like it? Thanks, David From lennart at augustsson.net Sat Aug 18 15:32:10 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Sat Aug 18 15:23:35 2007 Subject: [Haskell-cafe] How do I simulate dependent types using phantom types? In-Reply-To: References: Message-ID: Use value :: a -> Integer On 8/18/07, DavidA wrote: > > Hi, > > I am trying to implement quadratic fields Q(sqrt d). These are numbers of > the > form a + b sqrt d, where a and b are rationals, and d is an integer. > > In an earlier attempt, I tried > data QF = QF Integer Rational Rational > (see http://www.polyomino.f2s.com/david/haskell/hs/QuadraticField.hs.txt) > The problem with this approach is that it's not really type-safe: > I can attempt to add a + b sqrt 2 to c + d sqrt 3, whereas this should be > a > type error because 2 /= 3. > > So I thought I'd have a go at doing it with phantom types. In effect I'd > be > using phantom types to simulate dependent types. Here's the code: > > {-# OPTIONS_GHC -fglasgow-exts #-} > > import Data.Ratio > > class IntegerType a where > value :: Integer > > data Two > instance IntegerType Two where value = 2 > > data Three > instance IntegerType Three where value = 3 > > data QF d = QF Rational Rational deriving (Eq) > > instance IntegerType d => Show (QF d) where > show (QF a b) = show a ++ " + " ++ show b ++ " sqrt " ++ show value > > instance IntegerType d => Num (QF d) where > QF a b + QF a' b' = QF (a+a') (b+b') > negate (QF a b) = QF (-a) (-b) > QF a b * QF c d = QF (a*c + b*d*value) (a*d + b*c) > fromInteger n = QF (fromInteger n) 0 > > The problem is, this doesn't work. GHC complains: > The class method `value' > mentions none of the type variables of the class IntegerType a > When checking the class method: value :: Integer > In the class declaration for `IntegerType' > > Is what I'm trying to do reasonable? If no, what should I be doing > instead? If > yes, why doesn't GHC like it? > > Thanks, David > > _______________________________________________ > 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/haskell-cafe/attachments/20070818/fd11571b/attachment.htm From derek.a.elkins at gmail.com Sat Aug 18 15:37:09 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Sat Aug 18 15:28:40 2007 Subject: [Haskell-cafe] How do I simulate dependent types using phantom types? In-Reply-To: References: Message-ID: <1187465829.5462.25.camel@derek-laptop> On Sat, 2007-08-18 at 19:26 +0000, DavidA wrote: > Hi, > > I am trying to implement quadratic fields Q(sqrt d). These are numbers of the > form a + b sqrt d, where a and b are rationals, and d is an integer. > > In an earlier attempt, I tried > data QF = QF Integer Rational Rational > (see http://www.polyomino.f2s.com/david/haskell/hs/QuadraticField.hs.txt) > The problem with this approach is that it's not really type-safe: > I can attempt to add a + b sqrt 2 to c + d sqrt 3, whereas this should be a > type error because 2 /= 3. > > So I thought I'd have a go at doing it with phantom types. In effect I'd be > using phantom types to simulate dependent types. Here's the code: > > {-# OPTIONS_GHC -fglasgow-exts #-} > > import Data.Ratio > > class IntegerType a where > value :: Integer > > data Two > instance IntegerType Two where value = 2 > > data Three > instance IntegerType Three where value = 3 > > data QF d = QF Rational Rational deriving (Eq) > > instance IntegerType d => Show (QF d) where > show (QF a b) = show a ++ " + " ++ show b ++ " sqrt " ++ show value > > instance IntegerType d => Num (QF d) where > QF a b + QF a' b' = QF (a+a') (b+b') > negate (QF a b) = QF (-a) (-b) > QF a b * QF c d = QF (a*c + b*d*value) (a*d + b*c) > fromInteger n = QF (fromInteger n) 0 > > The problem is, this doesn't work. GHC complains: > The class method `value' > mentions none of the type variables of the class IntegerType a > When checking the class method: value :: Integer > In the class declaration for `IntegerType' > > Is what I'm trying to do reasonable? If no, what should I be doing instead? If > yes, why doesn't GHC like it? When you write 'value' how is GHC supposed to know what instance you want? The typical trick is to add what could be called a phantom argument to propagate the type. I.e. class IntegerType a where value :: a -> Integer instance IntegerType Two where value _ = 2 value (undefined :: Two) == 2 From twanvl at gmail.com Sat Aug 18 15:37:58 2007 From: twanvl at gmail.com (Twan van Laarhoven) Date: Sat Aug 18 15:29:16 2007 Subject: [Haskell-cafe] How do I simulate dependent types using phantom types? In-Reply-To: References: Message-ID: <46C74A96.4080107@gmail.com> DavidA wrote: > Hi, > > I am trying to implement quadratic fields Q(sqrt d). These are numbers of the > form a + b sqrt d, where a and b are rationals, and d is an integer. > > ... > > class IntegerType a where > value :: Integer > > The problem is, this doesn't work. GHC complains: > The class method `value' > mentions none of the type variables of the class IntegerType a > When checking the class method: value :: Integer > In the class declaration for `IntegerType' > > Is what I'm trying to do reasonable? If no, what should I be doing instead? If > yes, why doesn't GHC like it? You are on the right track. The problem with the class method is that it doesn't use type 'a' anywhere, consider > f :: Integer > f = value What class instance should be used here? The solution is to use a dummy parameter: > class IntegerType a where > value :: a -> Integer And call it like: > f = value (undefined :: Two) So for instance: > instance IntegerType d => Show (QF d) where > show (QF a b) = show a ++ " + " ++ show b ++ " sqrt " > ++ show (value (undefined::d)) The problem is that this doesn't work, because d is not in scope, you need the scoped type variables extension: > valueOfQF :: forall a. IntegerType a => QF a -> Integer > valueOfQF qf = value (undefined :: a) or maybe better, change the class: > class IntegerType a where > value :: QF a -> Integer Now you can simply use > instance IntegerType d => Show (QF d) where > show qf@(QF a b) = show a ++ " + " ++ show b ++ " sqrt " > ++ show (value qf) Twan From chaddai.fouche at gmail.com Sat Aug 18 16:03:23 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Sat Aug 18 15:54:49 2007 Subject: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <000101c7e1c6$8724d260$956e7720$@be> References: <000101c7e1c6$8724d260$956e7720$@be> Message-ID: > foo n = if n<0 then [] else n : foo (n-1) > > bar n = aux 0 [] where > aux i xs = if i>n then xs else aux (i+1) (i:xs) > > that foo is more efficient than bar because lazy evaluation of foo just puts > the delayed computation in the "cdr" of the list, while lazy evaluation of > bar has to keep track of all aux calls (the "closures") which gives much > more overhead, maybe even stack overflow? Something like that? There is absolutely no problem with bar, it will not stack overflow since it _is_ tail-recursive _and_ the comparison i > n force the evaluation of i avoiding the risk of constructing a too big thunk for the first parameter of aux which could bring a stack overflow like in this example : nonStrictLength n [] = n nonStrictLength n (_:xs) = nonStrictLength (n+1) xs (try nonStrictLength 0 [1..10000000] in GHCi to see the stack overflow, GHC strictness analysis would avoid the problem with -O) Though foo is still more interesting than bar since it will work on infinite list, bar is too strict. -- Jeda? From polyomino at f2s.com Sat Aug 18 16:27:30 2007 From: polyomino at f2s.com (DavidA) Date: Sat Aug 18 16:19:15 2007 Subject: [Haskell-cafe] Re: How do I simulate dependent types using phantom types? References: <46C74A96.4080107@gmail.com> Message-ID: Twan van Laarhoven gmail.com> writes: > The solution is to use a dummy parameter: > > class IntegerType a where > > value :: a -> Integer > And call it like: > > f = value (undefined :: Two) > > So for instance: > > instance IntegerType d => Show (QF d) where > > show (QF a b) = show a ++ " + " ++ show b ++ " sqrt " > > ++ show (value (undefined::d)) Thanks to all respondents for this suggestion. That works great. > > The problem is that this doesn't work, because d is not in scope, you > need the scoped type variables extension: > > > valueOfQF :: forall a. IntegerType a => QF a -> Integer > > valueOfQF qf = value (undefined :: a) Well actually, your first attempt *did* work for me (using GHC 6.6.1). Is this not behaviour that I can rely on? From jon at ffconsultancy.com Sat Aug 18 19:11:41 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Sat Aug 18 19:14:17 2007 Subject: [Haskell-cafe] Sudoku Solver In-Reply-To: <800870BA-28F7-4778-B80B-2ED41B6A66AD@cs.nott.ac.uk> References: <46B71D2B.8080504@inf.fu-berlin.de> <20070807021701.GN8756@cse.unsw.EDU.AU> <800870BA-28F7-4778-B80B-2ED41B6A66AD@cs.nott.ac.uk> Message-ID: <200708190011.42296.jon@ffconsultancy.com> On Saturday 18 August 2007 19:05:04 Wouter Swierstra wrote: > I hacked up a parallel version of Richard Bird's function pearl solver: > > http://www.haskell.org/sitewiki/images/1/12/SudokuWss.hs > > It not really optimized, but there are a few neat tricks there. > Rather than prune the search space by rows, boxes, and columns > sequentially, it represents the sudoku grid by a [[TVar [Int]]], > where every cell has a TVar [Int] corresponding to the list of > possible integers that would 'fit' in that cell. When the search > space is pruned, we can fork off separate threads to prune by > columns, rows, and boxes -- the joy of STM! Is it possible to write a shorter Haskell version, perhaps along the lines of this OCaml: let invalid (i, j) (i', j') = i=i' || j=j' || i/n=i'/n && j/n=j'/n let select p n p' ns = if invalid p p' then filter ((<>) n) ns else ns let cmp (_, a) (_, b) = compare (length a) (length b) let add p n sols = sort cmp (map (fun (p', ns) -> p', select p n p' ns) sols) let rec search f sol = function | [] -> f sol | (p, ns)::sols -> iter (fun n -> search f (Map.add p n sol) (add p n sols)) ns -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/?e From dpiponi at gmail.com Sat Aug 18 20:38:49 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Sat Aug 18 20:30:13 2007 Subject: [Haskell-cafe] Using Apple Spotlight to search for .hs and .lhs files Message-ID: <625b74080708181738t6ed1d69n1cbba4dd2e7071bd@mail.gmail.com> This isn't really a Haskell question but I'm guessing some Haskell hackers have a solution. MacOS X's Spotlight doesn't seem to be able to search for text in .lhs and .hs files. But it can find text in .txt files. Is there a way of getting Spotlight to treat .lhs and .hs files like .txt files so I can instantly search all of my Haskell source? -- Dan From dons at cse.unsw.edu.au Sat Aug 18 22:24:56 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Sat Aug 18 22:16:27 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: <20070818181245.GC20812@gmx.de> References: <20070818181245.GC20812@gmx.de> Message-ID: <20070819022455.GA21176@cse.unsw.EDU.AU> marco-oweber: > > As I am a newbie to Haskell, I am not sure how to handle this problem > > with less work. Do you have any ideas about this problem? > > Thanks in advance! > > Have a look at > http://haskell.org/haskellwiki/Applications_and_libraries/Data_structures > section 3 (IO) -> http://haskell.org/haskellwiki/Binary_IO > > Of course you can just use most different parser libraries as well, because most > are not tight to one token type.. So you shouldn't have any trouble > parsing a ByeSttring which is a char (8bit word) buffer. > > I'd recommend having a look at ParseP or happy/ alex .. if the binary > libraries aren't suited for your task.. > > But to get the fastest/ whatsoever solution you should wait for > different replies as I haven't used all those yet to parse binary data.. I'd also recommend Data.Binary for this -- parsing C-friendly protocols off the wire, at high speed, is the main purpose for Data.Binary. -- Don From dbastos at toledo.com Sun Aug 19 00:46:14 2007 From: dbastos at toledo.com (Daniel C. Bastos) Date: Sun Aug 19 00:41:30 2007 Subject: [Haskell-cafe] building a regular polygon Message-ID: I'm new to functional programming and to haskell. I'm reading ``The Haskell School of Expression'' by Paul Hudak and I'm studying how to solve exercise 2.2. My difficulty here is more algorithmic than Haskellian, but perhaps many here have solved this exercise already, or would know how to solve it; I hope it's okay to post. (*) Exercise 2.2 Define a function regularPolygon :: Int -> Side -> Shape such that regularPolygon n s is a regular polygon with n sides, each of length s. (Hint: consider using some of Haskell's trigonometric functions, such as sin :: Float -> Float, cos :: Float -> Float, and tan :: Float -> Float.) My idea is to start with the vertices (0,0) and (0,s). Then I ``connect a line'' from (0,0) to (0,s) and I then I need to compute the next vertex of the polygon. The angles of a regular polygon are alpha = ((n - 2) * pi)/n, where n is the number of sides of the polygon. So the third vertex of the polygon is x = cos (180 - alpha) * s y = sin (180 - alpha) * s, but I don't know how to teach the computer to get to the forth vertex. Once I figure that in a general way, I would just call myself until I get to the last vertex; if I start at n, we end at at n = 2 in which I return []. Something like: > data Shape = Polygon [Vertex] deriving Show > > type Side = Float > type Vertex = (Float, Float) > > regularPolygon :: Int -> Side -> Shape > regularPolygon n s = Polygon ((0,0) : (0,s) : buildList n s (fromIntegral n)) > where buildList :: Int -> Side -> Float -> [Vertex] > buildList 2 _ _ = [] > buildList n s m = let x = cos(pi - alpha) * s > y = sin(pi - alpha) * s > alpha = ((m - 2) * pi)/m > in (x,y) : buildList (n-1) s m but right now it just repeats all the vertices after the second. Any help is appreciated. From radoslawg at gmail.com Sun Aug 19 02:33:47 2007 From: radoslawg at gmail.com (=?UTF-8?Q?Rados=C5=82aw_Grzanka?=) Date: Sun Aug 19 02:25:10 2007 Subject: [Haskell-cafe] building a regular polygon In-Reply-To: References: Message-ID: <9d55dbaf0708182333l130bc95y4f7d604759cfcd8@mail.gmail.com> 2007/8/19, Daniel C. Bastos : > Any help is appreciated. I also had problem with this exercise. However this was more Haskell newbie problem :) If you're feeling lost you can always try google and come up with this blog with solutions to exercises from this book. You should find it helpful: http://www.elbeno.com/haskell_soe_blog/?p=7 Cheers, Radek. -- Codeside: http://codeside.org/ Przedszkole Miejskie nr 86 w Lodzi: http://www.pm86.pl/ From fb at frank-buss.de Sun Aug 19 03:09:31 2007 From: fb at frank-buss.de (Frank Buss) Date: Sun Aug 19 03:01:01 2007 Subject: [Haskell-cafe] building a regular polygon In-Reply-To: References: Message-ID: <070501c7e22f$e459d020$64c5a8c0@galilei> > (*) Exercise 2.2 > > Define a function regularPolygon :: Int -> Side -> Shape such that > regularPolygon n s is a regular polygon with n sides, each of length > s. (Hint: consider using some of Haskell's trigonometric > functions, such > as sin :: Float -> Float, cos :: Float -> Float, and tan :: Float -> > Float.) I'm a Haskell newbie, too, but I would use the angle between the line, which is defined from the point of orign to every corner of the polygon, and a coordinate axis. Then I would add some Postscript output for easier testing. http://www.frank-buss.de/tmp/polygons.png import System type Shape = [Vertex] type Side = Float type Vertex = (Float, Float) regularPolygon :: Int -> Side -> Shape regularPolygon n s = (buildList n) where buildList 0 = [] buildList i = let x = cos(alpha) * s y = sin(alpha) * s alpha = 2*pi/(fromIntegral n)*(fromIntegral i) in (x,y) : buildList (i-1) showVertex vertex = show (fst vertex) ++ " " ++ show (snd vertex) postscriptPolygon n s = (showVertex first ++ " moveto\n") ++ (unlines (map (\vertex -> (showVertex vertex ++ " lineto")) rest)) ++ (show (fst first) ++ " " ++ show (snd first) ++ " lineto") ++ "\n" where poly = regularPolygon n s first = head poly rest = tail poly main = do let file = "c:\\tmp\\test.ps" writeFile file ("20 20 scale 0.1 setlinewidth\n" ++ "5 5 translate\n" ++ (postscriptPolygon 4 4) ++ "8 4 translate\n" ++ (postscriptPolygon 7 2) ++ "stroke showpage\n") system ("c:\\Programme\\gs\\gs8.15\\bin\\gswin32.exe -g500x500 " ++ file) -- Frank Buss, fb@frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From matthew at wellquite.org Sat Aug 18 18:39:37 2007 From: matthew at wellquite.org (Matthew Sackman) Date: Sun Aug 19 05:18:07 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: <396556a20708181047y3226f12am9f351421ad61dfd5@mail.gmail.com> References: <20070818191505.A5E693245F3@www.haskell.org> Message-ID: <20070818223937.GA31882@wellquite.org> Adam Langley mused: > On 8/18/07, Peter Cai wrote: > > As the old version of this component is written in C, it's very natural that > > this protocol is base on C structure definitions, which are, unfortunately, > > very complicated. And the worse is that every field in every structure must > > be converted to Network Endian. > > You could certainly try Data.Binary[1] for this. It has a nice Get > monad with methods such as getWord32be which sounds like it might be > what you want. One caveat is that it's fully lazy - you get the result > immediately and parse errors can only be caught as exceptions when you > actually come to using the result. This is perfect for very large > messages, but might be slightly wrong for you. Also, one thing to watch out for is the fact the existing Get and Put instances may not do anything like what you expect. For example, for some reason I expected that the instances of Get and Put for Float and Double would send across the wire Floats and Doubles in IEEE floating point standard. How wrong I was... But in general yes, Data.Binary is pretty useful for doing network protocols. Matthew From ndmitchell at gmail.com Sun Aug 19 06:54:03 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Sun Aug 19 06:45:31 2007 Subject: [Haskell-cafe] List comprehension desugaring Message-ID: <404396ef0708190354mb1a2c9el7f966691680c7273@mail.gmail.com> Hi, The Haskell desugaring for list comprehensions is given in: http://haskell.org/onlinereport/exps.html#list-comprehensions All the rules seem to be left to right rewrites, apart from the second one, which seems to be right to left. Is there some deep reason for this, or is this accidental. Thanks Neil From ndmitchell at gmail.com Sun Aug 19 06:57:26 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Sun Aug 19 06:48:48 2007 Subject: [Haskell-cafe] Re: List comprehension desugaring In-Reply-To: <404396ef0708190354mb1a2c9el7f966691680c7273@mail.gmail.com> References: <404396ef0708190354mb1a2c9el7f966691680c7273@mail.gmail.com> Message-ID: <404396ef0708190357i7813da7fhc261eae89d2119fb@mail.gmail.com> Hi Sorry for the noise, I've now realised they are a left to right rewrite system, the second rule is required to set up the base case. Thanks Neil On 8/19/07, Neil Mitchell wrote: > Hi, > > The Haskell desugaring for list comprehensions is given in: > > http://haskell.org/onlinereport/exps.html#list-comprehensions > > All the rules seem to be left to right rewrites, apart from the second > one, which seems to be right to left. Is there some deep reason for > this, or is this accidental. > > Thanks > > Neil > From alistair at abayley.org Sun Aug 19 07:44:04 2007 From: alistair at abayley.org (Alistair Bayley) Date: Sun Aug 19 07:35:26 2007 Subject: [Haskell-cafe] Re: Error building takusen with Cabal-1.1.6.2 In-Reply-To: References: Message-ID: <79d7c4980708190444y169a29dfm875b42c9c4fb009@mail.gmail.com> > > Setup.hs:13:7: > > Could not find module `Distribution.Compat.FilePath': > > it is hidden (in package Cabal-1.1.6.2) > > This is what I did to make takusen build with ghc-6.6.1: > > ben@sarun: .../haskell/takusen_0 > darcs whatsnew > { > hunk ./Setup.hs 13 > -import Distribution.Compat.FilePath (splitFileName, joinPaths)^M$ > +import System.FilePath (splitFileName, combine)^M$ > hunk ./Setup.hs 124 > - libDirs <- canonicalizePath (joinPaths path libDir)^M$ > - includeDirs <- canonicalizePath (joinPaths path includeDir)^M$ > + libDirs <- canonicalizePath (combine path libDir)^M$ > + includeDirs <- canonicalizePath (combine path includeDir)^M$ > } > > HTH > Ben I've pushed changes to the Setup scripts (and the README.txt) in the darcs report so that it should build out-of-the-box. Just pull the latest code. However, I'm off on holiday (more-or-less unaccessable) for a couple of weeks on Monday, so if I've busted it badly, I apologize in advance. Alistair From andrewcoppin at btinternet.com Sun Aug 19 07:53:07 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sun Aug 19 07:43:39 2007 Subject: [Haskell-cafe] GHC optimisations Message-ID: <46C82F23.9020509@btinternet.com> Does GHC do stuff like converting (2*) into (shift 1) or converting x + x into 2*x? If I do x * sin 12, is GHC likely to compute sin 12 at compile-time? From misc at alpheccar.org Sun Aug 19 08:37:50 2007 From: misc at alpheccar.org (alpheccar) Date: Sun Aug 19 08:26:57 2007 Subject: [Haskell-cafe] Using Apple Spotlight to search for .hs and .lhs files In-Reply-To: <625b74080708181738t6ed1d69n1cbba4dd2e7071bd@mail.gmail.com> References: <625b74080708181738t6ed1d69n1cbba4dd2e7071bd@mail.gmail.com> Message-ID: Since it is not really Haskell related, I have answered by email. If anyone is interested, don't hesitate to email me. alpheccar. > This isn't really a Haskell question but I'm guessing some Haskell > hackers have a solution. MacOS X's Spotlight doesn't seem to be able > to search for text in .lhs and .hs files. But it can find text in .txt > files. Is there a way of getting Spotlight to treat .lhs and .hs files > like .txt files so I can instantly search all of my Haskell source? > -- > Dan > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From apfelmus at quantentunnel.de Sun Aug 19 08:38:13 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Sun Aug 19 08:29:42 2007 Subject: [Haskell-cafe] Re: List comprehension desugaring In-Reply-To: <404396ef0708190354mb1a2c9el7f966691680c7273@mail.gmail.com> References: <404396ef0708190354mb1a2c9el7f966691680c7273@mail.gmail.com> Message-ID: Neil Mitchell wrote: > The Haskell desugaring for list comprehensions is given in: > > http://haskell.org/onlinereport/exps.html#list-comprehensions > > All the rules seem to be left to right rewrites, apart from the second > one, which seems to be right to left. Is there some deep reason for > this, or is this accidental. Isn't the second rule left to right, too? The translation assumes that Q is non-empty, so the three last rules don't match [e | q] but they match [e | q, True]. The non-emptiness is probably for ruling out the invalid list comprehension [e | ] which would otherwise appear as an intermediate result in the translation for empty Q. Regards, apfelmus From bertram.felgenhauer at googlemail.com Sun Aug 19 10:17:47 2007 From: bertram.felgenhauer at googlemail.com (Bertram Felgenhauer) Date: Sun Aug 19 10:09:18 2007 Subject: [Haskell-cafe] Re: How do I simulate dependent types using phantom types? In-Reply-To: References: <46C74A96.4080107@gmail.com> Message-ID: <20070819141747.GA4587@zombie.inf.tu-dresden.de> DavidA wrote: > Twan van Laarhoven gmail.com> writes: > > The solution is to use a dummy parameter: > > > class IntegerType a where > > > value :: a -> Integer > > Thanks to all respondents for this suggestion. That works great. I prefer a slightly elaborate way, > newtype Mark n t = Mark t > -- provide conversion from and to dummy functions because they are > -- much more convenient to use. > toDummy :: Mark n t -> n -> t > toDummy (Mark x) _ = x > fromDummy :: (n -> t) -> Mark n t > fromDummy f = Mark (f undefined) > class Natural a where > value' :: Mark a Integer > value :: Natural a => a -> Integer > value = toDummy value' The advantage of this approach is that the 'Natural' class dictionary contains a constant Integer value, not some function that the compiler doesn't know anything about. This makes no difference for simple uses, but once you define type level natural numbers, like > data Zero = Zero > newtype D0 a = D0 a > newtype D1 a = D1 a with instances, > instance Natural Zero where > value' = Mark 0 > instance Natural a => Natural (D0 a) where > value' = fromDummy (\(D0 d) -> value d * 2) > instance Natural a => Natural (D1 a) where > value' = fromDummy (\(D1 d) -> value d * 2 + 1) you get an actual speedup at runtime, because the value represented by the type is passed directly in the class dictionary and doesn't have to be recomputed each time "value" is called. (Note: it *is* possible to share intermediate results even with dummy functions, but I got a significant speed boost in my modular arithmetic code with this trick anyway.) This also opens up a *naughty* way to construct such phantom types in GHC. When I say "naughty" I mean it - use this code at your own risk. > -- Or is this reify? I'm confused about the convention here. > reflect :: Integer -> (forall n . Nat n => Mark n a) -> a > reflect = flip unsafeCoerce which can be used like this: *Test> reflect 42 value' 42 *Test> reflect 7 (fromDummy (\d -> value d * 6)) 42 It is an interesting exercise to implement reflect :: Integer -> (forall n . Nat n => Mark n a) -> a using Zero, D0 and D1 :) Bertram From benjamin.franksen at bessy.de Sun Aug 19 10:59:47 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Sun Aug 19 10:51:21 2007 Subject: [Haskell-cafe] Using Collections: ElemsView and KeysView Message-ID: Hi I am using collections-0.3 and need to perform some operations on keys resp. values of a map. In the concrete implementations there are functions like 'elems' and 'keys' but there is no such thing in Data.Collections. Instead there are the types 'ElemsView' and 'KeysView' and functions 'withElems' and 'withKeys', but I have not the slightest idea how they are supposed to be used, there is very sparse documentation and no examples. I'd be glad for any hints. Cheers Ben From agl at imperialviolet.org Sun Aug 19 12:08:12 2007 From: agl at imperialviolet.org (Adam Langley) Date: Sun Aug 19 11:59:33 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: <20070818223937.GA31882@wellquite.org> References: <20070818191505.A5E693245F3@www.haskell.org> <396556a20708181047y3226f12am9f351421ad61dfd5@mail.gmail.com> <20070818223937.GA31882@wellquite.org> Message-ID: <396556a20708190908n42f53902y18bc666bfe551be0@mail.gmail.com> On 8/18/07, Matthew Sackman wrote: > Also, one thing to watch out for is the fact the existing Get and Put > instances may not do anything like what you expect. For example, for > some reason I expected that the instances of Get and Put for Float and > Double would send across the wire Floats and Doubles in IEEE floating > point standard. How wrong I was... Ah, those aren't instances of Get and Put, but of Binary[1]. You use the Binary instances via the functions 'get' and 'put' (case is important). Get and Put provide actions like "putWord32be", for which the resulting bits are pretty much universally accepted. Binary has default instances which uses Get and Put to serialise Haskell types like [Int], or (Float, Float). Here the resulting bits aren't documented, but you can read the code and I have some C code for dealing with them somewhere if anyone is interrested. The serialisation of Float is, indeed, nothing like IEEE in either endianness. (* and, although Get isn't currently a class, I have sent patches to dons to make it so, with a default instance which matches current behaviour and speed, and an alternative which returns a Maybe, removing a little bit of lazyness in cases where you want to handle parse failures in pure code. Hopefully something will happen with this at the next sprint ;) ) [1] http://www.cse.unsw.edu.au/~dons/binary/Data-Binary.html#1 -- Adam Langley agl@imperialviolet.org http://www.imperialviolet.org 650-283-9641 From catamorphism at gmail.com Sun Aug 19 13:48:32 2007 From: catamorphism at gmail.com (Tim Chevalier) Date: Sun Aug 19 13:39:54 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46C82F23.9020509@btinternet.com> References: <46C82F23.9020509@btinternet.com> Message-ID: <4683d9370708191048w319b9ca2u2802c434e285b977@mail.gmail.com> On 8/19/07, Andrew Coppin wrote: > Does GHC do stuff like converting (2*) into (shift 1) or converting x + > x into 2*x? > Hmm, that's an interesting architecture where multiplication is cheaper than addition :-) > If I do x * sin 12, is GHC likely to compute sin 12 at compile-time? > I seriously doubt it, but there's an easy way to find out the answer to all these questions: pass the -ddump-simpl flag to GHC so that it prints out the intermediate code it generates. There's some information in the users' guide about how to read the results. Cheers, Tim -- Tim Chevalier * catamorphism.org * Often in error, never in doubt "I always wanted to be commander-in-chief of my own one-woman army" -- Ani DiFranco From stefanor at cox.net Sun Aug 19 15:14:20 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sun Aug 19 15:05:42 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46C82F23.9020509@btinternet.com> References: <46C82F23.9020509@btinternet.com> Message-ID: <20070819191420.GA3019@localhost.localdomain> On Sun, Aug 19, 2007 at 12:53:07PM +0100, Andrew Coppin wrote: > Does GHC do stuff like converting (2*) into (shift 1) or converting x + x > into 2*x? For a good time, compile some code which uses even or odd :: Int -> Bool using -O2 -fasm -ddump-asm... The compiler *really* shouldn't be using 'idivl'. (If you use -fvia-C -optc-O2, the C compiler will notice the operations and optimize it itself. This is one of the very few areas where -fvia-C is still better.) > If I do x * sin 12, is GHC likely to compute sin 12 at compile-time? Also try -ddump-simpl-stats and -ddump-simpl-iterations if you want to know *why*. (The extremely obscure 'full laziness' transformation performed by GHC has a fundamental effect on the compilation of x * sin 12...) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070819/a6e9f645/attachment.bin From bf3 at telenet.be Sun Aug 19 15:11:56 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sun Aug 19 15:06:01 2007 Subject: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <1187463267.5462.22.camel@derek-laptop> References: <000101c7e1c6$8724d260$956e7720$@be> <1187463267.5462.22.camel@derek-laptop> Message-ID: <000101c7e294$cf3d3280$6db79780$@be> Thanks. I got confused because the StackOverflow link on http://www.haskell.org/haskellwiki/HaWiki_migration is dead. -----Original Message----- From: Derek Elkins [mailto:derek.a.elkins@gmail.com] Sent: Saturday, August 18, 2007 8:54 PM To: Peter Verswyvelen Cc: haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? On Sat, 2007-08-18 at 20:35 +0200, Peter Verswyvelen wrote: > When reading an article about tail recursion > (http://themechanicalbride.blogspot.com/2007/04/haskell-for-c-3-programmers. > html) I came across the follow statements: > > "If you can write a non-recursive function that uses the colon syntax it is > probably better than a tail recursive one that doesn't. This is because > Haskell's lazy evaluation enabled you to use the non-tail recursive version > on an infinite stream without getting a stack overflow. " > > and > > ""Unfortunately", laziness "gets in the way". While transforming > non-tail-recursive code to a tail-recursive form is important and useful for > functional programming in general, dealing with laziness requires a little > more care, and often "non-tail-recursive" versions are preferrable. flatten > is an example of this, the first version is better in many ways. While I > don't believe it happens in this case, oftentimes naively writing code > "tail-recursively" in Haskell will actually -make- it overflow the stack. > Another (actual) benefit of the first version of flatten is that it will > work on infinite lists. http://www.haskell.org/hawiki/StackOverflow gives a > simple example and some explanation." That page was migrated here: http://www.haskell.org/haskellwiki/Stack_overflow From lemming at henning-thielemann.de Sun Aug 19 16:52:44 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sun Aug 19 16:44:06 2007 Subject: [Haskell-cafe] Re: Interval Arithmetics Message-ID: The page http://www.haskell.org/haskellwiki/Applications_and_libraries/Mathematics#Number_representations lists several implementations of several flavours of computable reals, which may be useful for you. From almeidaraf at gmail.com Sun Aug 19 17:03:42 2007 From: almeidaraf at gmail.com (Rafael Almeida) Date: Sun Aug 19 16:55:05 2007 Subject: [Haskell-cafe] building a regular polygon In-Reply-To: <070501c7e22f$e459d020$64c5a8c0@galilei> References: <070501c7e22f$e459d020$64c5a8c0@galilei> Message-ID: <6de6b1650708191403p62e3e727v5240a2dd9a8bb378@mail.gmail.com> On 8/19/07, Frank Buss wrote: > > (*) Exercise 2.2 > > > > Define a function regularPolygon :: Int -> Side -> Shape such that > > regularPolygon n s is a regular polygon with n sides, each of length > > s. (Hint: consider using some of Haskell's trigonometric > > functions, such > > as sin :: Float -> Float, cos :: Float -> Float, and tan :: Float -> > > Float.) > import System > > type Shape = [Vertex] > type Side = Float > type Vertex = (Float, Float) > > regularPolygon :: Int -> Side -> Shape > regularPolygon n s = (buildList n) > where buildList 0 = [] > buildList i = let x = cos(alpha) * s > y = sin(alpha) * s > alpha = 2*pi/(fromIntegral n)*(fromIntegral i) > in (x,y) : buildList (i-1) That looks good, but I'd do like this: regularPolygon :: Int -> Side -> Shape regularPolygon n s = (buildList n) where buildList 0 = [] buildList i = let x = cos(alpha) * r y = sin(alpha) * r alpha = 2*(fromIntegral i)*pi / fromIntegral n r = sqrt (s^2 / (2*(1 - cos (2*pi / fromIntegral n)))) in (x,y) : buildList (i-1) I used the cosine law in order to calculate r. After all, s is actually the size of the side of the polygon and not the distance of its vertices from the origin. From luc.taesch at googlemail.com Sun Aug 19 17:19:46 2007 From: luc.taesch at googlemail.com (Luc TAESCH) Date: Sun Aug 19 17:11:09 2007 Subject: [Haskell-cafe] IO in HApps handler ? In-Reply-To: References: Message-ID: <1be091cf0708191419m6ffd2d5br484a8a27b44f909f@mail.gmail.com> Subject: IO in HApps handler ? I am trying to add a handler that would run an external command in HApps 0.8.8, and I got a type issue I do not know how to get around.. can we have IO in a handler ? testcmdpost.hs:52:8: Couldn't match expected type `Ev st Request' against inferred type `IO' Expected type: ServerPart (Ev st Request) Request IO Result Inferred type: ServerPart IO Request im Result In the expression: (h ["xxx"] GET) $ (ok $ (\ () () -> do (MySt val) <- get runCommand "ls" ["."] respond (show "dfdf"))) here is the handler iI am adding : ,h ["xxx"] GET $ ok $ \() () -> do (MySt val) <- get; runCommand "ls" ["."]; respond (show "dfdf" ) in there : import HAppS.Util.Common... ... main :: IO () main = stdHTTP [debugFilter -- we want to see debug messages in the console ,h [""] GET $ ok $ val "GETting root hello" -- ,h (Prefix ["s"]) GET $ respIO $ fileServe staticPath , hs (Prefix ["s"]) GET $ basicFileServe staticPath -- 0.8.8 -- /val shows us the current value ,h ["val"] GET $ ok $ \() () -> do (MySt val) <- get; respond (show val) -- /set with the POST data "val"=56 would set the value to 56 ,h ["xxx"] GET $ ok $ \() () -> do (MySt val) <- get; runCommand "ls" ["."]; respond (show "dfdf" ) ,h ["set"] POST $ ok $ \() newVal -> do put newVal; respond ("New value is " ++ show newVal) -- The first one is FromReqURI and the second one is FromMessage -- The cryptic comment about is referring to the arguments () and newVal -- to the method. The type of newVal being MyState is what -- invokes our custom FromMessage instance above. ] this is the runcommand from HAppS.Util.Common , not from defined as -- | Run an external command. Upon failure print status -- to stderr. runCommand :: String -> [String] -> IO () runCommand cmd args = do (_, outP, errP, pid) <- runInteractiveProcess cmd args Nothing Nothing let pGetContents h = do mv <- newEmptyMVar let put [] = putMVar mv [] put xs = last xs `seq` putMVar mv xs forkIO (hGetContents h >>= put) takeMVar mv os <- pGetContents outP es <- pGetContents errP ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure e -> do hPutStrLn stderr ("Running process "++unwords (cmd:args)++" FAILED ("++show e++")") hPutStrLn stderr os hPutStrLn stderr es hPutStrLn stderr ("Raising error...") fail "Running external command failed" From luc.taesch at googlemail.com Sun Aug 19 17:20:52 2007 From: luc.taesch at googlemail.com (Luc TAESCH) Date: Sun Aug 19 17:12:14 2007 Subject: [Haskell-cafe] ghc 6.7 /6.8 In-Reply-To: References: Message-ID: <1be091cf0708191420n2cbb5337j5f0740942119331f@mail.gmail.com> Date: Sun, 19 Aug 2007 12:39:50 +0200 Subject: Fwd: ghc 6.7 /6.8 hello. will 6.7 be released, or will only 6.8 be ? ( i.e do you use an even/uneven relesing number convention) -in that case, does the 6.8 branch means the freeze is on, and what would be the target for 6.8 ? Q3/2007 ? Q4 ? ( context: I am impatient to test the new debbuger, but too newby to go and fix all the lib..hoping it may help me undertand haskell execution.. ) From matthew at wellquite.org Sun Aug 19 17:26:55 2007 From: matthew at wellquite.org (Matthew Sackman) Date: Sun Aug 19 17:18:28 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: <396556a20708190908n42f53902y18bc666bfe551be0@mail.gmail.com> References: <20070819205512.1EBAE324405@www.haskell.org> Message-ID: <20070819212655.GA21509@wellquite.org> Recently, Adam Langley responded so: > On 8/18/07, Matthew Sackman wrote: > > Also, one thing to watch out for is the fact the existing Get and Put > > instances may not do anything like what you expect. For example, for > > some reason I expected that the instances of Get and Put for Float and > > Double would send across the wire Floats and Doubles in IEEE floating > > point standard. How wrong I was... > > Ah, those aren't instances of Get and Put, but of Binary[1]. You use > the Binary instances via the functions 'get' and 'put' (case is > important). Gah, that'll teach me to post from memory without checking the code. Indeed, that is what I meant, the instances of Binary. > Get and Put provide actions like "putWord32be", for which the > resulting bits are pretty much universally accepted. Binary has > default instances which uses Get and Put to serialise Haskell types > like [Int], or (Float, Float). Here the resulting bits aren't > documented, but you can read the code and I have some C code for > dealing with them somewhere if anyone is interrested. The > serialisation of Float is, indeed, nothing like IEEE in either > endianness. Quite. Whilst we're on the subject (and I realise I might be hijacking this thread a little), it does seem rather odd that it's very easy to take a Word8/16/32/64 and interpret it as an integer. Similarly, it's very easy to take an integer and convert it to a Word of some sort. But it's vastly harder to do that for floats / non-integers. Now I know that the number classes in the Prelude are basically broken anyway and all really need rewriting, but it does seem completely arbitrary that Words somehow are only allowed to contain whole numbers! Matthew From ndmitchell at gmail.com Sun Aug 19 17:38:23 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Sun Aug 19 17:29:44 2007 Subject: [Haskell-cafe] ghc 6.7 /6.8 In-Reply-To: <1be091cf0708191420n2cbb5337j5f0740942119331f@mail.gmail.com> References: <1be091cf0708191420n2cbb5337j5f0740942119331f@mail.gmail.com> Message-ID: <404396ef0708191438u56b4a493yb262b758fbab0059@mail.gmail.com> Hi > will 6.7 be released, or will only 6.8 be ? 6.7 is the HEAD branch, 6.8 will be released. > -in that case, does the 6.8 branch means the freeze is on, and what would be > the target for 6.8 ? Q3/2007 ? Q4 ? Soon, in the next month - according to latest targets/estimates. > ( context: I am impatient to test the new debbuger, but too newby to go and > fix all the lib..hoping it may help me undertand haskell execution.. ) The new debugger looks dead cool, I can't wait for it either! Thanks Neil From haskell at list.mightyreason.com Sun Aug 19 18:25:49 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Sun Aug 19 18:17:28 2007 Subject: [Haskell-cafe] Re: trouble compiling "import GHC.Prim(MutableByteArray#, ....." (building regex-tdfa from darcs) -- what's that # sign doing? In-Reply-To: <20070817204757.GA3775@localhost.localdomain> References: <20070817204757.GA3775@localhost.localdomain> Message-ID: <46C8C36D.3050701@list.mightyreason.com> Stefan O'Rear wrote: > On Fri, Aug 17, 2007 at 04:27:29PM -0400, Thomas Hartman wrote: >> trying to compile regex-tdfa, I ran into another issue. (earlier I had a >> cabal problem but that's resolved.) >> >> there's a line that won't compile, neither for ghc 6.6.1 nor 6.7 >> >> import >> GHC.Prim(MutableByteArray#,RealWorld,Int#,sizeofMutableByteArray#,unsafeCoerce#) >> >> so the fresh darcs regex tdfa package won't build. >> >> This line (line 16 below) causes this error for >> >> ghc -e '' RunMutState.hs >> >> for both ghc 6.1 and 6.7 > > There are at least two things going on here. > > 1. GHC-specific unboxed identifiers have a # in the name. I think this > is a relic from back when the only reasonable way to namespace was to > modify your compiler to add extra identifier characters, and use them > in all non-portable identifiers. In any case, you have to enable the > -fglasgow-exts option (or -XMagicHash in recent 6.7) to allow imports > of such identifiers. > > 2. Explicitly importing GHC.Prim has been discouraged for as long as I > can remember, and GHC HQ has finally made good on the promise to make > it impossible. Code which imports it has a bug already, which can be > fixed by switching to GHC.Exts. (Why? GHC.Prim is wired into the > compiler, while GHC.Exts is a normal Haskell module, so by using > GHC.Exts you are insulated from questions of what is primitive and > what is derived but still unportable. Yes, this does change.) > > Stefan > > Hi, I wrote regex-tdfa, and since I don't use beyond GHC 6.6.1 I had not seen this problem emerge. The use of GHC.Prim and CPP is intimitely linked: from http://darcs.haskell.org/packages/regex-unstable/regex-tdfa/Text/Regex/TDFA/RunMutState.hs > > #ifdef __GLASGOW_HASKELL__ > foreign import ccall unsafe "memcpy" > memcpy :: MutableByteArray# RealWorld -> MutableByteArray# RealWorld -> Int# -> IO () > > {-# INLINE copySTU #-} > copySTU :: (Show i,Ix i,MArray (STUArray s) e (ST s)) => STUArray s i e -> STUArray s i e -> ST s () > copySTU (STUArray _ _ msource) (STUArray _ _ mdest) = > -- do b1 <- getBounds s1 > -- b2 <- getBounds s2 > -- when (b1/=b2) (error ("\n\nWTF copySTU: "++show (b1,b2))) > ST $ \s1# -> > case sizeofMutableByteArray# msource of { n# -> > case unsafeCoerce# memcpy mdest msource n# s1# of { (# s2#, () #) -> > (# s2#, () #) }} > > #else /* !__GLASGOW_HASKELL__ */ > > copySTU :: (MArray (STUArray s) e (ST s))=> STUArray s Tag e -> STUArray s Tag e -> ST s () > copySTU source destination = do > b@(start,stop) <- getBounds source > b' <- getBounds destination > -- traceCopy ("> copySTArray "++show b) $ do > when (b/=b') (fail $ "Text.Regex.TDFA.RunMutState copySTUArray bounds mismatch"++show (b,b')) > forM_ (range b) $ \index -> > unsafeRead source index >>= unsafeWrite destination index > #endif /* !__GLASGOW_HASKELL__ */ The entire point of using the ST monad is manage memory more efficiently than with (U)Array. The copySTU simply uses a "memcpy" to copy the whole source array into the destination efficiently. This lets me re-use the already allocated destination array. If there had been a high level "copyMArray" then this would not have been needed. The CPP is used to let non-GHC compilers copy element by element. The *right* solution is to patch the STUArray and/or MArray code to do this behind the scenes. So how does one get the array pointer without GHC.Prim in 6.7 ? -- Chris From stefanor at cox.net Sun Aug 19 18:53:53 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sun Aug 19 18:45:15 2007 Subject: [Haskell-cafe] Re: trouble compiling "import GHC.Prim(MutableByteArray#, ....." (building regex-tdfa from darcs) -- what's that # sign doing? In-Reply-To: <46C8C36D.3050701@list.mightyreason.com> References: <20070817204757.GA3775@localhost.localdomain> <46C8C36D.3050701@list.mightyreason.com> Message-ID: <20070819225353.GA3651@localhost.localdomain> On Sun, Aug 19, 2007 at 11:25:49PM +0100, ChrisK wrote: > > #ifdef __GLASGOW_HASKELL__ > > foreign import ccall unsafe "memcpy" > > memcpy :: MutableByteArray# RealWorld -> MutableByteArray# RealWorld -> Int# -> IO () > > > > {-# INLINE copySTU #-} > > copySTU :: (Show i,Ix i,MArray (STUArray s) e (ST s)) => STUArray s i e -> STUArray s i e -> ST s () > > copySTU (STUArray _ _ msource) (STUArray _ _ mdest) = > > -- do b1 <- getBounds s1 > > -- b2 <- getBounds s2 > > -- when (b1/=b2) (error ("\n\nWTF copySTU: "++show (b1,b2))) > > ST $ \s1# -> > > case sizeofMutableByteArray# msource of { n# -> > > case unsafeCoerce# memcpy mdest msource n# s1# of { (# s2#, () #) -> > > (# s2#, () #) }} > > > > #else /* !__GLASGOW_HASKELL__ */ > > > > copySTU :: (MArray (STUArray s) e (ST s))=> STUArray s Tag e -> STUArray s Tag e -> ST s () > > copySTU source destination = do > > b@(start,stop) <- getBounds source > > b' <- getBounds destination > > -- traceCopy ("> copySTArray "++show b) $ do > > when (b/=b') (fail $ "Text.Regex.TDFA.RunMutState copySTUArray bounds mismatch"++show (b,b')) > > forM_ (range b) $ \index -> > > unsafeRead source index >>= unsafeWrite destination index > > #endif /* !__GLASGOW_HASKELL__ */ > > The entire point of using the ST monad is manage memory more efficiently than > with (U)Array. The copySTU simply uses a "memcpy" to copy the whole source > array into the destination efficiently. This lets me re-use the already > allocated destination array. If there had been a high level "copyMArray" then > this would not have been needed. The CPP is used to let non-GHC compilers copy > element by element. The *right* solution is to patch the STUArray and/or MArray > code to do this behind the scenes. > > So how does one get the array pointer without GHC.Prim in 6.7 ? Import GHC.Exts, which exports everything GHC.Prim does, and according to the docs is "GHC Extensions: this is the Approved Way to get at GHC-specific extensions.". (Can't help you with the CPP issue though.) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070819/9501bc5f/attachment.bin From wagner.andrew at gmail.com Sun Aug 19 18:55:45 2007 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Sun Aug 19 18:47:06 2007 Subject: [Haskell-cafe] Bi-directional Maps Message-ID: Hi folks! So, in writing my chess engine, I've been trying to maintain 2 Map objects. One maps squares on the board to Ints, the other maps Ints to actual Pieces. It occurred to me that it would be useful to explicitly have a Bi-directional Map, which does the maintenance of keeping the Maps synchronized behind the scenes. Thus, Bimap was born! I've taken the API for Data.Map (which you can find at ), and cannibalized it for Bimap. The new API is at http://hpaste.org/2344 . The idea is that if you have a Bimap k a, and you want to treat the k's as keys, and use a function like Data.Map.foo, it will be called Data.Map.left_foo in Bimap. And if they want to do the same thing, but using the a's as keys, then they simply use right_foo. The metaphor is that we can view it as a Map in 2 directions, manipulating it from the left (on the k's), or from the right (on the a's). Is this useful? Is there a better way? Is the API too big, and if so, how can it be pared down? From fb at frank-buss.de Sun Aug 19 19:12:57 2007 From: fb at frank-buss.de (Frank Buss) Date: Sun Aug 19 19:04:27 2007 Subject: [Haskell-cafe] building a regular polygon In-Reply-To: <6de6b1650708191403p62e3e727v5240a2dd9a8bb378@mail.gmail.com> References: <070501c7e22f$e459d020$64c5a8c0@galilei> <6de6b1650708191403p62e3e727v5240a2dd9a8bb378@mail.gmail.com> Message-ID: <08a001c7e2b6$7b58a240$64c5a8c0@galilei> > From: Rafael Almeida [mailto:almeidaraf@gmail.com] > > I used the cosine law in order to calculate r. After all, s is > actually the size of the side of the polygon and not the distance of > its vertices from the origin. You are right, my solution was wrong. If you don't mind rounding errors, this is another solution: import List regularPolygon n s = iteratedAdd segments where a = 2 * pi / (fromIntegral n) segments = [rotatedSegment (fromIntegral i) | i <- [0..n-1]] rotatedSegment i = (s*sin(i*a),s*cos(i*a)) iteratedAdd = snd . mapAccumR (\s x->(add s x, add s x)) (0,0) add (x1,y1) (x2,y2) = (x1+x2,y1+y2) With this list comprehension, your solution could be written like this: regularPolygon n s = [(r * cos(a i), r * sin(a i)) | i <- [0..n-1]] where a i = 2 * fromIntegral i * pi / fromIntegral n r = sqrt(s^2 / (2 * (1 - cos(2 * pi / fromIntegral n)))) -- Frank Buss, fb@frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From marco-oweber at gmx.de Sun Aug 19 20:10:54 2007 From: marco-oweber at gmx.de (Marc Weber) Date: Sun Aug 19 20:02:21 2007 Subject: [Haskell-cafe] IO in HApps handler ? In-Reply-To: <1be091cf0708191419m6ffd2d5br484a8a27b44f909f@mail.gmail.com> References: <1be091cf0708191419m6ffd2d5br484a8a27b44f909f@mail.gmail.com> Message-ID: <20070820001054.GA27648@gmx.de> Hi TAESCH, THat's what haskell is good for. It prevents you from doing unsafe things by accident. You must get the source and have a look at the definition of the Ev type: (module HAppS.MACID.Types where:) (Not sure wether this code is most recent or not (Version: 0.8.8)) ============= ======================================================= [...] data Env st ev = Env { -- | Read only event. evEvent :: TxContext ev, -- | State, can be used with get and put. evState :: MutVar st, -- | Internal. List of side effects. evSideEffects :: MutVar [(Seconds, IO ())], -- | Internal. Used to signal completion of background IO. evBackgroundIOCompletion :: IO (), -- | Internal. Random numbers that should be used. evRandoms :: MutVar StdGen -- -- | Internal. New event generation. -- evCreateEvent :: ev -> IO () } type TxId = Int64 type EpochTime = Int64 type Seconds = Int instance Typeable StdGen where typeOf _ = undefined -- !! for default serial data TxContext evt = TxContext { txId :: TxId, txTime :: EpochTime, txStdGen :: StdGen, txEvent :: evt } deriving (Read,Show,Typeable) -- | ACID computations that work with any state and event types. type AnyEv a = forall state event. Ev state event a -- | Monad for ACID event handlers. newtype Ev state event t = Ev { unEv :: Env state event -> STM t } -- unsafe lifting unsafeIOToEv :: IO a -> AnyEv a unsafeIOToEv c = Ev $ \_ -> unsafeIOToSTM c unsafeSTMToEv :: STM a -> AnyEv a unsafeSTMToEv c = Ev $ \_ -> c unsafeIOToSTM :: IO a -> STM a unsafeIOToSTM = GHC.Conc.unsafeIOToSTM [...] ============= ======================================================= Now have a look at the line newtype Ev state event t = Ev { unEv :: Env state event -> STM t } which shows that you have some kind of state passed (Env state event) which results in STM t ) The next thing is having a look at either Env or STM.. data Env st ev = Env { [...] evBackgroundIOCompletion :: IO (), shows that an IO may be passed, which must be transformed into STM somehow: Yeah. STM permits this newtype STM a = STM (IORef (IO ()) -> IO a) this ( lifting an IO action into a different monad) is called lift(IO) most of the time.. and as you can see theere are some transformers defined: unsafeIOToEv :: IO a -> AnyEv a unsafeIOToEv c = Ev $ \_ -> unsafeIOToSTM c unsafeSTMToEv :: STM a -> AnyEv a unsafeSTMToEv c = Ev $ \_ -> c unsafeIOToSTM :: IO a -> STM a unsafeIOToSTM = GHC.Conc.unsafeIOToSTM But why they are called unsafe etc you should ask people familiar with HaPPS and its design.. But at least you can now use grep or google to see wether you can find some more info on those unsafe functions HTH Marc From newsham at lava.net Sun Aug 19 22:50:47 2007 From: newsham at lava.net (Tim Newsham) Date: Sun Aug 19 22:42:08 2007 Subject: [Haskell-cafe] IO in HApps handler ? In-Reply-To: <1be091cf0708191419m6ffd2d5br484a8a27b44f909f@mail.gmail.com> References: <1be091cf0708191419m6ffd2d5br484a8a27b44f909f@mail.gmail.com> Message-ID: > Subject: IO in HApps handler ? > I am trying to add a handler that would run an external command in > HApps 0.8.8, and I got a type issue I do not know how to get around.. > > can we have IO in a handler ? http://www.haskell.org/haskellwiki/HAppS_tutorial#Application "The MACID monad lets you update your state and *schedule* side-effects. To be clear, MACID is not in the IO monad so you cannot execute side effects, you can only schedule them. The framework takes care of making sure they are executed at-least-once (if they can be completed by a deadline you specify)." I don't know the specifics. Tim Newsham http://www.thenewsh.com/~newsham/ From apfelmus at quantentunnel.de Mon Aug 20 03:55:58 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Mon Aug 20 03:47:21 2007 Subject: [Haskell-cafe] Re: Bi-directional Maps In-Reply-To: References: Message-ID: Andrew Wagner wrote: > So, in writing my chess engine, I've been trying to maintain 2 Map > objects. One maps squares on the board to Ints, the other maps Ints to > actual Pieces. It occurred to me that it would be useful to explicitly > have a Bi-directional Map, which does the maintenance of keeping the > Maps synchronized behind the scenes. Thus, Bimap was born! I've taken > the API for Data.Map (which you can find at ), and cannibalized it for > Bimap. The new API is at http://hpaste.org/2344 . The idea is that if > you have a Bimap k a, and you want to treat the k's as keys, and use a > function like Data.Map.foo, it will be called Data.Map.left_foo in > Bimap. And if they want to do the same thing, but using the a's as > keys, then they simply use right_foo. The metaphor is that we can view > it as a Map in 2 directions, manipulating it from the left (on the > k's), or from the right (on the a's). > > Is this useful? Is there a better way? Is the API too big, and if so, > how can it be pared down? IMHO, the API is too big and not beautiful enough. How about a function flip :: Bimap a b -> Bimap b a that interchanges the role of keys and values? Or maybe keep every functions symmetric in a and b , like in update :: ((a,b) -> Maybe (a,b)) -> Either a b -> Bimap a b -> Bimap a b The changer functions take pairs and the search key to look for is Either a b . But most of the map functions (including update above) probably won't work anyway, what should left_insertWith (\new old -> new) 'a' 1 (fromList [('a',2),('b',1)]) do? I can't yield fromList [('a',1),('b',1)] since 1 has two keys now. Regards, apfelmus From david.maciver at gmail.com Mon Aug 20 04:46:45 2007 From: david.maciver at gmail.com (David Ritchie MacIver) Date: Mon Aug 20 04:38:09 2007 Subject: [Haskell-cafe] "Tying the knot" with unknown keys Message-ID: <46C954F5.6020502@gmail.com> I was playing with some code for compiling regular expressions to finite state machines and I ran into the following problem. I've solved it, but I'm not terribly happy with my solution and was wondering if someone could come up with a better one. :-) Essentially I have data FSM = State { transitions :: (Map Char FSM) } and transitions' :: Regexp -> Map Char Regexp I want to lift this so that the Regexps become states of the finite state machine (while making sure I set up a loop in the data structure). Tying the knot is the traditional way of doing such things, but we couldn't figure out a way to make it work without the set of keys known in advance because of the strictness of Map in its keys (an association list was suggested, and that would probably work, but it seemed a bit ugly and would be fairly inefficient). In the end what I did was just work out the set of reachable regexps in advance and use a standard tying the knot trick, but it felt vaguely unsatisfactory (and does some repeat work which I felt should be unneccessary). Anyone have a more elegant suggestion? Regards, David From jeanphilippe.bernardy at gmail.com Mon Aug 20 04:50:34 2007 From: jeanphilippe.bernardy at gmail.com (Jean-Philippe Bernardy) Date: Mon Aug 20 04:42:10 2007 Subject: [Haskell-cafe] Re: Using Collections: ElemsView and KeysView References: Message-ID: foldr on ElemsView is defined as such: > foldr f i (ElemsView c) = foldr (f . snd) i c so, for example: > getElementList = toList . ElemViews When I designed this code (some years ago), I didn't like the "fold" of Map to have the type: > fold :: (a -> b -> b) -> b -> Map k a -> b This just doesn't make sense if we see maps as a collection of (key, value) pairs. (Indeed, toList :: Map k a -> [(k, a)]) In order to be consistent, but to provide an easy way to migrate to the new collection classes I was designing, I provided the ElemViews/KeyViews to "switch" to the former behaviour on a case by case basis. This also allows for definining optimized versions of foldr, etc. for each types that supports "Views", but this was tedious, so I never did it. GHC "RULE" pragma is probably better suited to the purpose anyway. As for the lack of documentation, everyone is very welcome to contribute ;) Cheers, JP. From ryani.spam at gmail.com Mon Aug 20 08:27:04 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Mon Aug 20 08:18:23 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? Message-ID: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> I have a C function of type void f ( HsWord32* p0, HsWord32* p1, HsWord32 size ); along with the FFI declaration: foreign import ccall unsafe f :: Ptr Word32 -> Ptr Word32 -> Word32 -> IO () In my Haskell code I have an unboxed IO array of Word32; IOUArray Int Word32. I want to pass the pointer to this array to f(). How can I get the pointer out of the array? Or, is there a better way to declare f() to do this? I'm open to using GHC hackery; using v6.6.1 right now. -- ryan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/a84152b3/attachment.htm From dons at cse.unsw.edu.au Mon Aug 20 08:56:45 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Mon Aug 20 08:48:09 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> Message-ID: <20070820125645.GB19747@cse.unsw.EDU.AU> ryani.spam: > > I have a C function of type > > void f ( HsWord32* p0, HsWord32* p1, HsWord32 size ); > > > > along with the FFI declaration: > > foreign import ccall unsafe f :: Ptr Word32 -> Ptr Word32 > -> Word32 -> IO () > > > > In my Haskell code I have an unboxed IO array of Word32; > IOUArray Int Word32. > > I want to pass the pointer to this array to f(). How can I > get the pointer out of the array? Or, is there a better way > to declare f() to do this? > > > > I'm open to using GHC hackery; using v6.6.1 right now. > > Perhaps you want to use Foreign.Array instead (they are unboxed, and can be used as a Ptr over to C land)? -- Don From sjanssen at cse.unl.edu Mon Aug 20 10:59:13 2007 From: sjanssen at cse.unl.edu (Spencer Janssen) Date: Mon Aug 20 10:50:41 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> Message-ID: <200708200959.13226.sjanssen@cse.unl.edu> On Monday 20 August 2007 07:27:04 Ryan Ingram wrote: > I have a C function of type > void f ( HsWord32* p0, HsWord32* p1, HsWord32 size ); > > along with the FFI declaration: > foreign import ccall unsafe f :: Ptr Word32 -> Ptr Word32 -> Word32 -> > IO () > > In my Haskell code I have an unboxed IO array of Word32; IOUArray Int > Word32. > I want to pass the pointer to this array to f(). How can I get the pointer > out of the array? Or, is there a better way to declare f() to do this? > > I'm open to using GHC hackery; using v6.6.1 right now. > > -- ryan Perhaps you'd like to use Data.Array.Storable? It supports the MArray interface, and has the additional operation: withStorableArray :: StorableArray i e -> (Ptr e -> IO a) -> IO a Cheers, Spencer Janssen From jgbailey at gmail.com Mon Aug 20 11:35:22 2007 From: jgbailey at gmail.com (Justin Bailey) Date: Mon Aug 20 11:26:40 2007 Subject: [Haskell-cafe] Diagnosing stack overflow In-Reply-To: <1187433615.20252.1206016971@webmail.messagingengine.com> References: <1187308362.8691.1205805295@webmail.messagingengine.com> <1187433615.20252.1206016971@webmail.messagingengine.com> Message-ID: On 8/18/07, Matthew Brecknell wrote: > Justin Bailey: > > Would "retainer profiling" help me see what was building up > > this large thunk/closure? > > I'm not really familiar enough with GHC's profiling to answer that, but > I'll take a guess. You're experimental programs have given me an idea - I can use them to test if the profiling tools can show me where a stack overflow might be occurring. Thanks for the clear explanation of the difference. I also found the wiki page http://www.haskell.org/haskellwiki/Stack_overflow to be helpful. Justin From lanny at cisco.com Mon Aug 20 12:21:01 2007 From: lanny at cisco.com (Lanny Ripple) Date: Mon Aug 20 12:12:39 2007 Subject: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <000101c7e1c6$8724d260$956e7720$@be> References: <000101c7e1c6$8724d260$956e7720$@be> Message-ID: <46C9BF6D.40806@cisco.com> Not really more efficient but plays to the language implementation's strengths. Imagine take 10 $ foo (10^9) and take 10 $ bar (10^9) bar wouldn't evaluate until the 10^9 was done. (And I just ground my laptop to a halt checking that. :) foo on the other hand would run out to 10^6 and then conveniently finish the rest of your program waiting for the need of the other 10^9-10 values. If you *always* needed the result of the 10^9 calculations then tail-recursion should be better since you won't be holding onto the evaluation frames. -ljr Peter Verswyvelen wrote: > > Now if I understand this correctly, this just means that when writing > something like: > > foo n = if n<0 then [] else n : foo (n-1) > > bar n = aux 0 [] where > aux i xs = if i>n then xs else aux (i+1) (i:xs) > > that foo is more efficient than bar because lazy evaluation of foo just puts > the delayed computation in the "cdr" of the list, while lazy evaluation of > bar has to keep track of all aux calls (the "closures") which gives much > more overhead, maybe even stack overflow? Something like that? > > Thanks, > Peter > -- Lanny Ripple ScmDB / Cisco Systems, Inc. From lanny at cisco.com Mon Aug 20 12:24:10 2007 From: lanny at cisco.com (Lanny Ripple) Date: Mon Aug 20 12:15:53 2007 Subject: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <46C9BF6D.40806@cisco.com> References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> Message-ID: <46C9C02A.7000605@cisco.com> Lanny Ripple wrote: > Not really more efficient but plays to the language implementation's > strengths. > > Imagine > > take 10 $ foo (10^9) > > and > > take 10 $ bar (10^9) > > bar wouldn't evaluate until the 10^9 was done. (And I just ground my > laptop to a halt checking that. :) foo on the other hand would run out > to 10^6 and then conveniently finish the rest of your program waiting s/10^6/10/ That's what I get for not proof-reading after making a change after the first proof-read. > for the need of the other 10^9-10 values. If you *always* needed the > result of the 10^9 calculations then tail-recursion should be better > since you won't be holding onto the evaluation frames. > > -ljr > > Peter Verswyvelen wrote: >> >> Now if I understand this correctly, this just means that when writing >> something like: >> >> foo n = if n<0 then [] else n : foo (n-1) >> >> bar n = aux 0 [] where >> aux i xs = if i>n then xs else aux (i+1) (i:xs) >> >> that foo is more efficient than bar because lazy evaluation of foo >> just puts >> the delayed computation in the "cdr" of the list, while lazy >> evaluation of >> bar has to keep track of all aux calls (the "closures") which gives much >> more overhead, maybe even stack overflow? Something like that? >> Thanks, >> Peter >> > > -- Lanny Ripple ScmDB / Cisco Systems, Inc. From bertram.felgenhauer at googlemail.com Mon Aug 20 12:25:54 2007 From: bertram.felgenhauer at googlemail.com (Bertram Felgenhauer) Date: Mon Aug 20 12:17:18 2007 Subject: [Haskell-cafe] "Tying the knot" with unknown keys In-Reply-To: <46C954F5.6020502@gmail.com> References: <46C954F5.6020502@gmail.com> Message-ID: <20070820162554.GA4585@zombie.inf.tu-dresden.de> David Ritchie MacIver wrote: > I was playing with some code for compiling regular expressions to finite > state machines and I ran into the following problem. I've solved it, but > I'm not terribly happy with my solution and was wondering if someone could > come up with a better one. :-) > > Essentially I have > > data FSM = State { transitions :: (Map Char FSM) } > > and > > transitions' :: Regexp -> Map Char Regexp > > I want to lift this so that the Regexps become states of the finite state > machine (while making sure I set up a loop in the data structure). Tying > the knot is the traditional way of doing such things, but we couldn't > figure out a way to make it work without the set of keys known in advance > because of the strictness of Map in its keys (an association list was > suggested, and that would probably work, but it seemed a bit ugly and would > be fairly inefficient). > > In the end what I did was just work out the set of reachable regexps in > advance and use a standard tying the knot trick, but it felt vaguely > unsatisfactory (and does some repeat work which I felt should be > unneccessary). Anyone have a more elegant suggestion? Hmm. I tried and came up with this: > import Data.Maybe > import Data.Map (Map) > data Graph b = Graph (Map b (Graph b)) > buildTransitionGraph :: (Ord a, Ord b) => (a -> Map b a) -> a -> Graph b > buildTransitionGraph f i = fromJust $ i `M.lookup` build M.empty [i] where > -- build :: Map a (Graph b) -> [a] -> Map a (Graph b) > build g [] = g > build g (a:as) = g'' where > -- g'' :: Map a (Graph b) > g'' = build g' as' > (as', g') = foldr step (as, g) (M.toList (f a)) > step (l, n) (as, g) > | M.member n g = (as, g) > | otherwise = (n:as, M.insert n (f' n) g) > -- f' :: a -> Graph b > f' = Graph . M.map (fromJust . (`M.lookup` g'')) . f which couples the knot tying with finding the reachable states. 'build' takes a map of states seen so far to their corresponding 'Graph' node, and a working stack of states not processed yet and processes a single state. 'step' processes a single transition. If it leads to an unknown state, the state is added to the seen state map. The knot is tied between the final result of the calculation, g'', and the map that is being built - this happens in f'. Test: > t :: Int -> Map Int Int > t 1 = M.fromList [(1,2),(2,1)] > t 2 = M.fromList [(1,2),(3,1),(4,3)] > t _ = M.empty > traces :: Ord b => Int -> Graph b -> [[b]] > traces 0 g = [[]] > traces d (Graph g) = concat > [map (n:) (trace (d-1) g') | (n, g') <- M.toList g] *Main> trace 1 $ buildTransitionGraph t 1 [[1],[2]] *Main> trace 1 $ buildTransitionGraph t 2 [[1],[3],[4]] *Main> trace 2 $ buildTransitionGraph t 1 [[1,1],[1,3],[1,4],[2,1],[2,2]] It's still not lazy though. The potential lookups of states that haven't been seen yet makes this hard to accomplish, although it should be possible with an unbalanced search tree and some clever use of irrefutable patterns. enjoy, Bertram From thomas.hartman at db.com Mon Aug 20 12:37:30 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Mon Aug 20 12:28:48 2007 Subject: [Haskell-cafe] is there a way to patch the build-depends line of a cabal file without breaking backwards compatibility? Message-ID: cafe, is there a way to patch the build-depends line of a cabal file without breaking backwards compatibility? I just patched HDBC head to compile under ghc 6.7. Unfortunately it now won't compile in 6.6.1. is there a way for build-depends to detect which version of ghc you're on? also I seem to recall that -fglasgow-exts was deprecated under 6.7. is there a better way to beat back the error message below than this? thanks, thomas. { hunk ./Database/HDBC/Statement.hs 1 +{-# LANGUAGE TypeSynonymInstances #-} hunk ./Database/HDBC/Types.hs 1 +{-# OPTIONS_GHC -fglasgow-exts #-} +{- +-- without -fglasgow-exts you get: [_$_] +Database/HDBC/Types.hs:202:0: + Illegal polymorphic or qualified type: forall conn. + (IConnection conn) => + conn -> b + In the type signature for `withWConn': + withWConn :: forall b. + ConnWrapper -> (forall conn. (IConnection conn) => conn -> b) -> b +-} hunk ./HDBC.cabal 13 -Build-Depends: base, mtl + +Build-Depends: base, mtl, old-time, bytestring, containers +-- breaks backwards compability with ghc 6.6.1 + } --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/afcd390d/attachment.htm From thomas.hartman at db.com Mon Aug 20 13:10:37 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Mon Aug 20 13:01:56 2007 Subject: [Haskell-cafe] cabal install of HDBC-odbc fails on ghc 6.7, -I flag causes problems Message-ID: problemw with the -I flag to ghc are causing cabal install to fail for hdbc-odbc (darcs head). man ghc still reports that -I is a valid flag after installing ghc 6.7 from darcs head a couple days ago. I think the problem might be the space after the -I flag (which is bad for both 6.6.1 and 6.7) hartthoma@linuxpt:~/installs/HDBC-odbc-head/hdbc-odbc>/usr/local/bin/ghc-6.7.20070816 -I. -e '' Setup.hs hartthoma@linuxpt:~/installs/HDBC-odbc-head/hdbc-odbc>/usr/local/bin/ghc-6.7.20070816 -I/ -e '' Setup.hs hartthoma@linuxpt:~/installs/HDBC-odbc-head/hdbc-odbc>/usr/local/bin/ghc-6.7.20070816 -I / -e '' Setup.hs ghc-6.7.20070816: unrecognised flags: -I just a guess... anothing thing is it seems like there's a new INCLUDE pragma in 6.7. perhaps this should be used in one of the source files to get it to compile. but which one? I couldn't figure out what was causing ghc -c -I dist/build/Database/HDBC/ODBC/Connection_hsc_make.c -o dist/build/Database/HDBC/ODBC/Connection_hsc_make.o to be run. (I did try grepping on ghc but no luck, below.) Any tips on debugging this cabal install would be appreciated. thanks, thomas ************* $ runghc Setup.hs configure; runghc Setup.hs build ..... configure: Using tar found on system at: /bin/tar Reading parameters from /home/hartthoma/installs/HDBC-odbc-head/hdbc-odbc/HDBC-odbc.buildinfo Preprocessing library HDBC-odbc-1.1.2hartthoma@linuxpt:~/installs/HDBC-odbc-head/hdbc-odbc>darcs whatsnew.0... ghc-6.7.20070816: unrecognised flags: -I Usage: For basic information, try the `--help' option. compiling dist/build/Database/HDBC/ODBC/Connection_hsc_make.c failed command was: ghc -c -I dist/build/Database/HDBC/ODBC/Connection_hsc_make.c -o dist/build/Database/HDBC/ODBC/Connection_hsc_make.o ........ hartthoma@linuxpt:~/installs/HDBC-odbc-head/hdbc-odbc>darcs whatsnew { hunk ./Setup.hs 8 -main = defaultMainWithHooks defaultUserHooks{preConf = conf, postConf = ok} - where ok _ _ _ _ = return ExitSuccess +--main = defaultMainWithHooks defaultUserHooks{preConf = conf, postConf = ok} +-- where ok _ _ _ _ = return ExitSuccess +main = do + let ok _ _ _ _ = do return ExitSuccess + return () + in defaultMainWithHooks defaultUserHooks{preConf = conf, postConf = ok} + return () + } ..... hartthoma@linuxpt:~/installs/HDBC-odbc-head/hdbc-odbc>grep -i ghc * HDBC-odbc.buildinfo:ghc-prof-options: HDBC-odbc.buildinfo:ghc-options: HDBC-odbc.cabal:GHC-Options: -O2 Makefile:GHCPARMS := -fglasgow-exts Makefile:all: setup # GHC build Makefile: ghc -package Cabal Setup.hs -o setup Makefile: cd testsrc && ghc --make -package mtl -package HUnit -package MissingH -package HDBC -lodbc $(GHCPARMS) -o runtests -i../dist/build:.. ../d\ ist/build/hdbc-odbc-helper.o runtests.hs Makefile:test-ghc6: testsrc/runtests Makefile:interact-ghci: all Makefile: ghci -idist/build -Ldist/build $(GHCPARMS) Makefile:test: test-ghc6 test-hugs README.txt:You'll need either GHC 6.4.1 or above, or Hugs 2005xx or above. If README.txt:2) ghc --make -o setup Setup.lhs README.txt:To use with GHC, you'll want to use: --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/4b7ee31e/attachment.htm From andrewcoppin at btinternet.com Mon Aug 20 13:30:27 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Mon Aug 20 13:20:54 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070819191420.GA3019@localhost.localdomain> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> Message-ID: <46C9CFB3.9050007@btinternet.com> Stefan O'Rear wrote: > On Sun, Aug 19, 2007 at 12:53:07PM +0100, Andrew Coppin wrote: > >> Does GHC do stuff like converting (2*) into (shift 1) or converting x + x >> into 2*x? >> > > For a good time, compile some code which uses even or odd :: Int -> Bool > using -O2 -fasm -ddump-asm... The compiler *really* shouldn't be using 'idivl'. > > (If you use -fvia-C -optc-O2, the C compiler will notice the operations > and optimize it itself. This is one of the very few areas where -fvia-C > is still better.) > The way I heard it is that compilation via C is "always better", though they "plan" to change that some day. I don't know how true that is... >> If I do x * sin 12, is GHC likely to compute sin 12 at compile-time? >> > > Also try -ddump-simpl-stats and -ddump-simpl-iterations if you want to > know *why*. (The extremely obscure 'full laziness' transformation > performed by GHC has a fundamental effect on the compilation of x * sin > 12...) > Hmm, OK. From nominolo at googlemail.com Mon Aug 20 13:37:28 2007 From: nominolo at googlemail.com (Thomas Schilling) Date: Mon Aug 20 13:28:52 2007 Subject: [Haskell-cafe] is there a way to patch the build-depends line of a cabal file without breaking backwards compatibility? In-Reply-To: References: Message-ID: <175B84F4-DF13-48A6-9B0C-EC9B58226CB2@googlemail.com> On 20 aug 2007, at 18.37, Thomas Hartman wrote: > > cafe, is there a way to patch the build-depends line of a cabal > file without breaking backwards compatibility? > > I just patched HDBC head to compile under ghc 6.7. Unfortunately it > now won't compile in 6.6.1. > > is there a way for build-depends to detect which version of ghc > you're on? > > also I seem to recall that -fglasgow-exts was deprecated under 6.7. > is there a better way to beat back the error message below than this? > The next release of Cabal (and the current HEAD) supports conditionals to test for flags, os/arch, and implementation (+version). Note that the problem isn't the GHC version, but the new base version, in which the old base was split up into smaller packages, so we have something roughly like: base-1.0 = base-2.0 + bytestring + old-time + mtl. Take a look at the Cabal.cabal file, how this is solved, atm. Please also note that this might not be the best way to use the new features; as I suggested in another thread, simulating base-1.0 on systems with base-2.0 is probably best handled with a base.cabal file that imports base-2.0, old-time, etc. and re- exports all imported modules to get a "virtual" base-1.0. / Thomas From thomas.hartman at db.com Mon Aug 20 14:27:26 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Mon Aug 20 14:18:50 2007 Subject: [Haskell-cafe] can't build haxml under ghc 6.7, says HughesPJ is hidden... but ghc-pkg doesn't say it's hidden... In-Reply-To: <20070810133127.28ee0d30.Malcolm.Wallace@cs.york.ac.uk> Message-ID: so you get $ runghc Setup.hs configure Setup.hs: Multiple description files found. Please use only one of : ["HaXml.cabal","HaXml-darcs.cabal"] is there a way to specify which cabal file should be used, or do you just have to move a file out out the way with eg mv HaXml.cabal HaXml.cabal.tmp ? Understanding this better is important to me because I am installing a number of packages on 6.7, and am reluctant to send a patch that breaks backwards compabitility with earlier versions. It seems to me that if there is a way to specify the cabal file, you're a step closer to having something DWIM that works for either 6.6 or 6.7, as Claus wishlists elsewhere in this thread. thomas. Malcolm Wallace Sent by: haskell-cafe-bounces@haskell.org 08/10/2007 08:31 AM To haskell-cafe@haskell.org cc Subject Re: [Haskell-cafe] can't build haxml under ghc 6.7, says HughesPJ is hidden... but ghc-pkg doesn't say it's hidden... Stefan O'Rear wrote: > When you build a package, Cabal passess the -hide-all-packages option > to GHC, which prevents the package from using any installed packages > other than the ones explicitly listed in the Build-Depends: field. > > For now, we just edit .cabal files when transporting code between GHC > versions... Just for information, the HaXml darcs repo has recently adopted the solution of containing two .cabal files, one for ghc-6.6.x, and the other for the split-base packages (>=ghc-6.7). The only difference is the build-depends line, which is now as follows: build-depends: base, haskell98, polyparse, pretty, fps But if you have collected the earlier release HaXml-1.13.2 from hackage, then you can omit both 'polyparse' and 'fps' dependencies. ('fps' will shortly be changing to 'bytestring' in any case...) Regards, Malcolm _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/7cde72dd/attachment.htm From rich.neswold at gmail.com Mon Aug 20 14:46:15 2007 From: rich.neswold at gmail.com (Rich Neswold) Date: Mon Aug 20 14:37:34 2007 Subject: [Haskell-cafe] Re: Bi-directional Maps In-Reply-To: References: Message-ID: <14cf844b0708201146w715809afs26f20b37ba09b852@mail.gmail.com> On 8/20/07, apfelmus wrote: > > Andrew Wagner wrote: > > It occurred to me that it would be useful to explicitly > > have a Bi-directional Map, which does the maintenance of keeping the > > Maps synchronized behind the scenes. Thus, Bimap was born! > > ... most of the map functions (including update above) probably won't > work anyway, what should > > left_insertWith (\new old -> new) 'a' 1 (fromList [('a',2),('b',1)]) > > do? I can't yield > > fromList [('a',1),('b',1)] > > since 1 has two keys now. > Exactly. For this to work there needs to be the constraint that there's a one-to-one mapping in each direction. The Bimap should have the uniqueness promise that "Set (k, v)" gives. Yet you should be able to search on either tuple value. -- Rich JID: rich@neswold.homeunix.net AIM: rnezzy -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/38ba6bac/attachment.htm From stefanor at cox.net Mon Aug 20 14:49:50 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 20 14:41:37 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> Message-ID: <20070820184950.GB3098@localhost.localdomain> On Mon, Aug 20, 2007 at 05:27:04AM -0700, Ryan Ingram wrote: > I have a C function of type > void f ( HsWord32* p0, HsWord32* p1, HsWord32 size ); > > along with the FFI declaration: > foreign import ccall unsafe f :: Ptr Word32 -> Ptr Word32 -> Word32 -> IO > () > > In my Haskell code I have an unboxed IO array of Word32; IOUArray Int > Word32. > I want to pass the pointer to this array to f(). How can I get the pointer > out of the array? Or, is there a better way to declare f() to do this? Short answer: You can't. Longer: GHC uses a copying/compacting garbage collector, so most objects don't have stable addresses. In particular MutableByteArray# is movable by default. So, you need an array structure built on pinned memory. If you want MArray operations, that leaves you with Data.Array.Storable, as already mentioned. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/cc3c7c53/attachment.bin From agl at imperialviolet.org Mon Aug 20 14:57:11 2007 From: agl at imperialviolet.org (Adam Langley) Date: Mon Aug 20 14:48:32 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: <20070819212655.GA21509@wellquite.org> References: <20070819205512.1EBAE324405@www.haskell.org> <396556a20708190908n42f53902y18bc666bfe551be0@mail.gmail.com> <20070819212655.GA21509@wellquite.org> Message-ID: <396556a20708201157p395469d7p5e0fd1f93b0aca16@mail.gmail.com> On 8/19/07, Matthew Sackman wrote: > But it's vastly harder to do that for floats / non-integers. Now I know > that the number classes in the Prelude are basically broken anyway and > all really need rewriting, but it does seem completely arbitrary that > Words somehow are only allowed to contain whole numbers! Well, see the attached patch to Data.Binary to add putFloat[32|64][be|le]. I got bored, so adding the Get functions is an exercise for the reader :) (And so because I think it needs unsafeSomethingIO and I'm a little unsure about that). If these functions would be useful for you, you should bug the binary team to add something similar. AGL -- Adam Langley agl@imperialviolet.org http://www.imperialviolet.org 650-283-9641 -------------- next part -------------- A non-text attachment was scrubbed... Name: data-binary-float.darcs Type: application/octet-stream Size: 5797 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/12a8ad07/data-binary-float-0001.obj From thomas.hartman at db.com Mon Aug 20 14:58:31 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Mon Aug 20 14:49:48 2007 Subject: [Haskell-cafe] is there a way to patch the build-depends line of a cabal file without breaking backwards compatibility? In-Reply-To: <175B84F4-DF13-48A6-9B0C-EC9B58226CB2@googlemail.com> Message-ID: > Take a look at the Cabal.cabal file, how this is solved, atm. where is this, how can I take a look at it? > The next release of Cabal (and the current HEAD) supports conditionals I couldn't install head, but since I'm running 6.7, do I already have it? hartthoma@linuxpt:~/installs/cabal-head/cabal>runghc Setup.lhs configure Distribution/Simple/InstallDirs.hs:267:36: Not in scope: `dropDrive' hartthoma@linuxpt:~/installs/cabal-head/cabal>ls -l `which ghc` lrwxrwxrwx 1 root root 31 2007-08-20 11:08 /usr/local/bin/ghc -> /usr/local/bin/ghc-6.7.20070816 hartthoma@linuxpt:~/installs/cabal-head/cabal>ghc-pkg list | grep -i cabal Cabal-1.1.7 > Please also note that this might not be the > best way to use the new features; as I suggested in another thread, > simulating base-1.0 on systems with base-2.0 is probably best handled > with a base.cabal file that imports base-2.0, old-time, etc. and re- > exports all imported modules to get a "virtual" base-1.0. I'm interested in seeing how this works, but I couldn't find that other thread. Where is the documentation for the new functionality in cabal head, or do you just have to read the source code for now? thanks, t Thomas Schilling 08/20/2007 01:37 PM To Thomas Hartman/ext/dbcom@DBAmericas cc haskell-cafe Subject Re: [Haskell-cafe] is there a way to patch the build-depends line of a cabal file without breaking backwards compatibility? On 20 aug 2007, at 18.37, Thomas Hartman wrote: > > cafe, is there a way to patch the build-depends line of a cabal > file without breaking backwards compatibility? > > I just patched HDBC head to compile under ghc 6.7. Unfortunately it > now won't compile in 6.6.1. > > is there a way for build-depends to detect which version of ghc > you're on? > > also I seem to recall that -fglasgow-exts was deprecated under 6.7. > is there a better way to beat back the error message below than this? > The next release of Cabal (and the current HEAD) supports conditionals to test for flags, os/arch, and implementation (+version). Note that the problem isn't the GHC version, but the new base version, in which the old base was split up into smaller packages, so we have something roughly like: base-1.0 = base-2.0 + bytestring + old-time + mtl. Take a look at the Cabal.cabal file, how this is solved, atm. Please also note that this might not be the best way to use the new features; as I suggested in another thread, simulating base-1.0 on systems with base-2.0 is probably best handled with a base.cabal file that imports base-2.0, old-time, etc. and re- exports all imported modules to get a "virtual" base-1.0. / Thomas --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/db566db5/attachment.htm From ndmitchell at gmail.com Mon Aug 20 15:03:53 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Mon Aug 20 14:55:11 2007 Subject: [Haskell-cafe] is there a way to patch the build-depends line of a cabal file without breaking backwards compatibility? In-Reply-To: References: <175B84F4-DF13-48A6-9B0C-EC9B58226CB2@googlemail.com> Message-ID: <404396ef0708201203n6255caeekf656e41a09f13e8e@mail.gmail.com> Hi Distribution/Simple/InstallDirs.hs:267:36: > Not in scope: `dropDrive' > > hartthoma@linuxpt:~/installs/cabal-head/cabal>ls -l `which ghc` > lrwxrwxrwx 1 root root 31 2007-08-20 11:08 /usr/local/bin/ghc -> > /usr/local/bin/ghc-6.7.20070816 You'll need to upgrade the filepath library as well, since cabal depends on it, and a very recent version at that. Thanks Neil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/86a2cf3f/attachment.htm From stefanor at cox.net Mon Aug 20 15:15:26 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 20 15:07:40 2007 Subject: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <46C9BF6D.40806@cisco.com> References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> Message-ID: <20070820191526.GD3098@localhost.localdomain> On Mon, Aug 20, 2007 at 11:21:01AM -0500, Lanny Ripple wrote: > Not really more efficient but plays to the language implementation's > strengths. > > Imagine > > take 10 $ foo (10^9) > > and > > take 10 $ bar (10^9) > > bar wouldn't evaluate until the 10^9 was done. (And I just ground my > laptop to a halt checking that. :) foo on the other hand would run out to > 10^6 and then conveniently finish the rest of your program waiting for the > need of the other 10^9-10 values. If you *always* needed the result of the > 10^9 calculations then tail-recursion should be better since you won't be > holding onto the evaluation frames. Even if you did, in the presense of laziness it's not useful to make list producers tail recursive. Consider: sum = sum' 0 sum' k [] = k sum' k (x:xs) = (sum' $! (k+x)) xs enum x y | x >= y = 0 | otherwise = x : enum (x+1) y sum (enum 1 10) => sum' 0 (enum 1 10) => sum' 0 (1 : enum (1+1) 10) => (sum' $! (0+1)) (enum (1+1) 10) => sum' 1 (enum (1+1) 10) => sum' 1 (2 : enum (2+1) 10) => (sum' $! (1+2)) (enum (2+1) 10) => sum' 3 (enum (2+1) 10) => sum' 3 (3 : enum (3+1) 10) => (sum' $! (3+3)) (enum (3+1) 10) => sum' 6 (enum (3+1) 10) => sum' 6 (4 : enum (4+1) 10) => (sum' $! (6+4)) (enum (4+1) 10) => sum' 10 (enum (4+1) 10) => ... sum' 36 (9 : enum (9+1) 10) => (sum' $! (36+9)) (enum (9+1) 10) => sum' 45 (enum (9+1) 10) => sum' 45 [] => 45 (I need to find some way to automate making these trails :) ) It runs in constant space, despite the producer's non-tail-recursion. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/4eb5bb86/attachment.bin From stefanor at cox.net Mon Aug 20 15:22:48 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 20 15:15:09 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46C9CFB3.9050007@btinternet.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46C9CFB3.9050007@btinternet.com> Message-ID: <20070820192248.GE3098@localhost.localdomain> On Mon, Aug 20, 2007 at 06:30:27PM +0100, Andrew Coppin wrote: > Stefan O'Rear wrote: >> On Sun, Aug 19, 2007 at 12:53:07PM +0100, Andrew Coppin wrote: >> >>> Does GHC do stuff like converting (2*) into (shift 1) or converting x + x >>> into 2*x? >> >> For a good time, compile some code which uses even or odd :: Int -> Bool >> using -O2 -fasm -ddump-asm... The compiler *really* shouldn't be using >> 'idivl'. >> >> (If you use -fvia-C -optc-O2, the C compiler will notice the operations >> and optimize it itself. This is one of the very few areas where -fvia-C >> is still better.) > > The way I heard it is that compilation via C is "always better", though > they "plan" to change that some day. I don't know how true that is... Currently, it's never worse. GHC's backend is about as good as GCC; most of the optimiations it doesn't do are not possible for GCC because of various lack-of-information problems (the stack pointer never aliases the heap pointer, stuff like that). It's conceivable that at some point -fasm will be faster, because you have the possibility of much more accurate aliasing information inside the compiler, than can be coded in C. In the meantime, note that the runtime difference is less than 3% and the compile time difference is over 100%, so it's only worthwhile if you expect *this version* of your program to be used more than 30 times, ie releases only. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/159b5674/attachment.bin From simonpj at microsoft.com Mon Aug 20 16:57:38 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Mon Aug 20 16:48:54 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070819191420.GA3019@localhost.localdomain> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> Message-ID: GHC does some constant folding, but little by way of strength reduction, or using shifts instead of multiplication. It's pretty easy to add more: it's all done in a single module. Look at primOpRules in the module PrelRules. Patches welcome! But please also supply test-suite tests that check the correctness of the rules. Simon | -----Original Message----- | From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe- | bounces@haskell.org] On Behalf Of Stefan O'Rear | Sent: 19 August 2007 20:14 | To: Andrew Coppin | Cc: haskell-cafe@haskell.org | Subject: Re: [Haskell-cafe] GHC optimisations | | On Sun, Aug 19, 2007 at 12:53:07PM +0100, Andrew Coppin wrote: | > Does GHC do stuff like converting (2*) into (shift 1) or converting x | + x | > into 2*x? | | For a good time, compile some code which uses even or odd :: Int -> | Bool | using -O2 -fasm -ddump-asm... The compiler *really* shouldn't be using | 'idivl'. | | (If you use -fvia-C -optc-O2, the C compiler will notice the operations | and optimize it itself. This is one of the very few areas where -fvia- | C | is still better.) | | > If I do x * sin 12, is GHC likely to compute sin 12 at compile-time? | | Also try -ddump-simpl-stats and -ddump-simpl-iterations if you want to | know *why*. (The extremely obscure 'full laziness' transformation | performed by GHC has a fundamental effect on the compilation of x * sin | 12...) | | Stefan From wnoise at ofb.net Mon Aug 20 18:03:52 2007 From: wnoise at ofb.net (Aaron Denney) Date: Mon Aug 20 17:55:29 2007 Subject: [Haskell-cafe] Re: Parsing binary data. References: <20070819205512.1EBAE324405@www.haskell.org> <20070819212655.GA21509@wellquite.org> Message-ID: On 2007-08-19, Matthew Sackman wrote: > Recently, Adam Langley responded so: >> On 8/18/07, Matthew Sackman wrote: >> > Also, one thing to watch out for is the fact the existing Get and Put >> > instances may not do anything like what you expect. For example, for >> > some reason I expected that the instances of Get and Put for Float and >> > Double would send across the wire Floats and Doubles in IEEE floating >> > point standard. How wrong I was... >> >> Ah, those aren't instances of Get and Put, but of Binary[1]. You use >> the Binary instances via the functions 'get' and 'put' (case is >> important). > > Gah, that'll teach me to post from memory without checking the code. > Indeed, that is what I meant, the instances of Binary. > >> Get and Put provide actions like "putWord32be", for which the >> resulting bits are pretty much universally accepted. Binary has >> default instances which uses Get and Put to serialise Haskell types >> like [Int], or (Float, Float). Here the resulting bits aren't >> documented, but you can read the code and I have some C code for >> dealing with them somewhere if anyone is interrested. The >> serialisation of Float is, indeed, nothing like IEEE in either >> endianness. > > Quite. Whilst we're on the subject (and I realise I might be hijacking > this thread a little), it does seem rather odd that it's very easy to > take a Word8/16/32/64 and interpret it as an integer. Similarly, it's > very easy to take an integer and convert it to a Word of some sort. That's because there's basically only one way to interpret a given word as an integer, and store a given integer as a word. > But it's vastly harder to do that for floats / non-integers. Now I know > that the number classes in the Prelude are basically broken anyway and > all really need rewriting, but it does seem completely arbitrary that > Words somehow are only allowed to contain whole numbers! It's more that for floats, there are a zillion plausible ways to store them, and many have been used. -- Aaron Denney -><- From dpiponi at gmail.com Mon Aug 20 18:39:28 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Mon Aug 20 18:30:46 2007 Subject: [Haskell-cafe] "Tying the knot" with unknown keys In-Reply-To: <46C954F5.6020502@gmail.com> References: <46C954F5.6020502@gmail.com> Message-ID: <625b74080708201539te1418d3jbd44f30b0aa51726@mail.gmail.com> On 8/20/07, David Ritchie MacIver wrote: > I was playing with some code for compiling regular expressions to finite > state machines and I ran into the following problem. I've met exactly the same problem myself and you got me interested in it again. I think the tricky part isn't so much the knot-tying, but the fact that you need a high performance Map-like datastructure that doesn't die the way Data.Map.fromList would if you gave it an infinite list as argument. One approach might be to replace Map k a with something like a data UltraLazyMap k a = ULM (Map k a) [(k,a)] The idea is that the Map part is built only as needed and the list part represents the elements not yet inserted into the tree. When you come to perform a lookup you first look in the Map part. If you don't find what you want there you start looking through the list (assuming that when you come to do lookups, every key you need eventually appears at least once in the list). Each time you look at a list element you remove it from the list and insert it into the tree. That way you never try to build an "infinite" tree and instead grow it as needed. This would have a similar amortised performance as a regular Map, but the price is that lookups change the structure and so you need mutable state. But that's OK, you just stick all of your code in a State monad. I don't know if that State monad would ultimately mess up any attempt to eventually tie your knots, and I probably won't have time to try coding this up at lest until the weekend. So take all of this with a pinch of salt :-) Good luck! :-) And if that doesn't work, I also have another approach I'm thinking about... -- Dan From stefanor at cox.net Mon Aug 20 18:53:30 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Mon Aug 20 18:49:30 2007 Subject: [Haskell-cafe] "Tying the knot" with unknown keys In-Reply-To: <625b74080708201539te1418d3jbd44f30b0aa51726@mail.gmail.com> References: <46C954F5.6020502@gmail.com> <625b74080708201539te1418d3jbd44f30b0aa51726@mail.gmail.com> Message-ID: <20070820225330.GA4768@localhost.localdomain> On Mon, Aug 20, 2007 at 03:39:28PM -0700, Dan Piponi wrote: > On 8/20/07, David Ritchie MacIver wrote: > > I was playing with some code for compiling regular expressions to finite > > state machines and I ran into the following problem. > > I've met exactly the same problem myself and you got me interested in it again. > > I think the tricky part isn't so much the knot-tying, but the fact > that you need a high performance Map-like datastructure that doesn't > die the way Data.Map.fromList would if you gave it an infinite list as > argument. > > One approach might be to replace Map k a with something like a > > data UltraLazyMap k a = ULM (Map k a) [(k,a)] > > The idea is that the Map part is built only as needed and the list > part represents the elements not yet inserted into the tree. When you > come to perform a lookup you first look in the Map part. If you don't > find what you want there you start looking through the list (assuming > that when you come to do lookups, every key you need eventually > appears at least once in the list). Each time you look at a list > element you remove it from the list and insert it into the tree. That > way you never try to build an "infinite" tree and instead grow it as > needed. This would have a similar amortised performance as a regular > Map, but the price is that lookups change the structure and so you > need mutable state. But that's OK, you just stick all of your code in > a State monad. > > I don't know if that State monad would ultimately mess up any attempt > to eventually tie your knots, and I probably won't have time to try > coding this up at lest until the weekend. So take all of this with a > pinch of salt :-) > > Good luck! :-) > > And if that doesn't work, I also have another approach I'm thinking about... You could also just build the map lazily. data Map k a = Fork k a (Map k a) (Map k a) | Leaf ... insertMany (Fork k v l r) xs = Fork k v (insertMany l $ filter (k) xs) insertMany Leaf [] = Leaf insertMany Leaf ((k,v):xs) = insertMany (Fork k v Leaf Leaf) xs Unfortunately it's not at all clear how to add balancing, other than access-time mutation. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/b56ebaa4/attachment.bin From levi.stephen at optusnet.com.au Mon Aug 20 20:17:19 2007 From: levi.stephen at optusnet.com.au (Levi Stephen) Date: Mon Aug 20 20:08:52 2007 Subject: [Haskell-cafe] Re: I'm stuck in my thought experiment In-Reply-To: <46C59FDC.8060507@synopsys.com> References: <46C4E9D5.5090503@optusnet.com.au> <46C59FDC.8060507@synopsys.com> Message-ID: <46CA2F0F.3010109@optusnet.com.au> Al Falloon wrote: > > Maybe I am misunderstanding your requirements, but it seems to me that > the simplest solution would be best in this case: > > data Widget = BlogWidget [Article] > | TextWidget String > | MenuWiget Menu > | Rows Spacing [Widget] > | Columns Spacing [Widget] > > You can also add a type parameter if you want to be able to carry around > extra metadata about pages, or you could even parameterize the Article > and Menu types if you want to be able to extend them separately or if > you want to ensure your layout algorithms don't depend on widget > contents by keeping their type abstract. > Thanks for pointing out a simple solution. Over thinking this is something I'm worried about :) > > This code seems to indicate that you want to be able to extend the > widget types without changing this source file. This is a good goal, but > it may not be worth the extra complexity. Ideally, I'd like Widgets to be added through hs-plugins or similar. That is a ideal goal though, not a necessity. > > Also, this looks a lot like the Composite pattern from OO. A rule of > thumb that I use is: "if I would do this with inheritance in OO, I > probably want a variant in FP". Since Composite depends on the > inheritance of the composite object type, I would probably look to use a > single data type with multiple constructors for the different > compisites like the Widget type above. Interesting. I've been curious how OO concepts can map to FP, as most specs (consider stuff like DOM) seem to be written with OO implementaitons in mind. > > If I wanted to develop the widgets themselves separately from the > layout, I would probably do something like this: > > class Widget a where > render :: a -> Html > bbox :: a -> Size > > type Layout = forall a. Widget a => Widget a > | Rows Spacing [Layout] > | Columns Spacing [Layout] > | Grid Spacing [[Layout]] > > type Page = Page String Layout > > renderLayout :: Layout -> Html > > renderPage :: Page -> Html I'm unsure this gives what I'm after. I'm trying to have layouts consist of Widgets (e.g., header images, common menu), and as pages also consist of Widgets it seems like they can be modelled using a common type/construct. > >> >> The issue becomes, given a parent page and the customized content for >> the child page, >> what is the best way to insert the customized content at the right point? >> >> Might a tree like structure be useful? But, how do you work out where >> in the tree >> child content gets added? Store a traversal with each sub tree of >> child page content >> that basically says 'insert here'? > > This is probably a good use for a zipper (a kind of functional > iterator). http://en.wikibooks.org/wiki/Haskell/Zippers that way you can > pass around a value that means "right here", and its clear where the > substitution will happen. I was wondering with zippers were appropriate, or if I just had them in mind becuase I'd read so much about them lately :) > > So you want some sort of wildcard element that can be substituted in > later? Maybe I am misunderstanding your requirement, but if thats the > behavior you want, you should check out the term-level evaluators for > lambda calculus for inspiration on substitution, but I expect your > requirement may be simpler than that. I'm thinking a BlankWidget or ReplacableWidget is a fairly simple option. They could be named for the case of multiple replacements, and have a method similar to -- src -> replacements -> result replaceWidgets :: Widget -> [(String,Widget)] -> Widget which replaces all ReplacableWidgets in the source Widget with those specified. Would you happen to have some links on the evaluators for lambda calculus you talk about? I'm not as familiar as I should be with lambda calculus > >> It might be simple to have a PlaceHolderWidget. Then insertions of the >> child page >> content happens at each of those widgets. > >> This just gets trickier if I start considering multiple extension >> points for child >> pages and what happens when the layout/parent page changes. This is >> why I'm >> thinking I may be going along a bad path here. > > Exactly. With multiple substitutions you get into issues of naming, so > thats why looking at lambda calculus evaluators would be the right > inspiration, but I think it may be more complicated than you need. The > zipper approach might be easier. I think I will try and investigate both approaches. I'm after the process here, rather than the end result Thanks Levi lstephen.wordpress.com From nominolo at googlemail.com Mon Aug 20 20:26:04 2007 From: nominolo at googlemail.com (Thomas Schilling) Date: Mon Aug 20 20:17:26 2007 Subject: [Haskell-cafe] is there a way to patch the build-depends line of a cabal file without breaking backwards compatibility? In-Reply-To: References: Message-ID: On 20 aug 2007, at 20.58, Thomas Hartman wrote: > > > Take a look at the Cabal.cabal file, how this is solved, atm. > > where is this, how can I take a look at it? http://darcs.haskell.org/cabal/Cabal.cabal See below for a little more explaination. > > > The next release of Cabal (and the current HEAD) supports > conditionals > > I couldn't install head, but since I'm running 6.7, do I already > have it? > Yes, you already have it. It should be in ghc/libraries/Cabal, or contrib/Cabal > hartthoma@linuxpt:~/installs/cabal-head/cabal>runghc Setup.lhs > configure > > Distribution/Simple/InstallDirs.hs:267:36: > Not in scope: `dropDrive' > > hartthoma@linuxpt:~/installs/cabal-head/cabal>ls -l `which ghc` > lrwxrwxrwx 1 root root 31 2007-08-20 11:08 /usr/local/bin/ghc -> / > usr/local/bin/ghc-6.7.20070816 > See Neil's reply. > > hartthoma@linuxpt:~/installs/cabal-head/cabal>ghc-pkg list | grep - > i cabal > Cabal-1.1.7 > > > Please also note that this might not be the > > best way to use the new features; as I suggested in another thread, > > simulating base-1.0 on systems with base-2.0 is probably best > handled > > with a base.cabal file that imports base-2.0, old-time, etc. and re- > > exports all imported modules to get a "virtual" base-1.0. > > I'm interested in seeing how this works, but I couldn't find that > other thread. > There is no formal proposal, yet, and I think the note was in a recent thread on cabal-devel or libraries. Therefore, I won't discuss it here. I can tell you the current solution, though. > Where is the documentation for the new functionality in cabal head, > or do you just have to read the source code for now? > Performing (in the Cabal directory) "make doc" should build the haddocks and the latest user's guide. Performing "make users-guide" should only build the user's guide, but since that requires some tools which might be non-trivial to set up on some systems, I didn't recommend it. So here's the relevant part of how Cabal.cabal does it: if flag(small_base) { -- For ghc 6.2 you need to add 'unix' to Build-Depends: Build-Depends: base, filepath, pretty, directory, old-time, process, containers } else { Build-Depends: base, filepath } Note, that the format changed to a sectioned format, and that it is quite likely that it will still change slightly before the release. Consult the Cabal user's guide or (probably easier) take a look at other .cabal files in the ghc tree. It's quite straightforward, actually. The interesting feature here is that unless overridden explicitly, the flag "small_base" will be assigned to a value appropriate for the system, thus, if you don't have any of the packages pretty, directory, etc, it will automatically be assigned to false. (I think it better should be base >= 2.0, though.) (Also, the comment can now be replaced by an actual test like: if impl (ghc <=6.2) ..) HTH / Thomas From dons at cse.unsw.edu.au Mon Aug 20 20:33:29 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Mon Aug 20 20:24:49 2007 Subject: [Haskell-cafe] #haskell irc channel reaches 400 users Message-ID: <20070821003329.GA13546@cse.unsw.EDU.AU> A small announcement :) 5 1/2 years after its inception, under the guiding hand of Shae Erisson (aka shapr), the #haskell IRC channel[1] on freenode has finally reached 400 users! To chart the growth, we can note that the channel was founded in late 2001, and had slow growth till 2006, reaching 200 users in January of that year. Since then growth in the user base has been far more rapid, reaching 300 users in Dec 2006, and 400 users now, in August 2007. This puts the channel at around the 13th largest community of the 5500 freenode channels. For comparision, a sample of the state of the other language communities: #php 485 #perl 472 ##c++ 457 ##c 445 #python 430 #ruby-lang 420 > #haskell 411 #lisp 246 ##java 236 ##javascript 226 #perl6 144 #scheme 139 #erlang 118 #lua 105 #ocaml 58 You can see the growth of the channel over here: http://www.cse.unsw.edu.au/~dons/irc If you've not dropped by the channel yet, feel free to come and chat, and toss around some lambdas! :) Cheers, Don 1. http://www.haskell.org/haskellwiki/IRC_channel From midfield at gmail.com Mon Aug 20 21:52:17 2007 From: midfield at gmail.com (Ben) Date: Mon Aug 20 21:43:35 2007 Subject: [Haskell-cafe] STM, IO and b-trees Message-ID: <9157df230708201852h45325fd3s98550d40e8611db2@mail.gmail.com> for sake of argument, suppose an enterprising haskell newbie wanted to code up concurrent b-trees (really b-link trees) in haskell. if i am understanding STM correctly, it will NOT help in any way with the implementation, because of the IO-intensive nature of the algorithms? so i will have to resort to the usual games with locks and latches? (using Ibrahim Jaluta, Seppo Sippu and Eljas Soisalon-Soininen. Concurrency control and recovery for balanced B-link trees. The VLDB Journal, Volume 14, Issue 2 (April 2005), Pages: 257 - 277, ISSN:1066-8888. as a source for b-tree algorithms.) take care, B From drtomc at gmail.com Mon Aug 20 22:10:33 2007 From: drtomc at gmail.com (Thomas Conway) Date: Mon Aug 20 22:01:50 2007 Subject: [Haskell-cafe] STM, IO and b-trees In-Reply-To: <9157df230708201852h45325fd3s98550d40e8611db2@mail.gmail.com> References: <9157df230708201852h45325fd3s98550d40e8611db2@mail.gmail.com> Message-ID: <784a62100708201910o3184dfceh958cf110cedf82db@mail.gmail.com> On 8/21/07, Ben wrote: > for sake of argument, suppose an enterprising haskell newbie wanted to > code up concurrent b-trees (really b-link trees) in haskell. if i am > understanding STM correctly, it will NOT help in any way with the > implementation, because of the IO-intensive nature of the algorithms? > so i will have to resort to the usual games with locks and latches? I have produced exactly such an implementation in my day-job (so I can't, at this stage, give you the code, I'm afraid), but I'll happily give you some tips: 1. Investigate relaxed balance. BTrees with relaxed balance enable you to break up operations into much smaller transactions, which will reduce the amount of rerunning on transactions (big transactions are more likely to contain conflicts). Also, getting all the edge cases right is hard with strict balance. Especially in the presence of deletions. It is VASTLY simpler with relaxed balance, though there are a few little tricks. If it was too easy, it wouldn't be any fun (see 3, below). Hint: Although the on-disk version doesn't need or want parent pointers, you might want them for your in-memory version of pages. 2. Separate the IO from the BTree-stuff. Conceptually keep a TVar (Map Address ByteString). In the transaction, use this to find pages. If the page is not there, throw an exception containing the desired address. In a wrapper, catch the exception, read the page, add it to the map as a separate transaction then retry the original transaction. I say "conceptually" because something like TArray Address (Maybe ByteString), or similar will yield much better concurrency. In general, you want to push the TVars down as far as possible. 3. Have Fun STM is very cool, so make sure you enjoy making it all hang together. :-) From bertram.felgenhauer at googlemail.com Tue Aug 21 00:02:57 2007 From: bertram.felgenhauer at googlemail.com (Bertram Felgenhauer) Date: Mon Aug 20 23:54:28 2007 Subject: [Haskell-cafe] "Tying the knot" with unknown keys In-Reply-To: <46C954F5.6020502@gmail.com> References: <46C954F5.6020502@gmail.com> Message-ID: <20070821040257.GA10992@zombie.inf.tu-dresden.de> David Ritchie MacIver wrote: > Essentially I have > > data FSM = State { transitions :: (Map Char FSM) } > > and > > transitions' :: Regexp -> Map Char Regexp > > I want to lift this so that the Regexps become states of the finite state > machine (while making sure I set up a loop in the data structure). Tying > the knot is the traditional way of doing such things, but we couldn't > figure out a way to make it work without the set of keys known in advance > because of the strictness of Map in its keys (an association list was > suggested, and that would probably work, but it seemed a bit ugly and would > be fairly inefficient). > > In the end what I did was just work out the set of reachable regexps in > advance and use a standard tying the knot trick, but it felt vaguely > unsatisfactory (and does some repeat work which I felt should be > unneccessary). Anyone have a more elegant suggestion? I have a solution that I like now, even though it involves quite a bit of code. Its core idea is very simple. The main ingredient is > data RegexpTrie a which is a data type that represents an infinite trie-like structure, indexed by regular expressions. It comes with a lookup function, > lookupRE :: RegexpTrie a -> Regexp -> a with the obvious semantics. It also provides a function to populate a trie, > populateRE :: (Regexp -> a) -> RegexpTrie a With these functions we can build a map of *all* regular expressions to their corresponding FSM. This is where the knot-tying takes place: > fsm :: RegexpTrie FSM > fsm = populateRE (\re -> > State { transitions = Map.map (lookupRE fsm) (transitions' re) } Finally, 'compile' becomes a trivial lookup, > compile :: Regexp -> FSM > compile x = lookupRE fsm x Detailed code can be found at http://hpaste.org/2341#a3 . enjoy, Bertram From ryani.spam at gmail.com Tue Aug 21 02:03:45 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Tue Aug 21 01:55:03 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <249599669.20070820181059@gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> <249599669.20070820181059@gmail.com> Message-ID: <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> Thanks to everyone, especially Bulat Ziganshin. In http://haskell.org/haskellwiki/Modern_array_libraries there is enough information to do what I want. It specifically mentions that it's OK to pass ByteArray# and MutableByteArray# to an "unsafe foreign" procedure as long as that procedure doesn't save the pointer, and that worked for me. Here is what I ended up using, which worked great and the FFI usage for a couple of key functions sped up my code by a large factor: import Data.Array.Base import Data.Array.IO.Internals import GHC.Exts {-# INLINE unsafeByteArrayToPtr #-} unsafeByteArrayToPtr :: IOUArray Int Word32 -> Ptr Word32 unsafeByteArrayToPtr (IOUArray (STUArray _ _ array#)) = Ptr (unsafeCoerce# array#) Possibly a better thing to do would be to declare that the call takes a MutableByteArray# directly in the foreign import statement, which I believe would let me avoid using unsafeCoerce# at all, but this was good enough for my purposes. Afterwards I used -ddump-simpl to check on the generated Core for the foreign call and it looked good. -- ryan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/a1deaa3c/attachment.htm From stefanor at cox.net Tue Aug 21 02:08:59 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Tue Aug 21 02:12:28 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> <249599669.20070820181059@gmail.com> <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> Message-ID: <20070821060859.GA6014@localhost.localdomain> On Mon, Aug 20, 2007 at 11:03:45PM -0700, Ryan Ingram wrote: > Thanks to everyone, especially Bulat Ziganshin. > > In http://haskell.org/haskellwiki/Modern_array_libraries there is enough > information to do what I want. It specifically mentions that it's OK to > pass ByteArray# and MutableByteArray# to an "unsafe foreign" procedure as > long as that procedure doesn't save the pointer, and that worked for me. > > Here is what I ended up using, which worked great and the FFI usage for a > couple of key functions sped up my code by a large factor: > import Data.Array.Base > import Data.Array.IO.Internals > import GHC.Exts > > {-# INLINE unsafeByteArrayToPtr #-} > unsafeByteArrayToPtr :: IOUArray Int Word32 -> Ptr Word32 > unsafeByteArrayToPtr (IOUArray (STUArray _ _ array#)) = Ptr (unsafeCoerce# > array#) > > Possibly a better thing to do would be to declare that the call takes a > MutableByteArray# directly in the foreign import statement, which I believe > would let me avoid using unsafeCoerce# at all, but this was good enough for > my purposes. > > Afterwards I used -ddump-simpl to check on the generated Core for the > foreign call and it looked good. Your code is broken in a most evil and insidious way. Addr# is an uninterpreted address. Since it might point to arbitrary memory, or even be a coerced integer, it is meaningless for the garbage collector to try to follow it. MutableByteArray#s are objects in the heap, and can move. If a garbage collection happens after the unsafeCoerce# but before the foreign call, then you will pass a dangling pointer to memcpy. Massive memory corruption will ensue. As it stands, 1. the garbage collector is only called when all threads run out of memory in their local 4k blocks and 2. the optimizer will eliminate all allocation between the Ptr construction and the call. So you'll never notice anything wrong. Suppose some unsuspecting developer tries to compile without optimizations. Then that Ptr construction will remain, and each time your function is called, there is a 1/32,768 chance of catastrophe. Unreproducable bugs are rarely reported, but they do add to people's impression of how unstable a language/library is. "But I can just add a comment saying -O only." Then suppose in the mists of future time one of those parameters of GHC itself that I described, changes. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/3a3ee425/attachment.bin From drtomc at gmail.com Tue Aug 21 02:21:23 2007 From: drtomc at gmail.com (Thomas Conway) Date: Tue Aug 21 02:12:42 2007 Subject: [Haskell-cafe] STM, IO and b-trees In-Reply-To: <9157df230708202241o7c134c7fgab1fe81dfd486aa8@mail.gmail.com> References: <9157df230708201852h45325fd3s98550d40e8611db2@mail.gmail.com> <784a62100708201910o3184dfceh958cf110cedf82db@mail.gmail.com> <9157df230708202241o7c134c7fgab1fe81dfd486aa8@mail.gmail.com> Message-ID: <784a62100708202321l33e309c9w711b9a9ac254a0ad@mail.gmail.com> On 8/21/07, Ben wrote: > some basic questions: you have limits on key and value size? fixed > page sizes per tree? I have chosen Yes and Yes respectively, though these are *choices*. Personally, I think fixed sized pages are fine. Handling unlimited sized keys is not hard, especially if you think they will be rare: you use a bit to flag an immediate key vs a remote key, and keep an overflow file for long keys. Another idea that I've had, though I have not had the opportunity to implement it is to use arithmetic coding on the keys. If you carve up the zero-to-one interval in sorted order, then the arithmetic coded bitstrings sort (lexicographically) in the same order as the uncompressed strings. From the top of my head, most *english* words can compress in this fashion with a 0 order model to about 2-3 bits per character. This doesn't eliminate a key length by itself, but it should increase the limit dramatically in practice. My implementation uses 64K pages, with a limit of 32K - 8 bytes on the size of an individual key. > on point 2: it sounds like you'r suggesting using STM after all. not > sure if i understand what you've said: something like type PagePtr t = TVar (Address, Maybe t) data Node = Node (PagePtr Node) [(Key,PagePtr Node)] | Leaf [(Key,Data)] > work with a page cache. do the various b-tree algorithms in STM > transactions on the cached pages. retry STM transactions when pages > aren't loaded. on successful STM transaction completion, write out the > dirty pages. Yes, except you might want to be clever about flushing dirty pages more lazily. My implementation isn't crash-proof (i.e. doesn't support crash recovery - the environment in which my code operated means that if something bad happens, I can rebuild from external data). > probably use the trick where the STM transaction returns > an IO action which you then perform. probably use ordinary page-level > locks to deal with concurrency on IO -- STM doesn't help. Maybe. See the SPJ video on STM. His basic point is that STM helps get rid of the stupid concurrency bugs, leaving just the "more interesting" ones for you to deal with. :-) Actually, using relaxed balance and making all the tree updates local, means that my btree code successfully supports a very high degree of concurrency. > as far as implementing the page cache: using a TVar Map would > essentially be creating a global lock on the entire cache. Exactly, which is why you want to push the TVars down. > so you > suggest using other implementations. your suggestion sounds like an > array with linear search, or probably something more sophisticated. i > would imagine a balanced binary tree where the nodes are TVars might > work nice, though rebalacing would touch a lot of nodes. (it does > seem strange haskell doesn't have more concurrent data structures.) Yes, I've chatted with Andrew Bromage about the need for Data.Map.Concurrent Data.Set.Concurrent etc. I have a concurrent hash table which works very nicely. Think class Hashable t where hash :: t -> Word64 type HashTable k v = TArray Word64 [(k,v)] Another alternative that others have suggested are Tries (radix trees). Something along the lines: type Trie v = .... insert :: [Bit] -> v -> Trie v -> STM () > on point 1: you're saying relaxed balance is better for STM-style > optimistic transactions? i'm using > > B-Trees with Relaxed Balance (1993) > Kim S. Larsen, Rolf Fagerberg > IPPS: 9th International Parallel Processing Symposium Yes. There's a tech report version which includes details of deletion which IIRC the one you mention does not. citeseer... google.... The reason I believe relaxed balance works particularly well with STM is that all the operations (insert, delete, rebalance) operate *locally*. That is, they only modify a single node or a couple of proximate nodes. In STM terms, this means a given operation only *writes* a couple of TVars close to where the operation took place. One of the cool things is that Larsen et al prove that as you progress up the tree the number of rebalancing operations drops geometrically. Effectively, this means you very rarely need to get a write-lock on the root (or top few nodes) of the tree, so randomly dispersed operations are unlikely to conflict with one another. Also, by separating the insert/delete bits from the rebalance bits, both are simpler to code, and you have fewer edge cases to think about. cheers, T -- Dr Thomas Conway drtomc@gmail.com Silence is the perfectest herald of joy: I were but little happy, if I could say how much. From ryani.spam at gmail.com Tue Aug 21 02:47:06 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Tue Aug 21 02:38:23 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <20070821060859.GA6014@localhost.localdomain> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> <249599669.20070820181059@gmail.com> <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> <20070821060859.GA6014@localhost.localdomain> Message-ID: <2f9b2d30708202347n1964e43am222d9326d9d2c525@mail.gmail.com> > Your code is broken in a most evil and insidious way. Interesting. This is for a toy project, so I'm not too worried, but lets say I wanted to do this "correctly" and I was set on using IOUArray for some reason. (The Haskell wiki claims that StorableArray is slower; is that actually the case?) Which of the following fixes would work now? Which has the lowest probability of not working in the future? 1) Declare f to take Addr# and don't construct a Ptr Word32 I suspect this would be enough unless the GC changed to some sort of continous GC which can happen even without an allocation 2) Declare f to take MutableByteArray# Is this good enough to make the collector happy? 3) Something else I haven't thought of? If there was no other option, and StorableArray wasn't slower, and I was working on a real project, I'd probably wrap my own around ForeignPtr like Data.ByteString. -- ryan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070820/f950e47b/attachment.htm From hughperkins at gmail.com Tue Aug 21 03:06:42 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 21 02:57:59 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> Message-ID: <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> On 8/11/07, Neil Bartlett wrote: > You're absolutely right that a dynamic/adaptive approach is the only > one that will work when the tasks are of unknown size. Whether this > approach is as easy as you think is open for you to prove. I look > forward to testing your VM implementation, Well... obviously migrating Haskell to use a VM is itself non-trivial ;-) There are two obstacles: - technical - political The technical obstacle means implementing it. Given that high performance VMs exist this is largely pure software engineering, rather than research? The political obstacle means: pursuading people to use it if it were written. If no-one uses it, it wont be maintained, and is basically pretty useless. The main reasons why it might not be used are: - breaks the status quo / de facto standard - provides no advantage in a single-core environment Breaking the status quo is not an inconsiderable obstacle, but it would be broken if there was a real advantage of using automatic threading, which there is not right now because most machines are single-cored. Whilst it's the right time to think about how to implement things, it's maybe a year or two early to actually implement it and expect people to use it. What I think is: - automatic threading is not really that hard. Once you've got a pure FP running in a VM, the actual automatic threading bit is pretty easy (largely software engineering, not research) - when machines become multicored, Microsoft will just take F# (which already runs in a VM I guess? but not sure if it's an FP-dedicated VM, they might need to build one), and just slot in the automatic threading bit. > or at the very least > reading your paper on the subject ;-) Writing a paper would be fun. I think I'm a little out of my depth to be writing a paper ;-) but just on the off-chance, how does one go about writing a paper and getting it published? Does one have to be a member of an accredited institution, or can one write one as a "freelancer"? If one has to be a member of an accredited institution, what are the options? From catamorphism at gmail.com Tue Aug 21 03:14:38 2007 From: catamorphism at gmail.com (Tim Chevalier) Date: Tue Aug 21 03:05:55 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> Message-ID: <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> On 8/21/07, Hugh Perkins wrote: > On 8/11/07, Neil Bartlett wrote: > > You're absolutely right that a dynamic/adaptive approach is the only > > one that will work when the tasks are of unknown size. Whether this > > approach is as easy as you think is open for you to prove. I look > > forward to testing your VM implementation, > > Well... obviously migrating Haskell to use a VM is itself non-trivial > ;-) There are two obstacles: > - technical > - political > > The technical obstacle means implementing it. Given that high > performance VMs exist this is largely pure software engineering, > rather than research? > GHCi, of course, is a bytecode interpreter, so that's sort of like a VM. You might start by looking at how GHCi works and see what you would need to change if performance rather than interactivity was your goal. > The political obstacle means: pursuading people to use it if it were > written. If no-one uses it, it wont be maintained, and is basically > pretty useless. The main reasons why it might not be used are: > - breaks the status quo / de facto standard > - provides no advantage in a single-core environment > > Breaking the status quo is not an inconsiderable obstacle, but it > would be broken if there was a real advantage of using automatic > threading, which there is not right now because most machines are > single-cored. Whilst it's the right time to think about how to > implement things, it's maybe a year or two early to actually implement > it and expect people to use it. > I don't think you have to worry too much about the political obstacles. People want automatic multithreading, and in a year or two we'll all have multicore boxen. In any case, if you don't solve the technical problems, the political ones will never surface; if you build it, people will come, or if they don't, you at least know something that you wouldn't have known if you didn't build it :-) > Writing a paper would be fun. I think I'm a little out of my depth to > be writing a paper ;-) but just on the off-chance, how does one go > about writing a paper and getting it published? Does one have to be a > member of an accredited institution, or can one write one as a > "freelancer"? If one has to be a member of an accredited institution, > what are the options? Anyone can submit a paper to a CS journal or conference. While most people who do so are affiliated with universities, research labs, or (more rarely) non-research companies, there are independent researchers out there, and sometimes you'll notice a paper where someone is listed by just their name with no affiliation. Conferences issue calls for papers (you might see some posted on this mailing list) that give you an idea for the rough format of the paper and submission guidelines. But really, you'll want to find a mentor who can give you advice on how to write a paper that will fit the mold. First come up with a technical result that you believe is paper-worthy, then find other people to talk to who can confirm that opinion and help you get your paper submitted :-) Cheers, Tim -- Tim Chevalier * catamorphism.org * Often in error, never in doubt "I cannot remember a time when I did not take it as understood that everybody has at least two, if not twenty-two, sides to him."--Robertson Davies From dons at cse.unsw.edu.au Tue Aug 21 03:19:54 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Tue Aug 21 03:11:20 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <2f9b2d30708202347n1964e43am222d9326d9d2c525@mail.gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> <249599669.20070820181059@gmail.com> <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> <20070821060859.GA6014@localhost.localdomain> <2f9b2d30708202347n1964e43am222d9326d9d2c525@mail.gmail.com> Message-ID: <20070821071954.GC14885@cse.unsw.EDU.AU> ryani.spam: > > > Your code is broken in a most evil and insidious way. > > > > Interesting. This is for a toy project, so I'm not too > worried, but lets say I wanted to do this "correctly" and I > was set on using IOUArray for some reason. (The Haskell wiki > claims that StorableArray is slower; is that actually the > case?) > > > > Which of the following fixes would work now? Which has the > lowest probability of not working in the future? > > > > 1) Declare f to take Addr# and don't construct a Ptr Word32 > > I suspect this would be enough unless the GC changed to > some sort of continous GC which can happen even without an > allocation > > > > 2) Declare f to take MutableByteArray# > > Is this good enough to make the collector happy? > > > > 3) Something else I haven't thought of? > > If there was no other option, and StorableArray wasn't > slower, and I was working on a real project, I'd probably > wrap my own around ForeignPtr like Data.ByteString. Yeah, we have ForeignPtr arrays and Foreign.Array /exactly/ for calling to C safely. I don't know why people suggest all these other dodgy solutions, when there's one that's guaranteed by the FFI spec to work. -- Don From stefanor at cox.net Tue Aug 21 03:19:34 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Tue Aug 21 03:24:16 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <2f9b2d30708202347n1964e43am222d9326d9d2c525@mail.gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> <249599669.20070820181059@gmail.com> <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> <20070821060859.GA6014@localhost.localdomain> <2f9b2d30708202347n1964e43am222d9326d9d2c525@mail.gmail.com> Message-ID: <20070821071934.GA6111@localhost.localdomain> On Mon, Aug 20, 2007 at 11:47:06PM -0700, Ryan Ingram wrote: > > Your code is broken in a most evil and insidious way. > > Interesting. This is for a toy project, so I'm not too worried, but lets > say I wanted to do this "correctly" and I was set on using IOUArray for some > reason. Heh, I'm a lot less worried now. (Somehow I thought this was going into a high-visibility library!) > (The Haskell wiki claims that StorableArray is slower; is that > actually the case?) Good question! I wrote a basic CA benchmark and a much simpler array benchmark, both parameterized by the array type, and couldn't get consistent results, so I'll take this as a "no". stefan@stefans:/tmp$ cat ArrayTest.hs {-# OPTIONS_GHC -fglasgow-exts -cpp #-} import Data.Array.MArray import Data.Bits import Data.Array.IO import Data.Array.Base import Data.Array.Storable import GHC.Exts -- #define ARRAY IOUArray -- uch! iter :: Int -> ARRAY Int Word -> IO () iter 4096 arr = arr `seq` return () iter ix arr = do unsafeWrite arr ix . succ =<< unsafeRead arr ix iter (ix+1) arr bench 100000 arr = arr `seq` return () bench ct arr = do iter 0 arr bench (ct+1) arr main = do arr <- newListArray (0,4095) [1..] bench 0 arr print =<< getElems arr stefan@stefans:/tmp$ ghc -fforce-recomp -DARRAY=IOUArray -O2 ArrayTest.hs && time ./a.out > /dev/null real 0m2.006s user 0m2.028s sys 0m0.008s stefan@stefans:/tmp$ ghc -fforce-recomp -DARRAY=StorableArray -O2 ArrayTest.hs && time ./a.out > /dev/null real 0m1.845s user 0m1.872s sys 0m0.004s stefan@stefans:/tmp$ > Which of the following fixes would work now? Which has the lowest > probability of not working in the future? > > 1) Declare f to take Addr# and don't construct a Ptr Word32 > I suspect this would be enough unless the GC changed to some sort of > continous GC which can happen even without an allocation Would work now, I think. > 2) Declare f to take MutableByteArray# > Is this good enough to make the collector happy? Maybe. In theory the collector should know that an argument passed to a foreign function as a pointer type, should be followed. I'd tentatively call it a bug if this breaks, but it's fragile enough that you should expect to find yourself reporting said bug. > 3) Something else I haven't thought of? > > If there was no other option, and StorableArray wasn't slower, and I was > working on a real project, I'd probably wrap my own around ForeignPtr like > Data.ByteString. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070821/ded5ed02/attachment.bin From bulat.ziganshin at gmail.com Tue Aug 21 03:38:29 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Tue Aug 21 03:34:21 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <20070821060859.GA6014@localhost.localdomain> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> <249599669.20070820181059@gmail.com> <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> <20070821060859.GA6014@localhost.localdomain> Message-ID: <628736005.20070821113829@gmail.com> Hello Stefan, Tuesday, August 21, 2007, 10:08:59 AM, you wrote: > Your code is broken in a most evil and insidious way. and this code, too? :) freezeSTUArray :: Ix i => STUArray s i e -> ST s (UArray i e) freezeSTUArray (STUArray l u marr#) = ST $ \s1# -> case sizeofMutableByteArray# marr# of { n# -> case newByteArray# n# s1# of { (# s2#, marr'# #) -> case unsafeCoerce# memcpy marr'# marr# n# s2# of { (# s3#, () #) -> case unsafeFreezeByteArray# marr'# s3# of { (# s4#, arr# #) -> (# s4#, UArray l u arr# #) }}}} > Unreproducable bugs are rarely reported, but they do add to people's > impression of how unstable a language/library is. -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From ryani.spam at gmail.com Tue Aug 21 03:50:22 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Tue Aug 21 03:41:39 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <628736005.20070821113829@gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> <249599669.20070820181059@gmail.com> <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> <20070821060859.GA6014@localhost.localdomain> <628736005.20070821113829@gmail.com> Message-ID: <2f9b2d30708210050t6d167189pb8f317e22eeb9668@mail.gmail.com> Ah, sneaky. That code is fine because it uses unsafeCoerce# on "memcpy", changing memcpy from whatever type it is, into MutableByteArray# s# -> MutableByteArray# s# -> Int# -> s# -> (# s#, () #) So as long as the GC understands MutableByteArray# it's safe; it's relying on the C calling convention being handled properly. On 8/21/07, Bulat Ziganshin wrote: > > Hello Stefan, > > Tuesday, August 21, 2007, 10:08:59 AM, you wrote: > > > Your code is broken in a most evil and insidious way. > > and this code, too? :) > > freezeSTUArray :: Ix i => STUArray s i e -> ST s (UArray i e) > freezeSTUArray (STUArray l u marr#) = ST $ \s1# -> > case sizeofMutableByteArray# marr# of { n# -> > case newByteArray# n# s1# of { (# s2#, marr'# #) -> > case unsafeCoerce# memcpy marr'# marr# n# s2# of { (# s3#, () #) -> > case unsafeFreezeByteArray# marr'# s3# of { (# s4#, arr# #) -> > (# s4#, UArray l u arr# #) }}}} > > > Unreproducable bugs are rarely reported, but they do add to people's > > impression of how unstable a language/library is. > > > > > -- > Best regards, > Bulat mailto:Bulat.Ziganshin@gmail.com > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070821/1e08898d/attachment.htm From ajb at spamcop.net Tue Aug 21 03:51:42 2007 From: ajb at spamcop.net (ajb@spamcop.net) Date: Tue Aug 21 03:42:59 2007 Subject: [Haskell-cafe] "Tying the knot" with unknown keys In-Reply-To: <46C954F5.6020502@gmail.com> References: <46C954F5.6020502@gmail.com> Message-ID: <20070821035142.mrvxtp87kccows8g@webmail.spamcop.net> G'day all. Quoting David Ritchie MacIver : > I was playing with some code for compiling regular expressions to > finite state machines and I ran into the following problem. I've solved > it, but I'm not terribly happy with my solution and was wondering if > someone could come up with a better one. :-) Doing structural induction is quite viable, as you noted. However, there are advantages to implementing explicit indirection. The main one is memory usage. Explicit indirection is much less leak-prone, and you can easily share structures thanks to hash consing. At any rate, I'm extremely curious as to how your code compares with mine, performance-wise: http://www.ninebynine.org/Software/HaskellRDF/Dfa/Dfa.lhs Cheers, Andrew Bromage From stefanor at cox.net Tue Aug 21 03:47:22 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Tue Aug 21 03:52:33 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <2f9b2d30708210050t6d167189pb8f317e22eeb9668@mail.gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> <249599669.20070820181059@gmail.com> <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> <20070821060859.GA6014@localhost.localdomain> <628736005.20070821113829@gmail.com> <2f9b2d30708210050t6d167189pb8f317e22eeb9668@mail.gmail.com> Message-ID: <20070821074722.GA6516@localhost.localdomain> On Tue, Aug 21, 2007 at 12:50:22AM -0700, Ryan Ingram wrote: > Ah, sneaky. That code is fine because it uses unsafeCoerce# on "memcpy", > changing memcpy from whatever type it is, into > MutableByteArray# s# -> MutableByteArray# s# -> Int# -> s# -> (# s#, () #) > > So as long as the GC understands MutableByteArray# it's safe; it's relying > on the C calling convention being handled properly. Which still isn't quite correct, because the code for base-2.1:Data.Array.Base.memcpy could still be perverse and trigger a GC. However, since base is version-locked to GHC, it can depend on as much undocumented behaviour as it needs. The worst that can happen is a few more testsuite failures when someone tries to change the compiler. > On 8/21/07, Bulat Ziganshin wrote: > > > > Hello Stefan, > > > > Tuesday, August 21, 2007, 10:08:59 AM, you wrote: > > > > > Your code is broken in a most evil and insidious way. > > > > and this code, too? :) > > > > freezeSTUArray :: Ix i => STUArray s i e -> ST s (UArray i e) > > freezeSTUArray (STUArray l u marr#) = ST $ \s1# -> > > case sizeofMutableByteArray# marr# of { n# -> > > case newByteArray# n# s1# of { (# s2#, marr'# #) -> > > case unsafeCoerce# memcpy marr'# marr# n# s2# of { (# s3#, () #) -> > > case unsafeFreezeByteArray# marr'# s3# of { (# s4#, arr# #) -> > > (# s4#, UArray l u arr# #) }}}} > > > > > Unreproducable bugs are rarely reported, but they do add to people's > > > impression of how unstable a language/library is. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070821/f0cf5205/attachment-0001.bin From david.maciver at gmail.com Tue Aug 21 04:20:36 2007 From: david.maciver at gmail.com (David Ritchie MacIver) Date: Tue Aug 21 04:11:58 2007 Subject: [Haskell-cafe] "Tying the knot" with unknown keys In-Reply-To: <20070821035142.mrvxtp87kccows8g@webmail.spamcop.net> References: <46C954F5.6020502@gmail.com> <20070821035142.mrvxtp87kccows8g@webmail.spamcop.net> Message-ID: <46CAA054.7030001@gmail.com> ajb@spamcop.net wrote: > G'day all. > > Quoting David Ritchie MacIver : > >> I was playing with some code for compiling regular expressions to >> finite state machines and I ran into the following problem. I've solved >> it, but I'm not terribly happy with my solution and was wondering if >> someone could come up with a better one. :-) > > Doing structural induction is quite viable, as you noted. > > However, there are advantages to implementing explicit indirection. > The main one is memory usage. Explicit indirection is much less > leak-prone, and you can easily share structures thanks to hash consing. > > At any rate, I'm extremely curious as to how your code compares with > mine, performance-wise: > > http://www.ninebynine.org/Software/HaskellRDF/Dfa/Dfa.lhs > > Cheers, > Andrew Bromage I'd be astonished if yours didn't beat mine hands down. I'm just putting this together as an exercise to help me figure out some of the areas where my Haskell knowledge is extremely weak. It's totally unoptimised. From bulat.ziganshin at gmail.com Tue Aug 21 04:57:28 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Tue Aug 21 04:53:09 2007 Subject: [Haskell-cafe] How can I pass IOUArrays to FFI functions? In-Reply-To: <2f9b2d30708202347n1964e43am222d9326d9d2c525@mail.gmail.com> References: <2f9b2d30708200527n338a1995r947d07fdd8f31495@mail.gmail.com> <249599669.20070820181059@gmail.com> <2f9b2d30708202303w28de6cb1m34faee14fac6f822@mail.gmail.com> <20070821060859.GA6014@localhost.localdomain> <2f9b2d30708202347n1964e43am222d9326d9d2c525@mail.gmail.com> Message-ID: <43332366.20070821125728@gmail.com> Hello Ryan, Tuesday, August 21, 2007, 10:47:06 AM, you wrote: >> Your code is broken in a most evil and insidious way. > ? > Interesting.? This is for a toy project, so I'm not too worried, > but lets say I wanted to do this "correctly" and I was set on using > IOUArray for some reason. (The Haskell wiki claims that > StorableArray is slower; is that actually the case?) it was in 6.4. in 6.6 it has the same speed as IOArray the Arrays wiki page was written primarily by me and suggestion to use unsafeCoerce# based solely on the code fragment i just citated. so this page is broken in that it says primarily about rather old 6.4 version and that it suggests unreliable trick without much understanding of ghc intrinsics :) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From Malcolm.Wallace at cs.york.ac.uk Tue Aug 21 06:39:28 2007 From: Malcolm.Wallace at cs.york.ac.uk (Malcolm Wallace) Date: Tue Aug 21 06:40:37 2007 Subject: [Haskell-cafe] can't build haxml under ghc 6.7, says HughesPJ is hidden... but ghc-pkg doesn't say it's hidden... In-Reply-To: References: <20070810133127.28ee0d30.Malcolm.Wallace@cs.york.ac.uk> Message-ID: <20070821113928.3a914293.Malcolm.Wallace@cs.york.ac.uk> I wrote: > > Just for information, the HaXml darcs repo has recently adopted the > > solution of containing two .cabal files, one for ghc-6.6.x, and the > > other for the split-base packages (>=ghc-6.7). Thomas Hartman wrote: > $ runghc Setup.hs configure > Setup.hs: Multiple description files found. Please use only one of : > ["HaXml.cabal","HaXml-darcs.cabal"] > > is there a way to specify which cabal file should be used, or do you > just have to move a file out out the way? For now, the latter (remove the unneeded file). Ultimately, the use of "Cabal Configurations" will allow us to revert to a single .cabal file with sections conditional on the compiler version. > Understanding this better is important to me because I am installing a > number of packages on 6.7, and am reluctant to send a patch that > breaks backwards compabitility with earlier versions. Multiple .cabal files are just a temporary measure for development ease. Neither ghc-6.7 nor this version of HaXml have been released officially, so you should not rely on any particular behaviour. Regards, Malcolm From phil at kantaka.co.uk Tue Aug 21 07:22:14 2007 From: phil at kantaka.co.uk (Philip Armstrong) Date: Tue Aug 21 07:13:30 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> Message-ID: <20070821112214.GA19563@kantaka.co.uk> On Mon, Aug 20, 2007 at 09:57:38PM +0100, Simon Peyton-Jones wrote: >GHC does some constant folding, but little by way of strength >reduction, or using shifts instead of multiplication. It's pretty >easy to add more: it's all done in a single module. Look at >primOpRules in the module PrelRules. > >Patches welcome! But please also supply test-suite tests that check > the correctness of the rules. Sucking another example out of comp.lang.functional: This: import System f :: Int -> Int -> Int f s n = if n > 0 then f (s+n) (n-1) else s main = do [n] <- getArgs putStrLn $ show $ f 0 (read n) is 3-4x slower than this: #include #include #include int f(int s, int n) { return n > 0 ? f(s+n, n-1) : s; } int main(int argc, char *argv[]) { assert(argc == 2); printf("%d\n", f(0, strtol(argv[1],0,0))); } The generated assembler suggests (if I've read it correctly) that gcc is spotting that it can replace the tail call with a jump in the C version, but for some reason it can't spot it for the Haskell version when compiling with -fvia-C (and neither does ghc itself using -fasm). So the haskell version ends up pushing and popping values on and off the stack for every call to f, which is a bit sad. Phil -- http://www.kantaka.co.uk/ .oOo. public key: http://www.kantaka.co.uk/gpg.txt From dons at cse.unsw.edu.au Tue Aug 21 07:57:29 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Tue Aug 21 07:49:30 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070821112214.GA19563@kantaka.co.uk> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <20070821112214.GA19563@kantaka.co.uk> Message-ID: <20070821115729.GA17399@cse.unsw.EDU.AU> phil: > On Mon, Aug 20, 2007 at 09:57:38PM +0100, Simon Peyton-Jones wrote: > >GHC does some constant folding, but little by way of strength > >reduction, or using shifts instead of multiplication. It's pretty > >easy to add more: it's all done in a single module. Look at > >primOpRules in the module PrelRules. > > > >Patches welcome! But please also supply test-suite tests that check > >the correctness of the rules. > > Sucking another example out of comp.lang.functional: > > This: > > import System > > f :: Int -> Int -> Int > f s n = if n > 0 then f (s+n) (n-1) else s > > main = do > [n] <- getArgs > putStrLn $ show $ f 0 (read n) > > is 3-4x slower than this: > > #include > #include > #include > > int f(int s, int n) { > return n > 0 ? f(s+n, n-1) : s; > } > > int main(int argc, char *argv[]) { > assert(argc == 2); > printf("%d\n", f(0, strtol(argv[1],0,0))); > } > > The generated assembler suggests (if I've read it correctly) that gcc > is spotting that it can replace the tail call with a jump in the C > version, but for some reason it can't spot it for the Haskell version > when compiling with -fvia-C (and neither does ghc itself using > -fasm). So the haskell version ends up pushing and popping values on > and off the stack for every call to f, which is a bit sad. > That doesn't sound quite right. The C version should get a tail call , with gcc -O2, the Haskell version should be a tail call anyway. Let's see: C $ gcc -O t.c -o t $ time ./t 1000000000 zsh: segmentation fault (core dumped) ./t 1000000000 ./t 1000000000 0.02s user 0.22s system 5% cpu 4.640 total Turning on -O2 $ time ./t 1000000000 -243309312 ./t 1000000000 1.89s user 0.00s system 97% cpu 1.940 total And GHC: $ ghc -O2 A.hs -o A $ time ./A 1000000000 -243309312 ./A 1000000000 3.21s user 0.01s system 97% cpu 3.289 total So, what, 1.6x slower than gcc -O2 Seems ok without any tuning. -- Don From overdrigzed at gmail.com Tue Aug 21 08:14:20 2007 From: overdrigzed at gmail.com (Rodrigo Queiro) Date: Tue Aug 21 08:05:38 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070821115729.GA17399@cse.unsw.EDU.AU> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <20070821112214.GA19563@kantaka.co.uk> <20070821115729.GA17399@cse.unsw.EDU.AU> Message-ID: <2eb8984a0708210514y210080c8p8cd4c5ee4d6618e1@mail.gmail.com> On my system, the C version runs about 9x faster than the haskell version (with -O3 and -O2 -fvia-c -optc-O3 respectively). However, GCC seems to produce about 70 lines of assembly for the main loop, compared to about 10 from GHC. I suspect the speed difference is the result of some heavy optimisation by GCC, which would need to be hand-tuned for GHC. (I would be interested to see what this would be. Unfortunately I don't know x86 assembly well enough to understand the GCC output.) On 21/08/07, Donald Bruce Stewart wrote: > phil: > > On Mon, Aug 20, 2007 at 09:57:38PM +0100, Simon Peyton-Jones wrote: > > >GHC does some constant folding, but little by way of strength > > >reduction, or using shifts instead of multiplication. It's pretty > > >easy to add more: it's all done in a single module. Look at > > >primOpRules in the module PrelRules. > > > > > >Patches welcome! But please also supply test-suite tests that check > > >the correctness of the rules. > > > > Sucking another example out of comp.lang.functional: > > > > This: > > > > import System > > > > f :: Int -> Int -> Int > > f s n = if n > 0 then f (s+n) (n-1) else s > > > > main = do > > [n] <- getArgs > > putStrLn $ show $ f 0 (read n) > > > > is 3-4x slower than this: > > > > #include > > #include > > #include > > > > int f(int s, int n) { > > return n > 0 ? f(s+n, n-1) : s; > > } > > > > int main(int argc, char *argv[]) { > > assert(argc == 2); > > printf("%d\n", f(0, strtol(argv[1],0,0))); > > } > > > > The generated assembler suggests (if I've read it correctly) that gcc > > is spotting that it can replace the tail call with a jump in the C > > version, but for some reason it can't spot it for the Haskell version > > when compiling with -fvia-C (and neither does ghc itself using > > -fasm). So the haskell version ends up pushing and popping values on > > and off the stack for every call to f, which is a bit sad. > > > > That doesn't sound quite right. The C version should get a tail call , > with gcc -O2, the Haskell version should be a tail call anyway. > > Let's see: > > C > $ gcc -O t.c -o t > $ time ./t 1000000000 > zsh: segmentation fault (core dumped) ./t 1000000000 > ./t 1000000000 0.02s user 0.22s system 5% cpu 4.640 total > > Turning on -O2 > > $ time ./t 1000000000 > -243309312 > ./t 1000000000 1.89s user 0.00s system 97% cpu 1.940 total > > > And GHC: > > $ ghc -O2 A.hs -o A > $ time ./A 1000000000 > -243309312 > ./A 1000000000 3.21s user 0.01s system 97% cpu 3.289 total > > So, what, 1.6x slower than gcc -O2 > Seems ok without any tuning. > > -- Don > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From haskell at list.mightyreason.com Tue Aug 21 08:24:28 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Tue Aug 21 08:16:12 2007 Subject: [Haskell-cafe] Re: "Tying the knot" with unknown keys In-Reply-To: <46C954F5.6020502@gmail.com> References: <46C954F5.6020502@gmail.com> Message-ID: <46CAD97C.7090002@list.mightyreason.com> David Ritchie MacIver wrote: > I was playing with some code for compiling regular expressions to finite > state machines and I ran into the following problem. I've solved it, but > I'm not terribly happy with my solution and was wondering if someone > could come up with a better one. :-) > > Essentially I have > > data FSM = State { transitions :: (Map Char FSM) } > > and > > transitions' :: Regexp -> Map Char Regexp > > I want to lift this so that the Regexps become states of the finite > state machine (while making sure I set up a loop in the data structure). > Tying the knot is the traditional way of doing such things, but we > couldn't figure out a way to make it work without the set of keys known > in advance because of the strictness of Map in its keys (an association > list was suggested, and that would probably work, but it seemed a bit > ugly and would be fairly inefficient). > > In the end what I did was just work out the set of reachable regexps in > advance and use a standard tying the knot trick, but it felt vaguely > unsatisfactory (and does some repeat work which I felt should be > unneccessary). Anyone have a more elegant suggestion? > > Regards, > David As others have pointed out, the decision to use Data.Map is a limiting issue. Another approach is the combinator method in CTK Light http://www.cse.unsw.edu.au/~chak/haskell/ctk/ which was specialized and enhanced for regexp in the regex-dfa package [1]. This lazily constructs a DFA from the regular expression. The "tying the knot" happens in the definition of the 'star' combinator (the '*' regexp character, also implied by '+'). The problem with this elegant definition is that it fails badly if the pattern being repeated might succeed after consuming zero characters (it hangs in an infinite loop). Other than that it is a wonderful definition: > type Regexp = Lexer -> Lexer > > -- star re1 re2 means repeat re1 follow with re2: "((re1)*)(re2)" > star :: Regexp -> Regexp -> Regexp > star re1 re2 = \l -> let self = re1 self >||< re2 l in self My regex-tdfa package did something quite different since it has to deal with a lot of extra complexity. It works in a few stages, in particular because it needs the NFA states to handle subexpression captures and because it has to handle anchors like ^ and $. String of regexp => Parsec extended regexp parser => parse tree data type parse tree => complicated analyzer (uses mdo) => smarter tree data type smarter tree => My complicated assembly monad (uses mdo) => Array Int NFA Where a simplified description of NFA is something like data NFA = NFA Int Trans data Trans = Trans (Map Char (Set Int))-- Might lead to more than one NFA state I could just as easily have made this data Trans = Trans (Map Char (Set NFA)) or data Trans = Trans (Map Char (Set Trans)) by doing a lazy lookup into the array, but it would then not have been as easy to make the DFA in the next step: Array Int NFA => Use of Trie indexed by (Set Int) => DFA Where a simplified DFA is like data DFA = DFA (Set Int) (Map Char DFA) and the Trie means I can lazily lookup any subset of NFA state and get their merge DFA state. So the procedure starts with a simple empty winning NFA to the "right" of the parse tree. The rexgexp tree walk is done in a monad which provides the supply of unique Int index when a new NFA state is created. The last NFA state to be created is the unique start state which always gets the largest Int index. The "tying the knot" trick in building the NFA was handled by walking the regexp parse tree where each node is attached to an NFA representing the future continuation from that node. The tricky case was the one that kills the simple "tying the knot" in CTK Light's method: when you have 'p*' and 'p' might match zero characters. The continuation needed to describe the future in that case had to be supplied in a more complicated form while walking 'p' to avoid the infinite looping. There are no mutable STRef/IORef variables. All the NFA nodes that are created during the monadic traversal are part of the final NFA (so there is no wasted work even though I make a single walk through the tree). The resulting NFA is not as minimal as the differentiation method since my traversal does not look at whether characters in the regexp are equal (my NFA builder is equivalent to treating all the regexp characters are distinct). But this also means I do not have the combinatoric explosion of regexps that the differentiation method can produce. I kept improving the design until it reproduced the same kinds of NFA graphs I could produce manually under those assumptions. The typical NFA state represents the condition "you have just accepted character X in the regexp". This is different from the Thompson NFA where states usually mean "you have just accepted a character leading to character X in the regexp". The NFA that regexp-tdfa produces * has no empty transitions * Captures extended regexp Posix semantics (difficult with empty matches) * handles anchors such as ^ and $ properly * efficiently handle inverted matches like [^a-z] with a default transition * Tracks parenthesized subexpression for later capture * Can handle very tricky cases like {n,m} repetitions Since it has no empty transitions the NFA states are also the simplest states of the DFA. And the DFA states are just merged subsets of the NFA states, thus a simple Trie works wonders. Advanced hints: Things like ((^|a)?b*($|c)?)* are ugly. Getting Posix patterns with {n,m} repetitions right was difficult -- and quick check found out that the Mac OS X regex.h actually contains a bug for some uses of {n,m} repetitions. -- Chris [1] http://hackage.haskell.org/cgi-bin/hackage-scripts/package/regex-dfa-0.91 From stefanor at cox.net Tue Aug 21 08:25:49 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Tue Aug 21 08:35:47 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <2eb8984a0708210514y210080c8p8cd4c5ee4d6618e1@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <20070821112214.GA19563@kantaka.co.uk> <20070821115729.GA17399@cse.unsw.EDU.AU> <2eb8984a0708210514y210080c8p8cd4c5ee4d6618e1@mail.gmail.com> Message-ID: <20070821122549.GA7504@localhost.localdomain> On Tue, Aug 21, 2007 at 01:14:20PM +0100, Rodrigo Queiro wrote: > On my system, the C version runs about 9x faster than the haskell > version (with -O3 and -O2 -fvia-c -optc-O3 respectively). However, GCC > seems to produce about 70 lines of assembly for the main loop, > compared to about 10 from GHC. I suspect the speed difference is the > result of some heavy optimisation by GCC, which would need to be > hand-tuned for GHC. (I would be interested to see what this would be. > Unfortunately I don't know x86 assembly well enough to understand the > GCC output.) The fundamental problem is that GHC doesn't have enough registers to to a good job with Haskell. Normal Haskell code makes extensive use of the GHC stack for function calls, the C stack for signal handlers, the capability base pointer for thread state, and the heap for everything else. Which doesn't really leave us in a good state for optimizing. In particular, x86 ghc ALWAYS passes parameters on the stack, even for tail calls. I didn't actually bother to check, but I'm pretty sure that's what the OP was noticing - if you look carefully it's not actually pushing or popping anything, just using stack memory. Situations are far better on x86_64 (16 registers) and ppc (32 registers). There is some work being done on the backend to improve this (in particular, a new and much better register allocator and a parameter-aware Cmm system). Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070821/80b68a93/attachment.bin From hughperkins at gmail.com Tue Aug 21 09:02:11 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 21 08:53:28 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> Message-ID: <837db430708210602n26d94186q7581465af529ed14@mail.gmail.com> On 8/21/07, Tim Chevalier wrote: > I don't think you have to worry too much about the political > obstacles. People want automatic multithreading, and in a year or two > we'll all have multicore boxen. In any case, if you don't solve the > technical problems, the political ones will never surface; if you > build it, people will come, or if they don't, you at least know > something that you wouldn't have known if you didn't build it :-) Ok, that's good encouragement. Practical question: I dont have a multicore box ;-) It's my main show-stopper right now. Any clues on how to get access to one, eg via ssh? 32-core or higher would be favorite ;-) but I guess even just a 4-core or so is enough for proof-of-concept? > GHCi, of course, is a bytecode interpreter, so that's sort of like a > VM. You might start by looking at how GHCi works and see what you > would need to change if performance rather than interactivity was your > goal. Yes, I guess two approaches are to take GHCi and make it handle automatic threading, but keeping the interactivity, ie not seeking to rival ghc in real performance, but merely providing a PoC, ... ... or build a minimal vm, enough to get 3 or 4 somewhat interesting algorithms / programs to run, and get automatic threading working on a couple of targets, eg on maps, and whatever [ x | x <- somelist ] these things are called. (folds are a little harder from an implementation point of view, so can be a future upgrade). > Anyone can submit a paper to a CS journal or conference. While most > people who do so are affiliated with universities, research labs, or > (more rarely) non-research companies, there are independent > researchers out there, and sometimes you'll notice a paper where > someone is listed by just their name with no affiliation. Again, that's quite encouraging :-) I'm far too lazy to sign my life away for 7 years of phd :-D (unless someone knows anyone looking for phd students in somewhere exotic like Paris, China or Singapore???), but working on it in my own time sounds fun. > First come up with a technical result that you believe is > paper-worthy I guess a "paperworthy technical result" doesnt have to be a fully fledged Haskell VM with in-depth automatic threading?, but either GHCi with some simple automatic threading, or a minimal vm implementation, again with some simple automatic threading? Basically, we give it one or three algorithms with automatic threading switched off, time execution, then run it on (ideally 32 or 64 cores but 4 is ok) a multicore machine, and show that the execution elapsed time is less? > But really, you'll want to find a mentor who > can give you advice on how to write a paper that will fit the mold. , then find other people to talk to who can confirm that > opinion and help you get your paper submitted :-) Would you or Neil fancy being a mentor for this, if I can start to get somewhere on it? From hughperkins at gmail.com Tue Aug 21 09:08:53 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 21 09:00:10 2007 Subject: [Haskell-cafe] Re: Bi-directional Maps In-Reply-To: <14cf844b0708201146w715809afs26f20b37ba09b852@mail.gmail.com> References: <14cf844b0708201146w715809afs26f20b37ba09b852@mail.gmail.com> Message-ID: <837db430708210608m442fcb9s7dc0bfca05cd8b40@mail.gmail.com> > Exactly. For this to work there needs to be the constraint that there's a > one-to-one mapping in each direction. The Bimap should have the uniqueness > promise that "Set (k, v)" gives. Yet you should be able to search on either > tuple value. Or... have the possibility of returning a list of values. Arguably there are two possible implementations, one that enforces one-to-one mapping, and one which allows multiple values, in either direction. "But how can you change a value if there are non-unique keys?". Well, you dont change a value, you change a list of values ;-) So, let's say our bimap is: 1,1 1,2 5,2 5,3 then: bimap_getvalue ourbimap 1 gives [1,2] bimap_getkey ourbimap 2 gives [1,5] Executing bimap_setkey ourbimap 2 [1,4] changes the bimap to: 1,1 1,2 4,2 5,3 From phil at kantaka.co.uk Tue Aug 21 09:19:10 2007 From: phil at kantaka.co.uk (Philip Armstrong) Date: Tue Aug 21 09:10:27 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070821122549.GA7504@localhost.localdomain> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <20070821112214.GA19563@kantaka.co.uk> <20070821115729.GA17399@cse.unsw.EDU.AU> <2eb8984a0708210514y210080c8p8cd4c5ee4d6618e1@mail.gmail.com> <20070821122549.GA7504@localhost.localdomain> Message-ID: <20070821131910.GA22562@kantaka.co.uk> On Tue, Aug 21, 2007 at 05:25:49AM -0700, Stefan O'Rear wrote: >On Tue, Aug 21, 2007 at 01:14:20PM +0100, Rodrigo Queiro wrote: >> On my system, the C version runs about 9x faster than the haskell >> version (with -O3 and -O2 -fvia-c -optc-O3 respectively). However, GCC >> seems to produce about 70 lines of assembly for the main loop, >> compared to about 10 from GHC. I suspect the speed difference is the >> result of some heavy optimisation by GCC, which would need to be >> hand-tuned for GHC. (I would be interested to see what this would be. >> Unfortunately I don't know x86 assembly well enough to understand the >> GCC output.) GCC is carrying out two major optimisations that ghc is missing here: replacing the tail call with a jump directly into the function body (having stuffed the correct arguments into the appropriate registers) and unrolling the loop. That's pretty much it. Neither are what I'd call 'heavy' optimisations. >The fundamental problem is that GHC doesn't have enough registers to to >a good job with Haskell. Normal Haskell code makes extensive use of >the GHC stack for function calls, the C stack for signal handlers, the >capability base pointer for thread state, and the heap for everything >else. Which doesn't really leave us in a good state for optimizing. In >particular, x86 ghc ALWAYS passes parameters on the stack, even for tail >calls. I didn't actually bother to check, but I'm pretty sure that's >what the OP was noticing - if you look carefully it's not actually >pushing or popping anything, just using stack memory. Yes, absolutely. >Situations are far better on x86_64 (16 registers) and ppc (32 >registers). There is some work being done on the backend to improve >this (in particular, a new and much better register allocator and a >parameter-aware Cmm system). Ouch. That's even worse: $ ./sum 100000000 C version: 0.16s Haskell : 1.40s Looking at the generated assembler, the ppc version has exactly the same problem that the x86 version does. It carries out the calculation, the stores the result in some memory locations and calls f again so that the preamble to f can pull those same results out of the memory locations in order to put them back into the same registers again! (I'm using ghc 6.6.1 on Debian unstable btw for anyone following along.) cheers, Phil -- http://www.kantaka.co.uk/ .oOo. public key: http://www.kantaka.co.uk/gpg.txt From afalloon at synopsys.com Tue Aug 21 09:31:16 2007 From: afalloon at synopsys.com (Al Falloon) Date: Tue Aug 21 09:23:16 2007 Subject: [Haskell-cafe] Re: I'm stuck in my thought experiment In-Reply-To: <46CA2F0F.3010109@optusnet.com.au> References: <46C4E9D5.5090503@optusnet.com.au> <46C59FDC.8060507@synopsys.com> <46CA2F0F.3010109@optusnet.com.au> Message-ID: <46CAE924.2040001@synopsys.com> Levi Stephen wrote: > Al Falloon wrote: >> This code seems to indicate that you want to be able to extend the >> widget types without changing this source file. This is a good goal, >> but it may not be worth the extra complexity. > > Ideally, I'd like Widgets to be added through hs-plugins or similar. That > is a ideal goal though, not a necessity. >> Also, this looks a lot like the Composite pattern from OO. A rule of >> thumb that I use is: "if I would do this with inheritance in OO, I >> probably want a variant in FP". Since Composite depends on the >> inheritance of the composite object type, I would probably look to use >> a single data type with multiple constructors for the different >> compisites like the Widget type above. > > Interesting. I've been curious how OO concepts can map to FP, as most specs > (consider stuff like DOM) seem to be written with OO implementaitons in > mind. This is a very interesting discussion that could be its own text book (or flame war) as far as I can tell, the only answer everyone agrres on is "it depends". After that it gets a little hairy. For me, I find that the best method is to just come at the problem fresh using an FP approach, and don't worry about 'mapping' the concepts. >> If I wanted to develop the widgets themselves separately from the >> layout, I would probably do something like this: >> >> class Widget a where >> render :: a -> Html >> bbox :: a -> Size >> >> type Layout = forall a. Widget a => Widget a >> | Rows Spacing [Layout] >> | Columns Spacing [Layout] >> | Grid Spacing [[Layout]] >> >> type Page = Page String Layout >> >> renderLayout :: Layout -> Html >> >> renderPage :: Page -> Html > > I'm unsure this gives what I'm after. I'm trying to have layouts consist > of Widgets (e.g., header images, common menu), and as pages also consist > of Widgets it seems like they can be modelled using a common > type/construct. Well if you want to abstract over the layout too, you can just add instance Widget Layout where render = renderLayout bbox = ... But just because you can, doesn't mean you should. I don't know the full details of your design, but what do you gain by allowing the layout to intermingle with the widgets? Is worth the extra complexity? If you treat layout as "just another widget" then it becomes harder to answer specific questions about the page layout because you have less information in your tree. >> So you want some sort of wildcard element that can be substituted in >> later? Maybe I am misunderstanding your requirement, but if thats the >> behavior you want, you should check out the term-level evaluators for >> lambda calculus for inspiration on substitution, but I expect your >> requirement may be simpler than that. > > I'm thinking a BlankWidget or ReplacableWidget is a fairly simple > option. They could be named for the case of multiple replacements, and > have a method similar to > > -- src -> replacements -> result > replaceWidgets :: Widget -> [(String,Widget)] -> Widget > > which replaces all ReplacableWidgets in the source Widget with those > specified. > > Would you happen to have some links on the evaluators for lambda > calculus you talk about? I'm not as familiar as I should be with lambda > calculus They are surprisingly hard to find! It must be one of those things that is so ingrained that no-one thinks to write it down. Anyway, the closest I could find to what I meant is the "Interpretive Haskell programmer" heading in "The evolution of a Haskell programmer" http://www.willamette.edu/~fruehr/haskell/evolution.hs However, now that I look at your example again, I may have been too quick to answer with "LC evaluator!" because your language only has substitution and not abstraction (defining functions) so you don't have much of the complexity to contend with. The obvious implementation of replaceWidgets will probably work fine for you. >>> It might be simple to have a PlaceHolderWidget. Then insertions of >>> the child page >>> content happens at each of those widgets. >> >>> This just gets trickier if I start considering multiple extension >>> points for child >>> pages and what happens when the layout/parent page changes. This is >>> why I'm >>> thinking I may be going along a bad path here. >> >> Exactly. With multiple substitutions you get into issues of naming, so >> thats why looking at lambda calculus evaluators would be the right >> inspiration, but I think it may be more complicated than you need. The >> zipper approach might be easier. > > I think I will try and investigate both approaches. I'm after the > process here, rather than the end result Good luck. You can learn a lot just by lurking on the cafe and reading some of the better blogs. The papers are also good reading, I have a "rule of 2" if I have heard the title come up twice, I read it. From apfelmus at quantentunnel.de Tue Aug 21 09:37:24 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Tue Aug 21 09:29:53 2007 Subject: [Haskell-cafe] Re: Bi-directional Maps In-Reply-To: <837db430708210608m442fcb9s7dc0bfca05cd8b40@mail.gmail.com> References: <14cf844b0708201146w715809afs26f20b37ba09b852@mail.gmail.com> <837db430708210608m442fcb9s7dc0bfca05cd8b40@mail.gmail.com> Message-ID: Hugh Perkins wrote: >> Exactly. For this to work there needs to be the constraint that there's a >> one-to-one mapping in each direction. The Bimap should have the uniqueness >> promise that "Set (k, v)" gives. Yet you should be able to search on either >> tuple value. > > Or... have the possibility of returning a list of values. > > Arguably there are two possible implementations, one that enforces > one-to-one mapping, and one which allows multiple values, in either > direction. Terminology reminder :) - the latter is called "(binary) relation" http://en.wikipedia.org/wiki/Binary_relation - the former would be a "bijection" http://en.wikipedia.org/wiki/Bijective_map Regards, apfelmus From phil at kantaka.co.uk Tue Aug 21 09:39:03 2007 From: phil at kantaka.co.uk (Philip Armstrong) Date: Tue Aug 21 09:30:20 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <2eb8984a0708210514y210080c8p8cd4c5ee4d6618e1@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <20070821112214.GA19563@kantaka.co.uk> <20070821115729.GA17399@cse.unsw.EDU.AU> <2eb8984a0708210514y210080c8p8cd4c5ee4d6618e1@mail.gmail.com> Message-ID: <20070821133903.GA23774@kantaka.co.uk> Don's reply didn't reach me for some reason, but pulling it out of the previous response: >On 21/08/07, Donald Bruce Stewart wrote: >> phil: >> > The generated assembler suggests (if I've read it correctly) that gcc >> > is spotting that it can replace the tail call with a jump in the C >> > version, but for some reason it can't spot it for the Haskell version >> > when compiling with -fvia-C (and neither does ghc itself using >> > -fasm). So the haskell version ends up pushing and popping values on >> > and off the stack for every call to f, which is a bit sad. >> > >> >> That doesn't sound quite right. The C version should get a tail call , >> with gcc -O2, the Haskell version should be a tail call anyway. Just to be clear; the Haskell version is a tail call, but it's pushing the values to and from memory (well, cache really of course) for every call to f, which is killing the performance. >> Let's see: >> >> C >> $ gcc -O t.c -o t >> $ time ./t 1000000000 >> zsh: segmentation fault (core dumped) ./t 1000000000 >> ./t 1000000000 0.02s user 0.22s system 5% cpu 4.640 total >> >> Turning on -O2 >> >> $ time ./t 1000000000 >> -243309312 >> ./t 1000000000 1.89s user 0.00s system 97% cpu 1.940 total -O3 does better thanks to the loop unrolling, see timings bellow. >> And GHC: >> >> $ ghc -O2 A.hs -o A >> $ time ./A 1000000000 >> -243309312 >> ./A 1000000000 3.21s user 0.01s system 97% cpu 3.289 total >> >> So, what, 1.6x slower than gcc -O2 >> Seems ok without any tuning. You're getting much better timings than I am! $ time -p ./sum-hs 1000000000 -243309312 real 3.75 user 3.70 $ time -p ./sum-c-O2 1000000000 -243309312 real 1.40 user 1.35 $ time -p ./sum-c-O3 1000000000 -243309312 real 1.21 user 1.18 (My box has a AMD Athlon64 3000+ CPU fwiw, but the powerpc version is even worse when compared to it's respective C binary!) Phil -- http://www.kantaka.co.uk/ .oOo. public key: http://www.kantaka.co.uk/gpg.txt From hughperkins at gmail.com Tue Aug 21 09:39:32 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 21 09:30:48 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070820192248.GE3098@localhost.localdomain> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46C9CFB3.9050007@btinternet.com> <20070820192248.GE3098@localhost.localdomain> Message-ID: <837db430708210639kf4e5231xed8a265fb0f4614a@mail.gmail.com> On 8/21/07, Stefan O'Rear wrote: > Currently, it's never worse. GHC's backend is about as good as GCC; > most of the optimiations it doesn't do are not possible for GCC because > of various lack-of-information problems (the stack pointer never aliases > the heap pointer, stuff like that). It's conceivable that at some point > -fasm will be faster, because you have the possibility of much more > accurate aliasing information inside the compiler, than can be coded in > C. In the meantime, note that the runtime difference is less than 3% > and the compile time difference is over 100%, so it's only worthwhile if > you expect *this version* of your program to be used more than 30 times, > ie releases only. Wait, you're saying that ghc can produce "pure" c-code, that doesnt contain any assembly code, and that runs as fast as ghc code that does contain assembly? Sooo.... if I was feeling "evil", could I take this c-code and pipe it into something that turns it into C#??? If it contains lots of macros (or any macros at all perhaps...), this becomes non-trivial, but otherwise I think most things in C can be mapped fairly trivially to C#? (It's a one-way mapping of course, eg "delete" in C is simply dropped when mapped to c#). (Not that I have any good reason to do this, simply... fun). From hughperkins at gmail.com Tue Aug 21 09:42:17 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 21 09:33:33 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <837db430708210639kf4e5231xed8a265fb0f4614a@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46C9CFB3.9050007@btinternet.com> <20070820192248.GE3098@localhost.localdomain> <837db430708210639kf4e5231xed8a265fb0f4614a@mail.gmail.com> Message-ID: <837db430708210642u359eba21u7ea0e32a56f0aca0@mail.gmail.com> > eg "delete" in C is simply dropped when mapped to c#). (errrr... obviously delete doenst exist in C :-D it would be free... or something... :-D ) From ndmitchell at gmail.com Tue Aug 21 09:50:27 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Tue Aug 21 09:41:43 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <837db430708210639kf4e5231xed8a265fb0f4614a@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46C9CFB3.9050007@btinternet.com> <20070820192248.GE3098@localhost.localdomain> <837db430708210639kf4e5231xed8a265fb0f4614a@mail.gmail.com> Message-ID: <404396ef0708210650u2e3d6f13s6aef983f6e34cd6b@mail.gmail.com> Hi > Wait, you're saying that ghc can produce "pure" c-code, that doesnt > contain any assembly code, and that runs as fast as ghc code that does > contain assembly? No. It can produce pure C code (unregistered), but to get high performance it processes the output assembly afterwards (registered). > Sooo.... if I was feeling "evil", could I take this c-code and pipe it > into something that turns it into C#??? You might be able to. Much easier would be to use Yhc and pass the --dotnet flag which generates .NET binaries natively. > macros (or any macros at all perhaps...), this becomes non-trivial, > but otherwise I think most things in C can be mapped fairly trivially > to C#? (It's a one-way mapping of course, eg "delete" in C is simply > dropped when mapped to c#). There isn't going to be much free/delete, its all a garbage collected heap. Thanks Neil From stefanor at cox.net Tue Aug 21 09:39:11 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Tue Aug 21 09:50:25 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <837db430708210639kf4e5231xed8a265fb0f4614a@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46C9CFB3.9050007@btinternet.com> <20070820192248.GE3098@localhost.localdomain> <837db430708210639kf4e5231xed8a265fb0f4614a@mail.gmail.com> Message-ID: <20070821133911.GA7715@localhost.localdomain> On Tue, Aug 21, 2007 at 09:39:32PM +0800, Hugh Perkins wrote: > On 8/21/07, Stefan O'Rear wrote: > > Currently, it's never worse. GHC's backend is about as good as GCC; > > most of the optimiations it doesn't do are not possible for GCC because > > of various lack-of-information problems (the stack pointer never aliases > > the heap pointer, stuff like that). It's conceivable that at some point > > -fasm will be faster, because you have the possibility of much more > > accurate aliasing information inside the compiler, than can be coded in > > C. In the meantime, note that the runtime difference is less than 3% > > and the compile time difference is over 100%, so it's only worthwhile if > > you expect *this version* of your program to be used more than 30 times, > > ie releases only. > > Wait, you're saying that ghc can produce "pure" c-code, that doesnt > contain any assembly code, and that runs as fast as ghc code that does > contain assembly? No. Name: Registerized C Performance: 1.00 Flags: -fvia-C C, but with gcc and machine specific hacks to implement general tail calls and (most notably) register global variables. Name: Native code generator Performance: 0.97 Flags: -fasm GHC's own mini C compiler converts the internal C-- data into assembly code, which is then piped to gas. Name: Unregisterized C Performance: 0.40 Flags: -unreg Generates near-ANSI C, using memory variables for the VM's registers and the returning function pointer hack seen in oh so many Scheme compilers. Good for early stages of porting, and not much else. Name: Byte-code Performance: 0.05 Flags: -fbyte-code (GHCi HEAD only) Generates a compact form of STG code, and then interprets it. A generally quite bad idea, whose main redeeming feature is that it doesn't require starting the GNU toolchain. > Sooo.... if I was feeling "evil", could I take this c-code and pipe it > into something that turns it into C#??? Yes. You could do the same with the original haskell. It's called a compiler. > If it contains lots of macros (or any macros at all perhaps...), this > becomes non-trivial, I fail to see how macros have anything to do with this. Especially since cpp removes them all. > but otherwise I think most things in C can be mapped fairly trivially > to C#? Unsafe C#, sure. Haskell's type system is strictly more expressive than C#, and you need to sacrifice either machine efficiency or checked safety. > (It's a one-way mapping of course, eg "delete" in C is simply dropped > when mapped to c#). There is no delete in C, and even if there was, GHC wouldn't use it. Allocation is *the* major bottleneck of functional programs, and having a custom allocator inlined into every call site is vital to have usable performance. > (Not that I have any good reason to do this, simply... fun). Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070821/ffb7dc94/attachment.bin From keith at oreilly.com Tue Aug 21 10:48:44 2007 From: keith at oreilly.com (Keith Fahlgren) Date: Tue Aug 21 10:40:01 2007 Subject: [Haskell-cafe] ANN: SF Bay Area Functional Programmers Group Message-ID: <46CAFB4C.3030806@oreilly.com> Hi All, I'd like to announce the formation of the Bay Area Functional Programmers group. This group is for anyone using or interested in functional programming and functional programming languages, particularly strongly typed languages such as Haskell, OCaml, SML, etc. The first meeting will be Thursday, September 13th at 7:30pm somewhere in San Francisco. Please join the mailing list at http://groups.google.com/group/bayfp and suggest a location. The initial meeting will be a casual pizza and beer get together, although going forward we'd like to also include speakers, reading and discussion of technical papers, and some hands on coding. Future announcements and the location of the first meeting will be posted to the BayFP mailing list. More information will be available on the website: http://bayfp.org/. Keith (+ Mike Wells) From bf3 at telenet.be Tue Aug 21 11:07:47 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Tue Aug 21 10:58:45 2007 Subject: [Haskell-cafe] Generic data constructor in pattern? Message-ID: <00c901c7e405$08923f00$19b6bd00$@be> Consider the following example code: data Vector = V Float Float data Matrix = M Vector Vector liftV1 f (V x y) = V (f x) (f y) liftV2 f (V x1 y1) (V x2 y2) = V (f x1 x2) (f y1 y2) liftM1 f (M x y) = M (f x) (f y) liftM2 f (M x1 y1) (M x2 y2) = M (f x1 x2) (f y1 y2) Both pairs of lift functions have almost identical implementations. Can I merge these somehow? I know data constructors are first class values and are not types, but if I want to merge these lift functions I have to write something like lift1 f (d x y) = d (f x) (f y) lift2 f (d x1 y1) (d x2 y2) = d (f x1 x2) (f y1 y2) But this does not work, as the pattern matcher does not seem to like this. Thanks, Peter Verswyvelen PS: Of course I could define a single type like: data Pair a = P a a type Vector = Pair Float type Matrix = Pair Vector lift1 f (P x y) = P (f x) (f y) lift2 f (P x1 y1) (P x2 y2) = P (f x1 x2) (f y1 y2) But that's beside the question :) From ndmitchell at gmail.com Tue Aug 21 11:24:13 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Tue Aug 21 11:15:28 2007 Subject: [Haskell-cafe] Generic data constructor in pattern? In-Reply-To: <00c901c7e405$08923f00$19b6bd00$@be> References: <00c901c7e405$08923f00$19b6bd00$@be> Message-ID: <404396ef0708210824l4dd747eaua0601fe7b0725817@mail.gmail.com> Hi Peter, > liftV1 f (V x y) = V (f x) (f y) > liftV2 f (V x1 y1) (V x2 y2) = V (f x1 x2) (f y1 y2) > > liftM1 f (M x y) = M (f x) (f y) > liftM2 f (M x1 y1) (M x2 y2) = M (f x1 x2) (f y1 y2) > Both pairs of lift functions have almost identical implementations. Can I > merge these somehow? Using the Uniplate library the first already has a name, its called "descend". The second does not, but could be implemented in Uniplate if you wanted. descend2 :: Biplate a b => (b -> b -> b) -> a -> a -> a descend2 f a b = a2 (zipWith f as bs) where (as, a2) = uniplate a (bs, b2) = uniplate b For full details see the website: http://www-users.cs.york.ac.uk/~ndm/uniplate/ Thanks Neil From lemming at henning-thielemann.de Tue Aug 21 11:53:46 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Tue Aug 21 11:45:08 2007 Subject: [Haskell-cafe] Generic data constructor in pattern? In-Reply-To: <00c901c7e405$08923f00$19b6bd00$@be> References: <00c901c7e405$08923f00$19b6bd00$@be> Message-ID: On Tue, 21 Aug 2007, Peter Verswyvelen wrote: > Consider the following example code: > > data Vector = V Float Float > data Matrix = M Vector Vector > > liftV1 f (V x y) = V (f x) (f y) > liftV2 f (V x1 y1) (V x2 y2) = V (f x1 x2) (f y1 y2) > > liftM1 f (M x y) = M (f x) (f y) > liftM2 f (M x1 y1) (M x2 y2) = M (f x1 x2) (f y1 y2) > > Both pairs of lift functions have almost identical implementations. Can I > merge these somehow? I know data constructors are first class values and are > not types, but if I want to merge these lift functions I have to write > something like Maybe you are happy with instances of Control.Applicative (GHC-6.6) http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html (untested code follows) data Vector a = Vector a a instance Functor a where fmap f (Vector x y) = Vector (f x) (f y) instance Applicative pure x = Vector x x (Vector fx fy) <*> (Vector x y) = Vector (fx x) (fy y) pure f <*> vx pure f2 <*> vx <*> vy However, I'm not convinced that your code becomes more readable or flexible by this change. From bf3 at telenet.be Tue Aug 21 12:53:43 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Tue Aug 21 12:44:44 2007 Subject: [Haskell-cafe] Yet another stupid question about numeric conversion In-Reply-To: <00c901c7e405$08923f00$19b6bd00$@be> References: <00c901c7e405$08923f00$19b6bd00$@be> Message-ID: <00d501c7e413$d52c4bb0$7f84e310$@be> Does a general approach exist to convert any non-constant (Num a) to a Float? Not using type annotation of course. Now I wrote a Convert class that has a toFloat function which I instantiate for all different numeric types, but as all these toFloat/toInt functions disappeared a long time ago from Haskell, it feels like a bad idea to reintroduce them locally in my code... Thanks (again!) Peter Verswyvelen From lennart at augustsson.net Tue Aug 21 13:09:23 2007 From: lennart at augustsson.net (Lennart Augustsson) Date: Tue Aug 21 13:00:39 2007 Subject: [Haskell-cafe] Yet another stupid question about numeric conversion In-Reply-To: <00d501c7e413$d52c4bb0$7f84e310$@be> References: <00c901c7e405$08923f00$19b6bd00$@be> <00d501c7e413$d52c4bb0$7f84e310$@be> Message-ID: How can you hope to convert an arbitrary Num to a Float? Num contains things like complex numbers that don't have any reasonable translation to a Float. But anyway, realToFrac is a good conversion function. -- Lennart On 8/21/07, Peter Verswyvelen wrote: > > Does a general approach exist to convert any non-constant (Num a) to a > Float? Not using type annotation of course. > > Now I wrote a Convert class that has a toFloat function which I > instantiate > for all different numeric types, but as all these toFloat/toInt functions > disappeared a long time ago from Haskell, it feels like a bad idea to > reintroduce them locally in my code... > > Thanks (again!) > Peter Verswyvelen > > > _______________________________________________ > 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/haskell-cafe/attachments/20070821/724c54da/attachment.htm From andrewcoppin at btinternet.com Tue Aug 21 13:25:47 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Tue Aug 21 13:16:09 2007 Subject: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <20070820191526.GD3098@localhost.localdomain> References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> <20070820191526.GD3098@localhost.localdomain> Message-ID: <46CB201B.3040803@btinternet.com> Stefan O'Rear wrote: > sum = sum' 0 > sum' k [] = k > sum' k (x:xs) = (sum' $! (k+x)) xs > > enum x y | x >= y = 0 > | otherwise = x : enum (x+1) y > > > sum (enum 1 10) => > sum' 0 (enum 1 10) => > sum' 0 (1 : enum (1+1) 10) => > (sum' $! (0+1)) (enum (1+1) 10) => > sum' 1 (enum (1+1) 10) => > > sum' 1 (2 : enum (2+1) 10) => > (sum' $! (1+2)) (enum (2+1) 10) => > sum' 3 (enum (2+1) 10) => > > sum' 3 (3 : enum (3+1) 10) => > (sum' $! (3+3)) (enum (3+1) 10) => > sum' 6 (enum (3+1) 10) => > > sum' 6 (4 : enum (4+1) 10) => > (sum' $! (6+4)) (enum (4+1) 10) => > sum' 10 (enum (4+1) 10) => > > ... > > > sum' 36 (9 : enum (9+1) 10) => > (sum' $! (36+9)) (enum (9+1) 10) => > sum' 45 (enum (9+1) 10) => > sum' 45 [] => > 45 > > (I need to find some way to automate making these trails :) ) > I did have a fairly small Tcl implementation for this... I don't have the code now, and I wrote it early in my Haskell career, so there's masses of stuff it didn't handle. (*cough* type classes) Actually, I've often longed for some tool (maybe even integrated into Lambdabot) to show the reduction sequence of an arbitrary expression. But none exists, AFAIK... From andrewcoppin at btinternet.com Tue Aug 21 13:26:47 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Tue Aug 21 13:17:09 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> Message-ID: <46CB2057.90303@btinternet.com> Simon Peyton-Jones wrote: > GHC does some constant folding, but little by way of strength reduction, or using shifts instead of multiplication. It's pretty easy to add more: it's all done in a single module. Look at primOpRules in the module PrelRules. > > Patches welcome! But please also supply test-suite tests that check the correctness of the rules. > So... you mean it's source-level transformation rules? (Rather than wired into the compiler itself somewhere.) From andrewcoppin at btinternet.com Tue Aug 21 13:29:21 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Tue Aug 21 13:19:46 2007 Subject: [Haskell-cafe] #haskell irc channel reaches 400 users In-Reply-To: <20070821003329.GA13546@cse.unsw.EDU.AU> References: <20070821003329.GA13546@cse.unsw.EDU.AU> Message-ID: <46CB20F1.2080104@btinternet.com> Donald Bruce Stewart wrote: > This puts the channel at around the 13th largest community of the 5500 > freenode channels. For comparision, a sample of the state of the other > language communities: > > #php 485 > #perl 472 > ##c++ 457 > ##c 445 > #python 430 > #ruby-lang 420 > > > #haskell 411 > > #lisp 246 > ##java 236 > ##javascript 226 > #perl6 144 > #scheme 139 > #erlang 118 > #lua 105 > #ocaml 58 > ...does this mean Haskell is officially harder to understand than Lisp, Java, Perl and O'Caml? :-} (OTOH, does this mean Haskell is easier to understand than PHP or C++?) From andrewcoppin at btinternet.com Tue Aug 21 13:32:55 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Tue Aug 21 13:23:18 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <20070810050139.GU3382@cse.unsw.EDU.AU> <837db430708092219i278638a9j37bebf56cdd1003@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> Message-ID: <46CB21C7.4070708@btinternet.com> Tim Chevalier wrote: > Anyone can submit a paper to a CS journal or conference. While most > people who do so are affiliated with universities, research labs, or > (more rarely) non-research companies, there are independent > researchers out there, and sometimes you'll notice a paper where > someone is listed by just their name with no affiliation. Conferences > issue calls for papers (you might see some posted on this mailing > list) that give you an idea for the rough format of the paper and > submission guidelines. But really, you'll want to find a mentor who > can give you advice on how to write a paper that will fit the mold. > First come up with a technical result that you believe is > paper-worthy, then find other people to talk to who can confirm that > opinion and help you get your paper submitted :-) > I highly doubt that automatic threading will happen any time this decade - but I just learned something worth while from reading this email. ;-) From simonpj at microsoft.com Tue Aug 21 14:02:37 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Tue Aug 21 13:53:50 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46CB2057.90303@btinternet.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> Message-ID: | > GHC does some constant folding, but little by way of strength | reduction, or using shifts instead of multiplication. It's pretty easy | to add more: it's all done in a single module. Look at primOpRules in | the module PrelRules. | > | > Patches welcome! But please also supply test-suite tests that check | the correctness of the rules. | > | | So... you mean it's source-level transformation rules? (Rather than | wired into the compiler itself somewhere.) No, constant folding is part of the compiler, I'm afraid, in the module PrelRules. Simon From apfelmus at quantentunnel.de Tue Aug 21 14:06:42 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Tue Aug 21 13:58:07 2007 Subject: [Haskell-cafe] Re: Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <20070820191526.GD3098@localhost.localdomain> References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> <20070820191526.GD3098@localhost.localdomain> Message-ID: Stefan O'Rear wrote: > sum (enum 1 10) => > sum' 0 (enum 1 10) => > ... > > sum' 36 (9 : enum (9+1) 10) => > (sum' $! (36+9)) (enum (9+1) 10) => > sum' 45 (enum (9+1) 10) => > sum' 45 [] => > 45 > > (I need to find some way to automate making these trails :) ) Yes! We'd need such an automatic tool for the wikibook, too. Regards, apfelmus From hjgtuyl at chello.nl Tue Aug 21 14:18:31 2007 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Tue Aug 21 14:09:36 2007 Subject: [Haskell-cafe] Yet another stupid question about numeric conversion In-Reply-To: <00d501c7e413$d52c4bb0$7f84e310$@be> References: <00c901c7e405$08923f00$19b6bd00$@be> <00d501c7e413$d52c4bb0$7f84e310$@be> Message-ID: On Tue, 21 Aug 2007 18:53:43 +0200, Peter Verswyvelen wrote: > Does a general approach exist to convert any non-constant (Num a) to a > Float? Not using type annotation of course. Instances of class Integral (Int and Integer) can be converted with fromIntegral. -- Met vriendelijke groet, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- From bf3 at telenet.be Tue Aug 21 14:40:05 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Tue Aug 21 14:31:04 2007 Subject: [Haskell-cafe] Yet another stupid question about numeric conversion In-Reply-To: References: <00c901c7e405$08923f00$19b6bd00$@be> <00d501c7e413$d52c4bb0$7f84e310$@be> Message-ID: <00e401c7e422$b15d6f20$14184d60$@be> Yes indeed, I realized that. I oversimplified my question. I'm basically trying to model 4D CG/HLSL operations (pixel/vertex shaders) in Haskell. I tried realToFrac, but that did not work. Then I tried splitting the instances into Fractional and Integral, but I kept getting errors. Maybe because I also made the Vector datatype an instance of Num, Fractional, etc, which was needed to model the CG/HLSL piecewise operations (so multiplication of two vectors is done piecewise by default in the CG model; one has special dot, cross, and mul operations for performing the other operations). Anyway, although I got something working when I enabled many GHC extensions, I dropped it for now. I notice that a lot of Haskell code uses type annotations (e.g. in HOpenGL), so I guess that's the price one has to pay. It would be nice if one could have a full predicate in the constraints section of a type class, like class ((Num a) && not (Vector4D a)) => ... But I guess this indicates bad design? Thanks, Peter lennart.augustsson@gmail.com wrote: How can you hope to convert an arbitrary Num to a Float? Num contains things like complex numbers that don't have any reasonable translation to a Float. But anyway, realToFrac is a good conversion function. From ndmitchell at gmail.com Tue Aug 21 15:23:26 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Tue Aug 21 15:14:43 2007 Subject: [Haskell-cafe] Re: Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> <20070820191526.GD3098@localhost.localdomain> Message-ID: <404396ef0708211223y4bcf7984u6650762b1f06731b@mail.gmail.com> Hi > > sum (enum 1 10) => > > sum' 0 (enum 1 10) => > > ... > > > > sum' 36 (9 : enum (9+1) 10) => > > (sum' $! (36+9)) (enum (9+1) 10) => > > sum' 45 (enum (9+1) 10) => > > sum' 45 [] => > > 45 > > > > (I need to find some way to automate making these trails :) ) > > Yes! We'd need such an automatic tool for the wikibook, too. The problem is that Haskell is ridiculously complex, and the "small step" interpretation is much harder than you'd think. For example, sum may well be defined as foldl' (+) 0, which is a CAF, so gets reduced once. The 0 won't actually be a 0, but will be fromInteger 0, which will correspond to looking up an item in the dictionary and applying it. Dictionaries especially make the "simple" interpretation completely wrong. It's easy to do informally, but once you start being more precise, its very complex. Thanks Neil From andrewcoppin at btinternet.com Tue Aug 21 15:37:19 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Tue Aug 21 15:27:41 2007 Subject: [Haskell-cafe] Re: Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <404396ef0708211223y4bcf7984u6650762b1f06731b@mail.gmail.com> References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> <20070820191526.GD3098@localhost.localdomain> <404396ef0708211223y4bcf7984u6650762b1f06731b@mail.gmail.com> Message-ID: <46CB3EEF.8040907@btinternet.com> Neil Mitchell wrote: > Hi > > >>> (I need to find some way to automate making these trails :) ) >>> >> Yes! We'd need such an automatic tool for the wikibook, too. >> > > The problem is that Haskell is ridiculously complex, and the "small > step" interpretation is much harder than you'd think. For example, sum > may well be defined as foldl' (+) 0, which is a CAF, so gets reduced > once. The 0 won't actually be a 0, but will be fromInteger 0, which > will correspond to looking up an item in the dictionary and applying > it. Dictionaries especially make the "simple" interpretation > completely wrong. > > It's easy to do informally, but once you start being more precise, its > very complex. > Like I said, I made a tool in Tcl that works. If you program in partially-parsed Haskell by hand first for all the functions it calls. (Except a few basic math ops.) Indeed, it was by playing with this tool that I first discovered why foldl' needs to exist! ;-) So, making a tool that you can set up to quickly generate an automated trace is quite easy. If you want a tool where you can just casually toss arbitrary Haskell at it and expect sensible answers... hmm... that's going to be kinda tricky. (!) (I had a go at it myself, several times. Each time I was tripped over by being unable to correctly parse arbitrary Haskell code. I never even got to writing the execution engine...!) I think a lot of people will agree that if such a tool existed it could be a *tremendous* help in many, many ways - a tool for experimenting and teaching, finding out why your really-complicated-function behaves wrong, checking out strictness properties, etc. But somebody has to write it first. It's ironic really; Haskell *looks* so easy to single-step. ;-) From trebla at vex.net Tue Aug 21 16:32:41 2007 From: trebla at vex.net (Albert Y. C. Lai) Date: Tue Aug 21 16:23:57 2007 Subject: [Haskell-cafe] Re: Bi-directional Maps In-Reply-To: References: <14cf844b0708201146w715809afs26f20b37ba09b852@mail.gmail.com> <837db430708210608m442fcb9s7dc0bfca05cd8b40@mail.gmail.com> Message-ID: <46CB4BE9.50302@vex.net> apfelmus wrote: > Hugh Perkins wrote: >> Arguably there are two possible implementations, one that enforces >> one-to-one mapping, and one which allows multiple values, in either >> direction. > > Terminology reminder :) > - the latter is called "(binary) relation" > http://en.wikipedia.org/wiki/Binary_relation > - the former would be a "bijection" > http://en.wikipedia.org/wiki/Bijective_map Following a great tradition, "That's just semantics." From midfield at gmail.com Tue Aug 21 16:34:07 2007 From: midfield at gmail.com (Ben) Date: Tue Aug 21 16:25:23 2007 Subject: [Haskell-cafe] STM, IO and b-trees In-Reply-To: <784a62100708202321l33e309c9w711b9a9ac254a0ad@mail.gmail.com> References: <9157df230708201852h45325fd3s98550d40e8611db2@mail.gmail.com> <784a62100708201910o3184dfceh958cf110cedf82db@mail.gmail.com> <9157df230708202241o7c134c7fgab1fe81dfd486aa8@mail.gmail.com> <784a62100708202321l33e309c9w711b9a9ac254a0ad@mail.gmail.com> Message-ID: <9157df230708211334lc1de4e7g6e6f4c2781f65a28@mail.gmail.com> thanks for the detailed response! On 8/20/07, Thomas Conway wrote: > something like > > type PagePtr t = TVar (Address, Maybe t) > > data Node = Node (PagePtr Node) [(Key,PagePtr Node)] | Leaf [(Key,Data)] so you're storing the data in the pages? > Yes, except you might want to be clever about flushing dirty pages more lazily. > > My implementation isn't crash-proof (i.e. doesn't support crash > recovery - the environment in which my code operated means that if > something bad happens, I can rebuild from external data). unfortunately i need crash recovery (though i can sacrifice durability.) i can't see how to do this with the IO / STM divide except by using a transaction log and eager updates. but if i'm going to do that anyways, i am thinking maybe i should go back to the original plan, which was to use a simple, immutable on-disk structure (flat file plus index) with a transaction log + cache and occasional merging. > > probably use the trick where the STM transaction returns > > an IO action which you then perform. probably use ordinary page-level > > locks to deal with concurrency on IO -- STM doesn't help. > > Maybe. See the SPJ video on STM. His basic point is that STM helps get > rid of the stupid concurrency bugs, leaving just the "more > interesting" ones for you to deal with. :-) i'm not sure i understand what you're saying here. i don't see how to synchronize IO actions with STM -- there's a wall between them. in the IO monad i only seem to be able to use MVars and the like. > Yes, I've chatted with Andrew Bromage about the need for > > Data.Map.Concurrent > Data.Set.Concurrent > etc. > > I have a concurrent hash table which works very nicely. Think > > class Hashable t where > hash :: t -> Word64 > > type HashTable k v = TArray Word64 [(k,v)] ah, this works nicely, probably the simplest thing to implement. but how do you do in-order traversals? > Yes. There's a tech report version which includes details of deletion > which IIRC the one you mention does not. citeseer... google.... do you mean "relaxed balancing made simple" by ottman and soisalon-soininen? thanks again for all the advice! take care, Ben From trebla at vex.net Tue Aug 21 16:43:14 2007 From: trebla at vex.net (Albert Y. C. Lai) Date: Tue Aug 21 16:34:29 2007 Subject: [Haskell-cafe] #haskell irc channel reaches 400 users In-Reply-To: <46CB20F1.2080104@btinternet.com> References: <20070821003329.GA13546@cse.unsw.EDU.AU> <46CB20F1.2080104@btinternet.com> Message-ID: <46CB4E62.8040804@vex.net> Andrew Coppin wrote: > ...does this mean Haskell is officially harder to understand than Lisp, > Java, Perl and O'Caml? :-} > > (OTOH, does this mean Haskell is easier to understand than PHP or C++?) Or, Haskell is the easiest to understand of them all. Reason: Extremely large channel means so hard to understand that many people want help. Extremely small channel means so hard to understand that few people show interest. The middle-sized channel sits at the sweet spot. From isaacdupree at charter.net Tue Aug 21 16:43:07 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Tue Aug 21 16:35:59 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> Message-ID: <46CB4E5B.1080201@charter.net> Simon Peyton-Jones wrote: > | > GHC does some constant folding, but little by way of strength > | reduction, or using shifts instead of multiplication. It's pretty easy > | to add more: it's all done in a single module. Look at primOpRules in > | the module PrelRules. > | > > | > Patches welcome! But please also supply test-suite tests that check > | the correctness of the rules. > | > > | > | So... you mean it's source-level transformation rules? (Rather than > | wired into the compiler itself somewhere.) > > No, constant folding is part of the compiler, I'm afraid, in the module PrelRules. > > Simon _Constant_ folding is, but in GHC.Base there are rules like (unboxed) multiplying by zero or one, or adding or subtracting zero, from an unknown other (non-constant) value. I think shifts might be doable via RULES... if you were willing to make one rule for each denominator 2, 4, 8 and so on, which rather depends on max. Int... (and that's not Integers either, I guess) Isaac From levi.stephen at optusnet.com.au Tue Aug 21 20:02:26 2007 From: levi.stephen at optusnet.com.au (Levi Stephen) Date: Tue Aug 21 19:53:54 2007 Subject: [Haskell-cafe] Re: I'm stuck in my thought experiment In-Reply-To: <46CAE924.2040001@synopsys.com> References: <46C4E9D5.5090503@optusnet.com.au> <46C59FDC.8060507@synopsys.com> <46CA2F0F.3010109@optusnet.com.au> <46CAE924.2040001@synopsys.com> Message-ID: <46CB7D12.4090300@optusnet.com.au> >>> If I wanted to develop the widgets themselves separately from the >>> layout, I would probably do something like this: >>> >>> class Widget a where >>> render :: a -> Html >>> bbox :: a -> Size >>> >>> type Layout = forall a. Widget a => Widget a >>> | Rows Spacing [Layout] >>> | Columns Spacing [Layout] >>> | Grid Spacing [[Layout]] >>> >>> type Page = Page String Layout >>> >>> renderLayout :: Layout -> Html >>> >>> renderPage :: Page -> Html >> >> I'm unsure this gives what I'm after. I'm trying to have layouts >> consist of Widgets (e.g., header images, common menu), and as pages >> also consist of Widgets it seems like they can be modelled using a >> common type/construct. > > Well if you want to abstract over the layout too, you can just add > > instance Widget Layout where > render = renderLayout > bbox = ... > > But just because you can, doesn't mean you should. I don't know the full > details of your design, but what do you gain by allowing the layout to > intermingle with the widgets? Is worth the extra complexity? > > If you treat layout as "just another widget" then it becomes harder to > answer specific questions about the page layout because you have less > information in your tree. > Layout might not actually be the right term. Page template might be better. What I'm trying to gain is best described with an example. * I have a template with a header image, and footer text. * I create another template defined as the previous, but with a menu bar down the left. * I create a page based on the previous with some text. The gain comes from when I want to change the header image, or add a Login/Register box on all pages, I only edit the first template. Levi From dot at dotat.at Tue Aug 21 20:25:50 2007 From: dot at dotat.at (Tony Finch) Date: Tue Aug 21 20:17:06 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: References: Message-ID: On Sun, 19 Aug 2007, Peter Cai wrote: > > My duty is writing a network server which talks to another server through a > binary based private protocol. Haskell needs something like Erlang's bit syntax. http://erlang.org/doc/reference_manual/expressions.html#6.16 http://erlang.org/doc/programming_examples/bit_syntax.html#4 The IP header example in the latter is a brilliant real-world example. It has recently been upgraded to support arbitrary bit streams. See http://www.it.uu.se/research/group/hipe/papers/padl07.pdf Tony. -- f.a.n.finch http://dotat.at/ IRISH SEA: SOUTHERLY, BACKING NORTHEASTERLY FOR A TIME, 3 OR 4. SLIGHT OR MODERATE. SHOWERS. MODERATE OR GOOD, OCCASIONALLY POOR. From haskell at list.mightyreason.com Tue Aug 21 20:39:26 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Tue Aug 21 20:30:54 2007 Subject: [Haskell-cafe] Re: STM, IO and b-trees In-Reply-To: <784a62100708201910o3184dfceh958cf110cedf82db@mail.gmail.com> References: <9157df230708201852h45325fd3s98550d40e8611db2@mail.gmail.com> <784a62100708201910o3184dfceh958cf110cedf82db@mail.gmail.com> Message-ID: <46CB85BE.7090901@list.mightyreason.com> Thomas Conway wrote: > 2. Separate the IO from the BTree-stuff. > > Conceptually keep a TVar (Map Address ByteString). In the > transaction, use this to find pages. If the page is not there, throw > an exception containing the desired address. In a wrapper, catch the > exception, read the page, add it to the map as a separate transaction > then retry the original transaction. I say "conceptually" because > something like TArray Address (Maybe ByteString), or > similar will yield much better concurrency. In general, you want to > push the TVars down as far as possible. > This type of idea has been discussed before, see [1]. This lead to the AdvSTM monad at [2]. The "Helper Thread Code" on that page provides > newtype AdvSTM a = AdvSTM (ReaderT Env STM a) deriving (Functor,Monad,MonadPlus,Typeable) > type Env = (CommitVar,RetryVar) > type CommitVar = TVar (IO ()->IO ()) > type RetryVar = MVar (IO ()->IO ()) and MonadAdvancedSTM which gives onCommit and onRetry. > class MonadAdvSTM m where > onCommit :: IO a -> m () > onRetry :: IO a -> m () Any IO action passed to onCommit is scheduled to run if and and only if the current atomic attempt succeeds. This is the easy part and if that is all you need then the "Just onCommit" section on [2] is much simpler. Thus (orElseAdv fails works >> alsoWorks) will run all onCommit actions posted by works and alsoWorks but will not run any onCommit actions posted by the 'fails' piece (because when fails retries it will be rolled back and the change to the TVar will not be seen). The onRetry is sneakier and uses unsafeIOToSTM to put the scheduled action into a private MVar. The runAdvSTM uses a final orElse to detect when the whole action will retry and again uses unsafeIOToSTM to send the scheduled onRetry actions to the (perhaps newly spawned) helper thread before the retry. Thus (orElseAdv fails works >> alsoFails) will run all onRetry action posted by any of the three pieces fails, works, and alsoFails. The private MVar cannot be replaced with a private TVar since the 'fails' piece gets rolled back before running 'works'. Exception handling needs to be improved (e.g. bracket or finally in the retry helper thread and the ensure writeChan chan Nothing gets called if needed, etc.). > 3. Have Fun > > STM is very cool, so make sure you enjoy making it all hang together. :-) [1] http://www.haskell.org/pipermail/haskell-cafe/2006-November/019771.html [2] http://haskell.org/haskellwiki/New_monads/MonadAdvSTM From dons at cse.unsw.edu.au Tue Aug 21 20:49:28 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Tue Aug 21 20:40:47 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: References: Message-ID: <20070822004928.GB10901@cse.unsw.EDU.AU> dot: > On Sun, 19 Aug 2007, Peter Cai wrote: > > > > My duty is writing a network server which talks to another server through a > > binary based private protocol. > > Haskell needs something like Erlang's bit syntax. > > http://erlang.org/doc/reference_manual/expressions.html#6.16 > http://erlang.org/doc/programming_examples/bit_syntax.html#4 > The IP header example in the latter is a brilliant real-world example. > > It has recently been upgraded to support arbitrary bit streams. > See http://www.it.uu.se/research/group/hipe/papers/padl07.pdf > Yes, we've looked at this in the context of Data.Binary. Rather than extending the core syntax, on option is to use Template Haskell, http://hackage.haskell.org/cgi-bin/hackage-scripts/package/BitSyntax-0.3 Another is to just use monad and pattern guards, which give quite reasonable syntax. -- Don From twanvl at gmail.com Tue Aug 21 22:13:46 2007 From: twanvl at gmail.com (Twan van Laarhoven) Date: Tue Aug 21 22:04:48 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46CB4E5B.1080201@charter.net> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> Message-ID: <46CB9BDA.4090408@gmail.com> Isaac Dupree wrote: > Simon Peyton-Jones wrote: > >> ... >> No, constant folding is part of the compiler, I'm afraid, in the >> module PrelRules. >> >> Simon > > > _Constant_ folding is, but in GHC.Base there are rules like (unboxed) > multiplying by zero or one, or adding or subtracting zero, from an > unknown other (non-constant) value. I think shifts might be doable via > RULES... if you were willing to make one rule for each denominator 2, 4, > 8 and so on, which rather depends on max. Int... (and that's not > Integers either, I guess) Just to see what this would look like. First of all, optimizing mod and div can not be done with PrelRules, because they are not primitives, quot and rem are. And most of the nice optimizations with shifts no longer work there. But using rules should work, assuming the inliner is not too fast. Multiplication and division can become shifts: > {-# RULES > > -- x * 2^n --> x `shiftL` n > "x# *# 2#" forall x#. x# *# 2# = x# `iShiftL#` 1# > "2# *# x#" forall x#. 2# *# x# = x# `iShiftL#` 1# > -- etc. > > -- x `div` 2^n --> x `shiftR` n > "x# `divInt#` 2#" forall x#. divInt# x# 2# = x# `iShiftRA#` 1# > "x# `divInt#` 4#" forall x#. divInt# x# 4# = x# `iShiftRA#` 2# > -- etc. Mod can become and: > -- x `mod` 2^n --> x .&. (2^n - 1) > "x# `modInt#` 2#" forall x#. modInt# x# 2# = andInt# x# 1# > "x# `modInt#` 4#" forall x#. modInt# x# 4# = andInt# x# 3# > -- etc. > > #-} Here I use a new function (see instance Bits Int), > andInt# :: Int# -> Int# -> Int# > andInt# x# y# = word2Int# (int2Word# x# `and#` int2Word# y#) but you could write that inline as well. A problem with these rules is that you need a whole lot of them. 32 per operation (on a 32 bit platform), * 4 operations, * 2 separate versions for words and ints = 256. Other rules that could be interesting are: > forall a b. fromInteger a + fromInteger b = fromInteger (a + b) > forall a b. fromInteger a * fromInteger b = fromInteger (a * b) > -- etc. To allow optimizations on generic Num code, although I am not sure what the Haskell spec has to say about this. Now, if you want to get really creative you can use other semi-evil optimization tricks for quot and rem. The following is based on code generated by Visual C++: > -- remPowInt x y == x `rem` (2^y) > remPowInt x y > | r >= 0 = r > | otherwise = ((r - 1) .|. (complement yWithSign)) + 1 > where r = x .&. yWithSign > yWithSign = (1 `shiftL` (bitSize - 1)) .|. > ((1 `shiftL` y) - 1) Or in assembly (for y == 2, so x `rem` 4) > and ecx,80000007h > jns main+60h (401060h) > dec ecx > or ecx,0FFFFFFF8h > inc ecx The C++ compiler also performs other optimizations when multiplying with other constants, for example *3 becomes something like > lea eax, [eax+eax*2] Divisions become horrendous constructs with magic numbers, > -- eax := ecx / 5 > mov eax,66666667h > imul ecx > sar edx,1 > mov eax,edx > shr eax,1Fh > add eax,edx But such things are probably best left to the code generator / a peephole optimizer, if they are done at all. I think the LEA trick should be feasible. Twan From allbery at ece.cmu.edu Tue Aug 21 22:16:20 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Tue Aug 21 22:07:37 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46CB9BDA.4090408@gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> Message-ID: <2333893E-F2CF-43A0-A073-A4B2665C2A65@ece.cmu.edu> On Aug 21, 2007, at 22:13 , Twan van Laarhoven wrote: > Other rules that could be interesting are: > > forall a b. fromInteger a + fromInteger b = fromInteger (a + b) I don't think this will work, a and b have to be the same type. -- 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 twanvl at gmail.com Tue Aug 21 22:21:26 2007 From: twanvl at gmail.com (Twan van Laarhoven) Date: Tue Aug 21 22:12:29 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <2333893E-F2CF-43A0-A073-A4B2665C2A65@ece.cmu.edu> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <2333893E-F2CF-43A0-A073-A4B2665C2A65@ece.cmu.edu> Message-ID: <46CB9DA6.4090809@gmail.com> Brandon S. Allbery KF8NH wrote: > > On Aug 21, 2007, at 22:13 , Twan van Laarhoven wrote: > >> Other rules that could be interesting are: >> > forall a b. fromInteger a + fromInteger b = fromInteger (a + b) > > > I don't think this will work, a and b have to be the same type. They are of the same type, both are Integers, > forall a b :: Integer. > ((fromInteger (a::Integer)) + (fromInteger b)) :: Num n => n > = > (fromInteger (a + b :: Integer)) :: Num n => n Twan From hughperkins at gmail.com Tue Aug 21 23:07:22 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 21 22:58:44 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <46CB21C7.4070708@btinternet.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> <46CB21C7.4070708@btinternet.com> Message-ID: <837db430708212007v60cf2b64m53a8a0b98e047168@mail.gmail.com> On 8/21/07, Andrew Coppin wrote: > I highly doubt that automatic threading will happen any time this decade > - but I just learned something worth while from reading this email. ;-) > That's an interesting observation. I cant say I dont believe it, but I'm interested to know why (but it could be just a feeling, or an observation in time-to-market lead times?). Are you saying this because multicores arent sufficiently widespread or powerful enough yet (4-cores doesnt really even make up for the overhead of using automatic threading, at least in initial implementations)? or are you saying this because you think the technical implementations are not sufficiently advanced? I kindof think automatic threading is like 3d graphics: as soon as the hardware became sufficiently powerful, 3d graphics became trivial. Enough money was thrown at the problem in a very short time by a few powerful companies that it was a non-issue. Nevertheless, if I could get a paper out of it before the big companies notice, that could be fun :-D From hughperkins at gmail.com Tue Aug 21 23:19:00 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 21 23:10:25 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070821133911.GA7715@localhost.localdomain> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46C9CFB3.9050007@btinternet.com> <20070820192248.GE3098@localhost.localdomain> <837db430708210639kf4e5231xed8a265fb0f4614a@mail.gmail.com> <20070821133911.GA7715@localhost.localdomain> Message-ID: <837db430708212018k7a592100s1bb51466ffe46291@mail.gmail.com> Thank-you for the information. It was very useful. Couple of reactions FWIW: On 8/21/07, Stefan O'Rear wrote: > > Sooo.... if I was feeling "evil", could I take this c-code and pipe it > > into something that turns it into C#??? > > Yes. You could do the same with the original haskell. It's called a > compiler. Yes, that is true. However, this is also true, for an appropriate compiler, for programs such as: "Give me the first 10 numbers of the Fibonnacci (spelling?) series". The compiler can search on the internet for what is the Fibonnacci series, and/or ask its friends. In a subsequent version, a compiler could in fact compile programs such as: "Go!" ... where the compiler uses context to deduce what I want it to do ;-) Nevertheless certain compilers are easier to write than others, and writing code to automatically port ghc-generated C code is likely to be significantly easier than to compile Haskell to C#, or to .Net bytecode, from scratch. > > Name: Native code generator > Performance: 0.97 > Flags: -fasm > > GHC's own mini C compiler converts the internal C-- data into assembly > code, which is then piped to gas. Ah, hence SPJ's C-- project? > > Name: Unregisterized C > Performance: 0.40 > Flags: -unreg > > Generates near-ANSI C, using memory variables for the VM's registers and > the returning function pointer hack seen in oh so many Scheme compilers. > Good for early stages of porting, and not much else. Could be good enough. C# compiler and VM provides some optimizations which could handle this. What is the function pointer hack? Specifically, is that why you say "near-ANSI" C, rather than "ANSI C"? > > > If it contains lots of macros (or any macros at all perhaps...), this > > becomes non-trivial, > > I fail to see how macros have anything to do with this. Especially > since cpp removes them all. > > > but otherwise I think most things in C can be mapped fairly trivially > > to C#? > > Unsafe C#, sure. Haskell's type system is strictly more expressive than > C#, and you need to sacrifice either machine efficiency or checked > safety. > > > (It's a one-way mapping of course, eg "delete" in C is simply dropped > > when mapped to c#). > > There is no delete in C, and even if there was, GHC wouldn't use it. > Allocation is *the* major bottleneck of functional programs, and having > a custom allocator inlined into every call site is vital to have usable > performance. > > > (Not that I have any good reason to do this, simply... fun). > > Stefan > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > > iD8DBQFGyur/FBz7OZ2P+dIRAleTAJ9WiK8tCp0QZE4syG4BZk5EFm1FuQCgzYGK > NUv22zY5IgeqkEJ5kL3yriQ= > =0Xkq > -----END PGP SIGNATURE----- > > From hughperkins at gmail.com Tue Aug 21 23:20:07 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 21 23:11:36 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <837db430708212018k7a592100s1bb51466ffe46291@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46C9CFB3.9050007@btinternet.com> <20070820192248.GE3098@localhost.localdomain> <837db430708210639kf4e5231xed8a265fb0f4614a@mail.gmail.com> <20070821133911.GA7715@localhost.localdomain> <837db430708212018k7a592100s1bb51466ffe46291@mail.gmail.com> Message-ID: <837db430708212020o57ebbb50y5215c9362ca66f39@mail.gmail.com> Arggh, lagged out, and accidentally hit send before deleting the quoted text. Sorry :-(((( From hughperkins at gmail.com Tue Aug 21 23:27:34 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Tue Aug 21 23:18:48 2007 Subject: [Haskell-cafe] Re: Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <46BC26E3.1030902@cs.caltech.edu> <837db430708100158m3f2f42e3k91712350933e7e5c@mail.gmail.com> Message-ID: <837db430708212027p56348f57x5feadecdf716ccd7@mail.gmail.com> On 8/11/07, Benjamin Franksen wrote: > A certain amount > of dynamism wrt the message content (high level protocol) is necessary for > systems for which Erlang was designed, namely large distributed control > systems with minimum down-times. For large distributed installations it is > a matter of practicality to be able to upgrade one component w/o needing to > recompile (and then re-start) all the other components that it communicates > with -- for systems with expected down-times of 3 Minutes per year it is a > matter of being able to meet the specifications. You'll have a hard time > finding high-availability or large control systems which use an IDL > approach for communication. Hmmm, that's interesting. I'd never considered lack of typing to be a good thing for system robustness before! Question: to what extent does interface versioning get around this problem? I assume the issue we're trying to address is to be able to upgrade clients/servers/peers independently, without losing connectivity with unupgraded systems? So, using versioned interfaces: Initially we have: client1 marketinterface1 server marketinterface1 client2 marketinterface1 Then, we upgrade the server with a new interface, marketinterface2. Significantly, we keep the old interface. So now we have: client1 marketinterface1 server marketinterface1, marketinterface2 client2 marketinterface1 The whole system continues to work: client1 and client2 continue to chat with server on marketinterface1. Now we upgrade client1: client1 marketinterface2 server marketinterface1, marketinterface2 client2 marketinterface1 ... and client2: client1 marketinterface2 server marketinterface1, marketinterface2 client2 marketinterface2 Finally, we deprecate/remove marketinterface1 from the server: client1 marketinterface2 server marketinterface2 client2 marketinterface2 From bos at serpentine.com Tue Aug 21 23:28:26 2007 From: bos at serpentine.com (Bryan O'Sullivan) Date: Tue Aug 21 23:23:50 2007 Subject: [Haskell-cafe] [ANN] An efficient lazy suffix tree library Message-ID: <46CBAD5A.8020408@serpentine.com> I just posted a library named suffixtree to Hackage. http://www.serpentine.com/software/suffixtree/ It implements Giegerich and Kurtz's lazy construction algorithm, with a few tweaks for better performance and resource usage. API docs: http://darcs.serpentine.com/suffixtree/dist/doc/html/Data-SuffixTree.html I've tested it on multi-megabyte input strings. References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <46BC26E3.1030902@cs.caltech.edu> <837db430708100158m3f2f42e3k91712350933e7e5c@mail.gmail.com> <837db430708212027p56348f57x5feadecdf716ccd7@mail.gmail.com> Message-ID: On Aug 21, 2007, at 23:27 , Hugh Perkins wrote: > Hmmm, that's interesting. I'd never considered lack of typing to be a > good thing for system robustness before! The old watchphrase (before Netscape and Microsoft abused it beyond anyone's expectation) for Internet protocols was "be liberal in what you accept and conservative in what you send"; same idea. -- 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 allbery at ece.cmu.edu Tue Aug 21 23:35:25 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Tue Aug 21 23:27:50 2007 Subject: [Haskell-cafe] Re: Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708212027p56348f57x5feadecdf716ccd7@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <46BC26E3.1030902@cs.caltech.edu> <837db430708100158m3f2f42e3k91712350933e7e5c@mail.gmail.com> <837db430708212027p56348f57x5feadecdf716ccd7@mail.gmail.com> Message-ID: On Aug 21, 2007, at 23:27 , Hugh Perkins wrote: > Hmmm, that's interesting. I'd never considered lack of typing to be a > good thing for system robustness before! The old watchphrase (before Netscape and Microsoft abused it beyond anyone's expectation) for Internet protocols was "be liberal in what you accept and conservative in what you send"; same idea. -- 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 lutz at iks-jena.de Wed Aug 22 03:30:05 2007 From: lutz at iks-jena.de (Lutz Donnerhacke) Date: Wed Aug 22 03:21:25 2007 Subject: [Haskell-cafe] Parsing binary data. References: Message-ID: * Tony Finch wrote: > http://erlang.org/doc/programming_examples/bit_syntax.html#4 > The IP header example in the latter is a brilliant real-world example. Unfortunly this example does not handle bit and byte order. Take a look at Ada's representation clauses for such topics. From simonpj at microsoft.com Wed Aug 22 04:04:11 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Wed Aug 22 03:55:16 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46CB9BDA.4090408@gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> Message-ID: | First of all, optimizing mod and div can not be done with PrelRules, | because they are not primitives, quot and rem are. Yes, you can do them with PrelRules! Check out PrelRules.builtinRules. | Multiplication and division can become shifts: | | > {-# RULES | > | > -- x * 2^n --> x `shiftL` n | > "x# *# 2#" forall x#. x# *# 2# = x# `iShiftL#` 1# | > "2# *# x#" forall x#. 2# *# x# = x# `iShiftL#` 1# | > -- etc. | A problem with these rules is that you need a whole lot of them. 32 per | operation (on a 32 bit platform), * 4 operations, * 2 separate versions | for words and ints = 256. I think you should be able to a lot better. For example, to do constant folding for +# you might think you needed a lot of rules 1# +# 2# = 3# 1# +# 3# = 4# etc But not so! See PrelRules for how to write one rule that does all of these at once. I think you can do multiply-to-shift in the same way. The downside of PrelRules is that it's part of the compiler, not in Haskell pragmas; that's what makes it more expressive than rules written in source code. Does that help? If one of the folk listening to this thread wanted to add a page to the GHC Commentary distilling this thread into Wiki material, I'd be happy to check its accuracy. http://hackage.haskell.org/trac/ghc/wiki/Commentary Simon From njbartlett at gmail.com Wed Aug 22 04:19:26 2007 From: njbartlett at gmail.com (Neil Bartlett) Date: Wed Aug 22 04:10:45 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708210602n26d94186q7581465af529ed14@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> <837db430708210602n26d94186q7581465af529ed14@mail.gmail.com> Message-ID: > multicore box ;-) It's my main show-stopper right now. Any clues on > how to get access to one, eg via ssh? 32-core or higher would be > favorite ;-) but I guess even just a 4-core or so is enough for > proof-of-concept? I think you'll have plenty of work to be before you get to the stage of needing a box with more than 4 cores. Even a dual core machine is likely to be enough for initial experimentation, I would say. > ... or build a minimal vm, enough to get 3 or 4 somewhat interesting > algorithms / programs to run, and get automatic threading working on a > couple of targets, eg on maps, and whatever [ x | x <- somelist ] > these things are called. (folds are a little harder from an > implementation point of view, so can be a future upgrade). The other thing to consider is that there are several other VMs out there, including many under open source licenses, that can be used as a testbed. Examples include the Java VM, Mono, Parrot, LLVM, etc. > Would you or Neil fancy being a mentor for this, if I can start to get > somewhere on it? Not me! I'm not an academic... I've never had a paper published and I'm not likely to either. Regards Neil From ndmitchell at gmail.com Wed Aug 22 04:43:32 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Wed Aug 22 05:02:17 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46CB9BDA.4090408@gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> Message-ID: <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> Hi > Other rules that could be interesting are: > > forall a b. fromInteger a + fromInteger b = fromInteger (a + b) > > forall a b. fromInteger a * fromInteger b = fromInteger (a * b) This is wrong, since the class function can do what it wants. Imagine: instance Num String where (+) = (++) fromInteger x = show x 1 + 2 :: String this expression now goes from "12" to "3" by applying this rule. You need to be incredibly careful if there are any classes floating around. Thanks Neil From lemming at henning-thielemann.de Wed Aug 22 05:10:32 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Wed Aug 22 05:02:49 2007 Subject: [Haskell-cafe] Yet another stupid question about numeric conversion In-Reply-To: <00e401c7e422$b15d6f20$14184d60$@be> References: <00c901c7e405$08923f00$19b6bd00$@be> <00d501c7e413$d52c4bb0$7f84e310$@be> <00e401c7e422$b15d6f20$14184d60$@be> Message-ID: On Tue, 21 Aug 2007, Peter Verswyvelen wrote: > Yes indeed, I realized that. I oversimplified my question. I'm basically > trying to model 4D CG/HLSL operations (pixel/vertex shaders) in Haskell. > > I tried realToFrac, but that did not work. Then I tried splitting the > instances into Fractional and Integral, but I kept getting errors. Maybe > because I also made the Vector datatype an instance of Num, Fractional, etc, > which was needed to model the CG/HLSL piecewise operations (so > multiplication of two vectors is done piecewise by default in the CG model; > one has special dot, cross, and mul operations for performing the other > operations). > It would be nice if one could have a full predicate in the constraints > section of a type class, like > > class ((Num a) && not (Vector4D a)) => ... > > But I guess this indicates bad design? Is still don't see why you need it. I have the feeling that you abuse Num and Fractional classes just for re-use of symbols like (*) and (/) in an arbitrary way. Better don't do that. Type classes are for writing generic functions. Define new infix operators where necessary. From luc.taesch at gmail.com Wed Aug 22 06:25:19 2007 From: luc.taesch at gmail.com (luc.taesch) Date: Wed Aug 22 06:16:31 2007 Subject: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) In-Reply-To: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> Message-ID: <12271924.post@talk.nabble.com> Hugh Perkins wrote: > > > > Threading is going to become a > major issue soon, maybe not tomorrow, but there is a GPL'd Niagara 2 out > with 64 threads (I think?), so the time is now... > > I didn t know what was niagara 2, and by researching , I also found about tilera, a 64 CORE issued that August , for $435. affordable... short : http://hardware.slashdot.org/article.pl?sid=07/08/20/1830221 longuer : http://www.marketwire.com/mw/release.do?id=761947 -- View this message in context: http://www.nabble.com/Haskell-vs-GC%27d-imperative-languages%2C-threading%2C-parallelizeability-%28is-that-a-word--%3A-D-%29-tf4247108.html#a12271924 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From bf3 at telenet.be Wed Aug 22 08:20:32 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Wed Aug 22 08:11:52 2007 Subject: [Haskell-cafe] Yet another stupid question about numeric conversion In-Reply-To: References: <00c901c7e405$08923f00$19b6bd00$@be> <00d501c7e413$d52c4bb0$7f84e310$@be> <00e401c7e422$b15d6f20$14184d60$@be> Message-ID: <015e01c7e4b6$d61faf50$825f0df0$@be> > Is still don't see why you need it. I have the feeling that you abuse Num > and Fractional classes just for re-use of symbols like (*) and (/) in an Maybe. It is true that I had the same feeling when first using the CG language: when v and u are (4D) vectors, then -u, u+v and u-v make perfect sense, but u*v, u/v, abs u, signum u, fromInteger u, sin u, etc, don't. In CG this is just solved by applying these operators componentwise. So when u=[u1 u2], then (abs u) = [(abs u1) (abs u2)]. Maybe not really correct in the mathematical sense, but it works fine in practice. It feels silly to invent new operators and names for all of these; the code looks weird, and every function in Num, Fractional, and Floating can be lifted fine into this componentwise scheme. I just "invented" extra operators (dot, cross, mul) to specify dot product, cross product, matrix/vector and matrix/matrix multiplication etc. These clearly do not fit in the numeric classes. Anyway, I started from scratch again, and all is working fine now. As a Haskell newbie, I face this a lot: it seems I'm really stuck with something, wanting to give up on Haskell, and then next day when I start my code from scratch, then it suddenly works fine in a much more elegant way. Maybe I should always do that before asking silly questions here ;) And I should checkin every version that does NOT work, so I can see what went wrong. Now I had them same when digesting C++ templates, so it's not really related to Haskell... Thanks, Peter PS: IMHO it's also a bit problematic the way the numeric classes in Haskell are defined. It would have been nicer if it followed mathematics a bit more, as it seems to be done in the upcoming Sun Fortress language. This is just a *feeling* I'm having by quickly reading the Fortress language specs, so I might be very very wrong :) No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.484 / Virus Database: 269.12.1/965 - Release Date: 21/08/2007 16:02 From lemming at henning-thielemann.de Wed Aug 22 08:34:45 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Wed Aug 22 08:26:03 2007 Subject: [Haskell-cafe] Yet another stupid question about numeric conversion In-Reply-To: <015e01c7e4b6$d61faf50$825f0df0$@be> References: <00c901c7e405$08923f00$19b6bd00$@be> <00d501c7e413$d52c4bb0$7f84e310$@be> <00e401c7e422$b15d6f20$14184d60$@be> <015e01c7e4b6$d61faf50$825f0df0$@be> Message-ID: On Wed, 22 Aug 2007, Peter Verswyvelen wrote: > PS: IMHO it's also a bit problematic the way the numeric classes in Haskell > are defined. I like to mention alternative type class hierarchies like NumericPrelude, again: http://www.haskell.org/haskellwiki/Mathematical_prelude_discussion http://www.haskell.org/haskellwiki/Applications_and_libraries/Mathematics#Type_class_hierarchies From gleb.alexeev at gmail.com Wed Aug 22 09:48:29 2007 From: gleb.alexeev at gmail.com (Gleb Alexeyev) Date: Wed Aug 22 09:39:50 2007 Subject: [Haskell-cafe] Impredicativity confusion Message-ID: Hello Cafe! Is there some reason why definition of 'boom' in the code below won't compile? Is it documented somewhere? Thanks. {-# OPTIONS_GHC -fglasgow-exts #-} data Foo a foo :: Foo a -> a -> Bool foo = undefined newtype A = A (forall a. a->a) ok = foo f (A id) where f = undefined :: Foo A type B = forall a. a->a boom = foo f (id :: B) where f = undefined :: Foo B From jeff.polakow at db.com Wed Aug 22 10:11:17 2007 From: jeff.polakow at db.com (Jeff Polakow) Date: Wed Aug 22 10:02:33 2007 Subject: [Haskell-cafe] Impredicativity confusion In-Reply-To: Message-ID: Hello, > {-# OPTIONS_GHC -fglasgow-exts #-} > > data Foo a > > foo :: Foo a -> a -> Bool > foo = undefined > > newtype A = A (forall a. a->a) > > ok = foo f (A id) > where f = undefined :: Foo A > > type B = forall a. a->a > > boom = foo f (id :: B) > where f = undefined :: Foo B > boom doesn't typecheck because foo's second argument is of type a which will cause GHC to treat it monomorphically (at least from the top-level of the type-- excuse my ignorance of the correct terminology for this). ok typechecks because the forall is hidden under the A. To better illustrate, the following will typecheck: foo :: Foo (forall a.a -> a) -> (forall a.a -> a) -> Bool foo = undefined type B = forall a.a -> a boom = foo f (id :: B) where f = undefined :: Foo B but this type for foo will prevent ok from typechecking. -Jeff --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/513642a1/attachment.htm From gleb.alexeev at gmail.com Wed Aug 22 10:26:25 2007 From: gleb.alexeev at gmail.com (Gleb Alexeyev) Date: Wed Aug 22 10:17:58 2007 Subject: [Haskell-cafe] Re: Impredicativity confusion In-Reply-To: References: Message-ID: Jeff Polakow wrote: > boom doesn't typecheck because foo's second argument is of type a which > will cause GHC to treat it monomorphically (at least from the top-level > of the type-- excuse my ignorance of the correct terminology for this). > ok typechecks because the forall is hidden under the A. > I'm sorry, I don't understand this. GHC manual [1] says that "you can call a polymorphic function at a polymorphic type, and parameterise data structures over polymorphic types". That's what I do in the code I posted. What make GHC to treat 'a' monomorphically when explicit type signature is given? [1]http://haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#impredicative-polymorphism > To better illustrate, the following will typecheck: > > foo :: Foo (forall a.a -> a) -> (forall a.a -> a) -> Bool > foo = undefined > > type B = forall a.a -> a > boom = foo f (id :: B) where f = undefined :: Foo B > > but this type for foo will prevent ok from typechecking. > > -Jeff > > > > --- From dimitriv at cis.upenn.edu Wed Aug 22 10:31:59 2007 From: dimitriv at cis.upenn.edu (Dimitrios Vytiniotis) Date: Wed Aug 22 10:23:15 2007 Subject: [Haskell-cafe] Impredicativity confusion In-Reply-To: References: Message-ID: <46CC48DF.80808@cis.upenn.edu> Hi, > > type B = forall a. a->a > > boom = foo f (id :: B) > where f = undefined :: Foo B Unfortunately the current implementation of impredicativity has similar problems, which can be summarized as: who gives information (and who should give if any) in application nodes about instantiations of variables; the arguments (and which one?) ? the result types? none? Now the source of the particular confusion is that although "Foo B" says that a should be instantiated with "B", the current way applications are checked does not know how to use this information because it is inside a "box". The point is that a "boxy" variable for "a" is filled in (correctly) with B, but then when we are checking: (id :: B) : this_boxy_variable we fail because it is not the case that: forall a. a -> a <= BOX{ forall a. a -> a} Now, there was a good reason for that, boxes represented inferred information that we have no idea *when* they are filled and by who. There are more useful cases for example where we really want: forall a. a -> a <= BOX{ tau -> tau } for any tau. and that is what GHC chooses, and that's what happens algorithmically. The whole story of impredicativity in GHC is unsatisfactory; for now you can circumvent your problem by simply providing yourself the correct instantiation of foo: boom = (foo :: Foo B -> B -> Bool) f (id :: B) So, until something is done to fix these issues (I am thinking about it and there exist several related reasearch proposals) a general rule for the current implementation is: give the instantiations yourself if it fails to check. I hope this helps more than confuses, -dimitris > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From brandon at heave.ugcs.caltech.edu Wed Aug 22 10:39:27 2007 From: brandon at heave.ugcs.caltech.edu (Brandon Michael Moore) Date: Wed Aug 22 10:30:40 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708212007v60cf2b64m53a8a0b98e047168@mail.gmail.com> References: <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> <46CB21C7.4070708@btinternet.com> <837db430708212007v60cf2b64m53a8a0b98e047168@mail.gmail.com> Message-ID: <20070822143927.GA4864@heave.ugcs.caltech.edu> On Wed, Aug 22, 2007 at 04:07:22AM +0100, Hugh Perkins wrote: > On 8/21/07, Andrew Coppin wrote: > > I highly doubt that automatic threading will happen any time this decade > > - but I just learned something worth while from reading this email. ;-) > > That's an interesting observation. I cant say I dont believe it, but > I'm interested to know why (but it could be just a feeling, or an > observation in time-to-market lead times?). Are you saying this > because multicores arent sufficiently widespread or powerful enough > yet (4-cores doesnt really even make up for the overhead of using > automatic threading, at least in initial implementations)? or are you > saying this because you think the technical implementations are not > sufficiently advanced? Automatic threading is inherently limited by data dependencies. You can't run a function that branches on an argument in parallel with the computation producing that argument. Even with arbitrarily many processors and no communication overhead there is a limit to how much parallelism you can squeeze from any given program. You should read "Feedback Directed Implicit Parallelism" http://research.microsoft.com/~tharris/papers/2007-fdip.pdf and perhaps "Limits to Implicit Parallelism in Functional Applications" http://www.detreville.org/papers/Limits.pdf In short, with zero overhead and an oracle for scheduling you can get a factor of at most 2x to 32x by implicitly parallelizing existing Haskell code. In practice, with execution overhead it's a gain of perhaps 10% to 80% on a 4-core system. The experiments in the first paper are based on a fairly sophisticated implementation that reduces overhead by using profiling results at compile time to decide which thunks might be worth evaluating in parallel. For a fixed benchmark there's probably not much lost by using canned profiling results instead of adapting at runtime, and in any case the hard bounds from data dependencies still apply. You can do a lot better if you expect people to rewrite code, but "automatic threading" suggests something completely effortless. I think you can get much better results if you work on the programming style in connection with a better runtime. You can think of data parallel Haskell as a new programming style with more implicit parallelims, and the runtime support to exploit it. > I kindof think automatic threading is like 3d graphics: as soon as the > hardware became sufficiently powerful, 3d graphics became trivial. > Enough money was thrown at the problem in a very short time by a few > powerful companies that it was a non-issue. If you have cores to waste, you might try rewrites like f x => case x of C1 a1 a2 -> f (C1 a1 a2) C2 b -> f (C2 b) C3 -> f C3 and then speculatively execute several of the case branches. If you don't throw away too much type information you should even be able to do it at runtime. Brandon From gleb.alexeev at gmail.com Wed Aug 22 10:47:38 2007 From: gleb.alexeev at gmail.com (Gleb Alexeyev) Date: Wed Aug 22 10:39:07 2007 Subject: [Haskell-cafe] Re: Impredicativity confusion In-Reply-To: <46CC48DF.80808@cis.upenn.edu> References: <46CC48DF.80808@cis.upenn.edu> Message-ID: Dimitrios Vytiniotis wrote: > I hope this helps more than confuses, It really does, thank you. To understand your explanation completely I have to study 'Boxy types' paper thoroughly, but from the user's point of view everything is clear - GHC currently cannot correctly instantiate type variables in polymorphic function's type when some of arguments have polymorphic types and only types of arguments are given. From stefanor at cox.net Wed Aug 22 10:58:42 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 22 10:49:55 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> Message-ID: <20070822145842.GA3363@localhost.localdomain> On Wed, Aug 22, 2007 at 09:04:11AM +0100, Simon Peyton-Jones wrote: > | First of all, optimizing mod and div can not be done with PrelRules, > | because they are not primitives, quot and rem are. > > Yes, you can do them with PrelRules! Check out PrelRules.builtinRules. > > | Multiplication and division can become shifts: > | > | > {-# RULES > | > > | > -- x * 2^n --> x `shiftL` n > | > "x# *# 2#" forall x#. x# *# 2# = x# `iShiftL#` 1# > | > "2# *# x#" forall x#. 2# *# x# = x# `iShiftL#` 1# > | > -- etc. > > > | A problem with these rules is that you need a whole lot of them. 32 per > | operation (on a 32 bit platform), * 4 operations, * 2 separate versions > | for words and ints = 256. > > I think you should be able to a lot better. For example, to do > constant folding for +# you might think you needed a lot of rules > > 1# +# 2# = 3# > 1# +# 3# = 4# > etc > > But not so! See PrelRules for how to write one rule that does all of > these at once. I think you can do multiply-to-shift in the same way. > > The downside of PrelRules is that it's part of the compiler, not in > Haskell pragmas; that's what makes it more expressive than rules > written in source code. Something I've pondered is adding a more-expressive form of RULES which works using general pattern matching: {-# XRULES "*#-to-shift" (*#) (CoreLit (CoreInt num)) obj | num .&. (num - 1) == 0 -> CoreApp (CoreVar "GHC.Prim.iShiftL#") [obj, CoreLit (CoreInt (lg2 num))] obj (CoreLit (CoreInt num)) | num .&. (num - 1) == 0 -> CoreApp (CoreVar "GHC.Prim.iShiftL#") [obj, CoreLit (CoreInt (lg2 num))] #-} This would require reusing the TH infrastructure, and (depending on how much we can abstract) might leak too many details of Core to be useful; on the other hand it would allow some very interesting domain optimizations to be done. Views might be nice here. Opinions on whether something like this is a good idea? Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/c13a6c0e/attachment.bin From dot at dotat.at Wed Aug 22 11:54:59 2007 From: dot at dotat.at (Tony Finch) Date: Wed Aug 22 11:46:12 2007 Subject: [Haskell-cafe] Parsing binary data. In-Reply-To: References: Message-ID: On Wed, 22 Aug 2007, Lutz Donnerhacke wrote: > * Tony Finch wrote: > > http://erlang.org/doc/programming_examples/bit_syntax.html#4 > > The IP header example in the latter is a brilliant real-world example. > > Unfortunly this example does not handle bit and byte order. > Take a look at Ada's representation clauses for such topics. Erlang has support for byte endianness but not (it seems) bit endianness. I'm currently kicking up a fuss about this on the erlang-questions list, since while Erlang's bitwise big-endian layout works OK for network protocols, it fails for typical little-endian C structures with bit fields. Thanks for the pointer to Ada. Tony. -- f.a.n.finch http://dotat.at/ IRISH SEA: SOUTHERLY, BACKING NORTHEASTERLY FOR A TIME, 3 OR 4. SLIGHT OR MODERATE. SHOWERS. MODERATE OR GOOD, OCCASIONALLY POOR. From simonpj at microsoft.com Wed Aug 22 11:57:18 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Wed Aug 22 11:48:34 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070822145842.GA3363@localhost.localdomain> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <20070822145842.GA3363@localhost.localdomain> Message-ID: | Something I've pondered is adding a more-expressive form of RULES which | works using general pattern matching: Yes, but it would need the rule-matcher in the Simplifier to be more sophisticated. Have a look in specialise/Rules.lhs. No need to be so ambitious; just moving towards what you can do in PrelRules would be an improvement Simon | | {-# XRULES | "*#-to-shift" (*#) | (CoreLit (CoreInt num)) obj | | num .&. (num - 1) == 0 -> | CoreApp (CoreVar "GHC.Prim.iShiftL#") | [obj, CoreLit (CoreInt (lg2 num))] | obj (CoreLit (CoreInt num)) | | num .&. (num - 1) == 0 -> | CoreApp (CoreVar "GHC.Prim.iShiftL#") | [obj, CoreLit (CoreInt (lg2 num))] | #-} | | This would require reusing the TH infrastructure, and (depending on how | much we can abstract) might leak too many details of Core to be | useful; on the other hand it would allow some very interesting domain | optimizations to be done. | | Views might be nice here. | | Opinions on whether something like this is a good idea? | | Stefan From isaacdupree at charter.net Wed Aug 22 12:21:05 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Wed Aug 22 12:14:09 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <20070822145842.GA3363@localhost.localdomain> Message-ID: <46CC6271.1000001@charter.net> Simon Peyton-Jones wrote: > | Something I've pondered is adding a more-expressive form of RULES which > | works using general pattern matching: > > Yes, but it would need the rule-matcher in the Simplifier to be more sophisticated. Have a look in specialise/Rules.lhs. > > No need to be so ambitious; just moving towards what you can do in PrelRules would be an improvement Careful about concealing http://hackage.haskell.org/trac/ghc/ticket/1603 even more than it already is! (Not actually, but it would probably be even harder to track down and still be a bug in some really obscure cases. Maybe there's a flag to disable PrelRules-optimizations for a run of ghc.) Isaac From trebla at vex.net Wed Aug 22 13:29:36 2007 From: trebla at vex.net (Albert Y. C. Lai) Date: Wed Aug 22 13:20:53 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> Message-ID: <46CC7280.7060408@vex.net> Neil Mitchell wrote: >> Other rules that could be interesting are: >> > forall a b. fromInteger a + fromInteger b = fromInteger (a + b) >> > forall a b. fromInteger a * fromInteger b = fromInteger (a * b) > > This is wrong, since the class function can do what it wants. Imagine: > > instance Num String where > (+) = (++) > fromInteger x = show x > > 1 + 2 :: String > > this expression now goes from "12" to "3" by applying this rule. > > You need to be incredibly careful if there are any classes floating around. Do we assume Num instances to obey Num axioms, just like Arrow instances to obey Arrow axioms? My impression is that the GHC de-sugaring of the proc notation contains an optimizing stage that uses arrow axioms. This is a good precedence. If Num obeys ring axioms, fromInteger is a perfectly fine ring-homomorphism. (It's also the first or second homomorphism taught.) If a and b are large integers and the target ring is small, fromInteger (a + b) is likely slower. That is my concern. From ndmitchell at gmail.com Wed Aug 22 13:36:15 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Wed Aug 22 13:27:29 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46CC7280.7060408@vex.net> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> Message-ID: <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> Hi > If Num obeys ring axioms, fromInteger is a perfectly fine > ring-homomorphism. (It's also the first or second homomorphism taught.) Does Int obey these axioms? I'm thinking that assuming properties about things such as numbers is very likely to go wrong very quickly. Monads you might be able to get away with, Numbers you probably can't. Thanks Neil From thomas.hartman at db.com Wed Aug 22 13:38:39 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Wed Aug 22 13:29:47 2007 Subject: [Haskell-cafe] -f flag to runghc broken, or is it just me? (because trying switch elegantly between ghc 6.6 and ghc 6.7) Message-ID: I'm doing a lot of switching between ghc 6.6 and ghc 6.7 on the same computer. I install modules using $ runghc Setup.hs configure etc. I would like to specify which version of ghc should be getting the package installed via the f flag to runghc $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>runghc runghc: syntax: runghc [-f GHCPATH] [GHC-ARGS] FILE ARG... but this appears to be broken. $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>runghc arghandling-nice.hs arghandling-nice.hs: args length does not equal 3. args: : [] usage example: $ runghc arghandling-nice.hs firstarg secondarg thirdarg without the flag works but $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>runghc -f /usr/local/bin/ghc-6.6.1 arghandling-nice.hs does nothing. $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>ls -l /usr/local/bin/ghc-6.6.1 -rwxr-xr-x 1 root root 151 2007-06-16 20:22 /usr/local/bin/ghc-6.6.1 In general I don't like using runghc because it doesn't appear to be documented anywhere except that (incorrect?) usage message. Is there a way to do a package install just using ghc -e? (Sure I could compile, but it helps me sometimes if I can not, a la runghc.) At any rate I couldn't figure out how to pass arguments to main via ghc -e. $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>cat arghandling-nice.hs import System main = do args <- getArgs let usagemsg = "usage example: $ runghc arghandling-nice.hs firstarg secondarg thirdarg" case args of [first,second,third] -> process first second third _ -> error $ "args length does not equal 3. args: : " ++ ( show args ) ++ "\n" ++ usagemsg process a b c = print $ unwords [a,b,c] Thanks for anybody who can help me out with this. Thomas. --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/8470115c/attachment.htm From andrewcoppin at btinternet.com Wed Aug 22 14:02:41 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Wed Aug 22 13:52:57 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> Message-ID: <46CC7A41.1030908@btinternet.com> Neil Mitchell wrote: > >> If Num obeys ring axioms, fromInteger is a perfectly fine >> ring-homomorphism. (It's also the first or second homomorphism taught.) >> > > Does Int obey these axioms? I'm thinking that assuming properties > about things such as numbers is very likely to go wrong very quickly. > Monads you might be able to get away with, Numbers you probably can't. > Now, see, you don't find this kind of discussion in other languages. If you go talk about Java, people just flame each other about whether we should have true MI or not... ;-) Ah, I *like* it here. :-D From thomas.hartman at db.com Wed Aug 22 14:03:00 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Wed Aug 22 13:54:12 2007 Subject: workaround found, pipe it through ghci Re: [Haskell-cafe] -f flag to runghc broken, or is it just me? (because trying switch elegantly between ghc 6.6 and ghc 6.7) In-Reply-To: Message-ID: this works. now if only there were a "quiet" option for ghci... well, for me, I guess this may be goodbye to poor sad undocumented malfunctioning runghc.. hartthoma@linuxpt:~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>echo ":main 1 2 3" | /usr/local/bin/ghci-6.6.1 arghandling-nice.hs ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.6.1, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base ... linking ... done. [1 of 1] Compiling Main ( arghandling-nice.hs, interpreted ) Ok, modules loaded: Main. *Main> Loading package haskell98 ... linking ... done. "1 2 3" *Main> Leaving GHCi. Thomas Hartman Sent by: haskell-cafe-bounces@haskell.org 08/22/2007 01:38 PM To "haskell-cafe@haskell.org" cc Subject [Haskell-cafe] -f flag to runghc broken, or is it just me? (because trying switch elegantly between ghc 6.6 and ghc 6.7) I'm doing a lot of switching between ghc 6.6 and ghc 6.7 on the same computer. I install modules using $ runghc Setup.hs configure etc. I would like to specify which version of ghc should be getting the package installed via the f flag to runghc $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>runghc runghc: syntax: runghc [-f GHCPATH] [GHC-ARGS] FILE ARG... but this appears to be broken. $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>runghc arghandling-nice.hs arghandling-nice.hs: args length does not equal 3. args: : [] usage example: $ runghc arghandling-nice.hs firstarg secondarg thirdarg without the flag works but $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>runghc -f /usr/local/bin/ghc-6.6.1 arghandling-nice.hs does nothing. $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>ls -l /usr/local/bin/ghc-6.6.1 -rwxr-xr-x 1 root root 151 2007-06-16 20:22 /usr/local/bin/ghc-6.6.1 In general I don't like using runghc because it doesn't appear to be documented anywhere except that (incorrect?) usage message. Is there a way to do a package install just using ghc -e? (Sure I could compile, but it helps me sometimes if I can not, a la runghc.) At any rate I couldn't figure out how to pass arguments to main via ghc -e. $ :~/personal/PersonalRepos/pharchive/learning/haskell/UnixTools/arghandling>cat arghandling-nice.hs import System main = do args <- getArgs let usagemsg = "usage example: $ runghc arghandling-nice.hs firstarg secondarg thirdarg" case args of [first,second,third] -> process first second third _ -> error $ "args length does not equal 3. args: : " ++ ( show args ) ++ "\n" ++ usagemsg process a b c = print $ unwords [a,b,c] Thanks for anybody who can help me out with this. Thomas. --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/845e549f/attachment-0001.htm From byorgey at gmail.com Wed Aug 22 14:13:22 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Wed Aug 22 14:04:35 2007 Subject: workaround found, pipe it through ghci Re: [Haskell-cafe] -f flag to runghc broken, or is it just me? (because trying switch elegantly between ghc 6.6 and ghc 6.7) In-Reply-To: References: Message-ID: <22fcbd520708221113m17e9a097q721dd6a393733ad6@mail.gmail.com> > > this works. now if only there were a "quiet" option for ghci... > > But there is! It's called -v0. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/7e939983/attachment.htm From stefanor at cox.net Wed Aug 22 14:13:37 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 22 14:04:53 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> Message-ID: <20070822181337.GA4124@localhost.localdomain> On Wed, Aug 22, 2007 at 06:36:15PM +0100, Neil Mitchell wrote: > Hi > > > If Num obeys ring axioms, fromInteger is a perfectly fine > > ring-homomorphism. (It's also the first or second homomorphism taught.) > > Does Int obey these axioms? I'm thinking that assuming properties > about things such as numbers is very likely to go wrong very quickly. > Monads you might be able to get away with, Numbers you probably can't. Int does obey the axioms, it's the classical ring ?[4294967296]. Double, however, does not: stefan@stefans:~$ ghci GHCi, version 6.7.20070712: http://www.haskell.org/ghc/ :? for help Loading package base ... linking ... done. Prelude> let x = 10000000000000000000000 ; y = 1 - x Prelude> fromInteger (x + y) :: Double 1.0 Prelude> fromInteger x + fromInteger y :: Double 0.0 Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/81a5fa18/attachment.bin From rich.neswold at gmail.com Wed Aug 22 14:27:00 2007 From: rich.neswold at gmail.com (Rich Neswold) Date: Wed Aug 22 14:18:12 2007 Subject: [Haskell-cafe] Help using CGIT Message-ID: <14cf844b0708221126l37c1654bhd8b120e78855377c@mail.gmail.com> Hello! I've been having a tough time trying to use the CGI monad transformer (CGIT). Hopefully someone can show me my misstep(s). I have a CGI script that's evolving. Early on, it needed a single database access. Now it's doing two accesses (and it looks like I'll be adding more.) Rather than making a connection for each access, the script needs to connect once. To do this, I want to combine the CGI monad with the Reader monad. This version compiles cleanly: > module AppMonad (App (..), runApp) > where > > import Control.Exception (bracket) > import Control.Monad.Reader > import Network.CGI.Monad > import Network.CGI.Protocol > import System.IO (stdin, stdout) > import Database.HSQL.PostgreSQL > > newtype App a = App (ReaderT Connection (CGIT IO) a) > deriving (Monad, MonadIO, MonadReader Connection) > > runApp :: App CGIResult -> IO () > runApp (App a) = > bracket (connect "host" "dbname" "user" "password") > disconnect > (\c -> do { env <- getCGIVars > ; hRunCGI env stdin stdout (runCGIT (runReaderT a c)) > ; return () } ) Unfortunately, when another module tries to actually use the monad, I get warnings about "No instance for (MonadCGI App)". I tried making an instance: > instance MonadCGI App where > cgiAddHeader = ? > cgiGet = ? But I don't know how to define these functions. I tried various 'lift'ing combinations, but couldn't come up with a solution that would compile. I'm also disappointed that I had to break apart 'runCGI' (by cut-and-pasting its source) because I couldn't make it believe my monad looked enough like MonadCGI. My previous experiment with monad transformers was successful. It didn't use CGIT, however, so the 'run*' functions were simpler. Does anyone have an example of using CGIT (I didn't find any from Google)? Shouldn't I be able to use 'runCGI' with my monad? CGIT users shouldn't be required to re-implement 'runCGI", right? Any help or ideas is appreciated! -- Rich JID: rich@neswold.homeunix.net AIM: rnezzy From twanvl at gmail.com Wed Aug 22 15:14:19 2007 From: twanvl at gmail.com (Twan van Laarhoven) Date: Wed Aug 22 15:05:19 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070822181337.GA4124@localhost.localdomain> References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> <20070822181337.GA4124@localhost.localdomain> Message-ID: <46CC8B0B.7020603@gmail.com> Stefan O'Rear wrote: > On Wed, Aug 22, 2007 at 06:36:15PM +0100, Neil Mitchell wrote: > >>Hi >> >> >>>If Num obeys ring axioms, fromInteger is a perfectly fine >>>ring-homomorphism. (It's also the first or second homomorphism taught.) >> >>Does Int obey these axioms? I'm thinking that assuming properties >>about things such as numbers is very likely to go wrong very quickly. >>Monads you might be able to get away with, Numbers you probably can't. > > > Int does obey the axioms, it's the classical ring ?[4294967296]. > Double, however, does not: But Double is already quite badly behaved: > let x = 1e20 > Prelude> 1 + (x - x) > 1.0 > Prelude> (1 + x) - x > 0.0 Using the fromInteger (and fromRational) axioms should only *increase* precission, I don't see how that is such a bad thing. Also, as far as I can see GHC already does this optimizations if the type is specialized to Double. Except for the fact that the PrelRules rules don't seem to fire, because the constants get floated out. Twan From overdrigzed at gmail.com Wed Aug 22 15:35:35 2007 From: overdrigzed at gmail.com (Rodrigo Queiro) Date: Wed Aug 22 15:26:46 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46CC8B0B.7020603@gmail.com> References: <46C82F23.9020509@btinternet.com> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> <20070822181337.GA4124@localhost.localdomain> <46CC8B0B.7020603@gmail.com> Message-ID: <2eb8984a0708221235r53c98b83kd2ae96c79196047a@mail.gmail.com> > Using the fromInteger (and fromRational) axioms should only *increase* > precission, I don't see how that is such a bad thing. I think it's bad if the behaviour of your program depends on the optimisation level. On 22/08/07, Twan van Laarhoven wrote: > Stefan O'Rear wrote: > > On Wed, Aug 22, 2007 at 06:36:15PM +0100, Neil Mitchell wrote: > > > >>Hi > >> > >> > >>>If Num obeys ring axioms, fromInteger is a perfectly fine > >>>ring-homomorphism. (It's also the first or second homomorphism taught.) > >> > >>Does Int obey these axioms? I'm thinking that assuming properties > >>about things such as numbers is very likely to go wrong very quickly. > >>Monads you might be able to get away with, Numbers you probably can't. > > > > > > Int does obey the axioms, it's the classical ring ?[4294967296]. > > Double, however, does not: > > But Double is already quite badly behaved: > > let x = 1e20 > > Prelude> 1 + (x - x) > > 1.0 > > Prelude> (1 + x) - x > > 0.0 > > Using the fromInteger (and fromRational) axioms should only *increase* > precission, I don't see how that is such a bad thing. > > Also, as far as I can see GHC already does this optimizations if the > type is specialized to Double. Except for the fact that the PrelRules > rules don't seem to fire, because the constants get floated out. > > Twan > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > From wss at Cs.Nott.AC.UK Wed Aug 22 15:36:29 2007 From: wss at Cs.Nott.AC.UK (Wouter Swierstra) Date: Wed Aug 22 15:28:36 2007 Subject: [Haskell-cafe] Old editions of The Monad.Reader lost In-Reply-To: References: Message-ID: Dear Henk-Jan, Thanks for pointing this out. I'll try to contact the authors and obtain their permission to move to the new wiki. What is the best way to move content to the new wiki? Surely these articles aren't the first to migrate from hawiki... Any technical advice would be much appreciated. Thanks, Wouter This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. From hjgtuyl at chello.nl Wed Aug 22 16:10:34 2007 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Wed Aug 22 16:01:47 2007 Subject: [Haskell-cafe] Old editions of The Monad.Reader lost In-Reply-To: References: Message-ID: On Wed, 22 Aug 2007 21:36:29 +0200, Wouter Swierstra wrote: > Thanks for pointing this out. I'll try to contact the authors and obtain > their permission to move to the new wiki. Another approach would be, to create (non-haskellwiki) pages with different licensing. You than need the autority to create normal HTML pages on www.haskell.org, of course. -- Met vriendelijke groet, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- From duncan.coutts at worc.ox.ac.uk Wed Aug 22 16:53:27 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Wed Aug 22 16:43:21 2007 Subject: [Haskell-cafe] cabal install of HDBC-odbc fails on ghc 6.7, -I flag causes problems In-Reply-To: References: Message-ID: <1187816007.1034.2.camel@localhost> On Mon, 2007-08-20 at 13:10 -0400, Thomas Hartman wrote: > > problemw with the -I flag to ghc are causing cabal install to fail for > hdbc-odbc (darcs head). > Any tips on debugging this cabal install would be appreciated. > $ runghc Setup.hs configure; runghc Setup.hs build Try with -v3 is: runghc Setup.hs build -v3 this will give extremely verbose output. We'd like to see the last bit to see what ghc command line exactly is failing. It'll show the command line arguments in Haskell show format eg ["-I", "/"] Duncan From coeus at gmx.de Wed Aug 22 17:24:32 2007 From: coeus at gmx.de (Marc A. Ziegert) Date: Wed Aug 22 17:15:55 2007 Subject: [Haskell-cafe] #haskell irc channel reaches 400 users In-Reply-To: <46CB4E62.8040804@vex.net> References: <20070821003329.GA13546@cse.unsw.EDU.AU> <46CB20F1.2080104@btinternet.com> <46CB4E62.8040804@vex.net> Message-ID: <200708222324.40393.coeus@gmx.de> i interpret it as this: all [ usage x > usage y || fun_to_talk_about x > fun_to_talk_about y | let lang=[minBound .. maxBound] -- C++,Haskell,Java,etc. , x<-lang , y<-lang , irc_channel_users x > irc_channel_users y ] - marc Am Dienstag, 21. August 2007 schrieb Albert Y. C. Lai: > Andrew Coppin wrote: > > ...does this mean Haskell is officially harder to understand than Lisp, > > Java, Perl and O'Caml? :-} > > > > (OTOH, does this mean Haskell is easier to understand than PHP or C++?) > > Or, Haskell is the easiest to understand of them all. > > Reason: Extremely large channel means so hard to understand that many > people want help. Extremely small channel means so hard to understand > that few people show interest. The middle-sized channel sits at the > sweet spot. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/fda49121/attachment-0001.bin From igloo at earth.li Wed Aug 22 17:28:28 2007 From: igloo at earth.li (Ian Lynagh) Date: Wed Aug 22 17:19:41 2007 Subject: [Haskell-cafe] Help using CGIT In-Reply-To: <14cf844b0708221126l37c1654bhd8b120e78855377c@mail.gmail.com> References: <14cf844b0708221126l37c1654bhd8b120e78855377c@mail.gmail.com> Message-ID: <20070822212828.GA26256@matrix.chaos.earth.li> On Wed, Aug 22, 2007 at 01:27:00PM -0500, Rich Neswold wrote: > > > newtype App a = App (ReaderT Connection (CGIT IO) a) > > deriving (Monad, MonadIO, MonadReader Connection) > > Unfortunately, when another module tries to actually use the monad, I > get warnings about "No instance for (MonadCGI App)". I tried making an > instance: > > > instance MonadCGI App where > > cgiAddHeader = ? > > cgiGet = ? You have three choices: 1: Install the unportable (works in GHC, not sure about hugs, not in anything else TTBOMK) cgi-undecidable package and import Network.CGI.Undecidable. instance MonadCGI App where cgiAddHeader n v = App $ cgiAddHeader n v cgiGet x = App $ cgiGet x Here Network.CGI.Undecidable provides the instance for MonadReader. The nice thing about this one is it'll keep working is you later add a StateT, say. 2: Provide an instance for ReaderT and an instance for App that uses it: instance MonadCGI App where cgiAddHeader n v = App $ cgiAddHeader n v cgiGet x = App $ cgiGet x instance MonadCGI m => MonadCGI (ReaderT c m) where cgiAddHeader n v = lift $ cgiAddHeader n v cgiGet x = lift $ cgiGet x Here the individual bits will keep working if you add a StateT, but you will also need to add a StateT instance. 3: Provide a single instance for App that does the whole thing: instance MonadCGI App where cgiAddHeader n v = App $ lift $ cgiAddHeader n v cgiGet x = App $ lift $ cgiGet x This one you would obviously have to change if you added a StateT. > I'm also disappointed that I had to break apart > 'runCGI' (by cut-and-pasting its source) because I couldn't make it > believe my monad looked enough like MonadCGI. runApp :: App CGIResult -> IO () runApp (App a) = bracket (connect "host" "dbname" "user" "password") disconnect (\c -> runCGI (runReaderT a c)) (the above is mostly untested, so it may be wrong in some details). Thanks Ian From igloo at earth.li Wed Aug 22 17:44:43 2007 From: igloo at earth.li (Ian Lynagh) Date: Wed Aug 22 17:35:55 2007 Subject: [Haskell-cafe] -f flag to runghc broken, or is it just me? (because trying switch elegantly between ghc 6.6 and ghc 6.7) In-Reply-To: References: Message-ID: <20070822214443.GB26256@matrix.chaos.earth.li> On Wed, Aug 22, 2007 at 01:38:39PM -0400, Thomas Hartman wrote: > > $ runghc -f /usr/local/bin/ghc-6.6.1 arghandling-nice.hs > > does nothing. Contrary to the usage message, you aren't actually allowed a space after "-f" in 6.6.1 (but you are in 6.7). Use runghc -f/usr/local/bin/ghc-6.6.1 arghandling-nice.hs instead. Thanks Ian From derek.a.elkins at gmail.com Wed Aug 22 18:24:58 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Wed Aug 22 18:16:16 2007 Subject: [Haskell-cafe] #haskell irc channel reaches 400 users In-Reply-To: <200708222324.40393.coeus@gmx.de> References: <20070821003329.GA13546@cse.unsw.EDU.AU> <46CB20F1.2080104@btinternet.com> <46CB4E62.8040804@vex.net> <200708222324.40393.coeus@gmx.de> Message-ID: <1187821498.5384.1.camel@derek-laptop> On Wed, 2007-08-22 at 23:24 +0200, Marc A. Ziegert wrote: > i interpret it as this: > > all [ usage x > usage y || fun_to_talk_about x > fun_to_talk_about y > | let lang=[minBound .. maxBound] -- C++,Haskell,Java,etc. > , x<-lang > , y<-lang > , irc_channel_users x > irc_channel_users y > ] all [ x `isUsedMoreThan` y || x `isMoreFunToTalkAboutThan` y | ...] From fxn at hashref.com Wed Aug 22 19:08:25 2007 From: fxn at hashref.com (Xavier Noria) Date: Wed Aug 22 18:59:54 2007 Subject: [Haskell-cafe] help understanding lazy evaluation Message-ID: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> I am learning Haskell with "Programming in Haskell" (an excellent book BTW). I have background in several languages but none of them has lazy evaluation. By now I am getting along with the intuitive idea that things are not evaluated until needed, but there's an example I don't understand (which means the intuitive idea needs some revision :-). We have factors(), defined on page 39 like this[*]: factors :: Int -> [Int] factors n = [x | x <- [1..n], n `mod` x == 0] and we base prime() on it this way: prime :: Int -> Bool prime n = factors n == [1, n] Now, the books says prime does not necessarily compute all of the factors of n because of lazy evaluation. Meaning that if n is composite as soon as some non-trivial divisor appears we halt computation and return False. My vague intuition said "we either need factors or we don't, we do because we need to perform the test, so we compute it". That's wrong, so a posteriori the explanation must be something like this: 1. someone knows we want factor() to perform an equality test 2. someone knows an equality test between lists is False as soon as we have a mismatch, left to right 3. thus, instead of evaluating factors completely we are going to build sublists of the result and perform the tests on those ones against [1, n]. That's a lot of *context* about that particular evaluation of factors, in particular step puzzles me. Can anyone explain how lazy evaluation fits there? I suspect the key is the implementation of == together with the fact that list comprehensions are lazy themselves, is that right? -- fxn [*] Which notation do you use for functions in text? is f() ok? From ndmitchell at gmail.com Wed Aug 22 19:28:49 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Wed Aug 22 19:20:01 2007 Subject: [Haskell-cafe] help understanding lazy evaluation In-Reply-To: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> Message-ID: <404396ef0708221628w56066827o9193b1f02af9b654@mail.gmail.com> Hi > factors :: Int -> [Int] > factors n = [x | x <- [1..n], n `mod` x == 0] > > prime :: Int -> Bool > prime n = factors n == [1, n] > > My vague intuition said "we either need factors or we don't, we do > because we need to perform the test, so we compute it". That's wrong, > so a posteriori the explanation must be something like this: The key point is that factors doesn't either compute all or none, it may compute part of the value. It does this by computing something like: _:_ 1:_ 1:_:_ where _ is the unevaluated bit, i.e. it computes one bit of the result at a time. Equals also has this property, it can be defined as: a:as == b:bs = a == b && as == bs [] == [] = True _ == _ = False If you have (1:_) == (2:_) then the match will fail instantly. > That's a lot of *context* about that particular evaluation of > factors, in particular step puzzles me. Can anyone explain how lazy > evaluation fits there? I suspect the key is the implementation of == > together with the fact that list comprehensions are lazy themselves, > is that right? Everything is lazy, to all subparts. You might get along better with a reasoning more of the form "to compute anything, this expression will demand this expression" - rather than your "someone knows we'll need". If you follow example derivations you'll see that there is always a very clear idea of what needs to happen next for the computation to proceed, which explains the laziness quite naturally. > [*] Which notation do you use for functions in text? is f() ok? Sure, although a little unusual for Haskell where f() means f applied to the empty tuple. Some people use |f| (generally those who use latex), but generally it can be inferred from the context what is a function Thanks Neil From mvanier at cs.caltech.edu Wed Aug 22 19:39:54 2007 From: mvanier at cs.caltech.edu (Michael Vanier) Date: Wed Aug 22 19:31:06 2007 Subject: [Haskell-cafe] help understanding lazy evaluation In-Reply-To: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> Message-ID: <46CCC94A.2000902@cs.caltech.edu> Xavier, First off, we don't put the () after function names in Haskell. What's happening is this (experts please correct any mistakes here): 1) You call prime on a number (e.g. 42). 2) In order to evaluate this further, (factors 42) must be evaluated at least partially to give input to == in prime. So (factors 42) is evaluated to give the first list value, which is 1. 3) The == in prime compares the 1 at the head of the list generated by (factors 42) (whose tail hasn't been evaluated yet) with the 1 at the head of [1, 42], and finds that they match, so == can continue processing. 4) (factors 42) resumes to compute another list value, which is 2 (a factor of 42). 5) == in prime compares 2 with 42, finds they don't match, and thus (primes 42) returns False. So not all the factors have been computed; in fact, only two of them were needed to prove that 42 is not prime. The interesting aspect of all this is that laziness allowed us to modularize the problem of primality testing into two separate (simpler) functions, instead of having to interleave generation of factors and testing of factors. This makes code easier to write and more modular. Hughes' paper "Why Functional Programming Matters" is a must-read for more on this. Lazy evaluation can be very tricky to wrap your head around, and there are lots of subtle issues that crop up where you think something is lazy but it's not, or you think something is strict but it's not. There are ways to force lazy/strict behavior, but they're somewhat more advanced. HTH, Mike Xavier Noria wrote: > I am learning Haskell with "Programming in Haskell" (an excellent book > BTW). > > I have background in several languages but none of them has lazy > evaluation. By now I am getting along with the intuitive idea that > things are not evaluated until needed, but there's an example I don't > understand (which means the intuitive idea needs some revision :-). > > We have factors(), defined on page 39 like this[*]: > > factors :: Int -> [Int] > factors n = [x | x <- [1..n], n `mod` x == 0] > > and we base prime() on it this way: > > prime :: Int -> Bool > prime n = factors n == [1, n] > > Now, the books says prime does not necessarily compute all of the > factors of n because of lazy evaluation. Meaning that if n is composite > as soon as some non-trivial divisor appears we halt computation and > return False. > > My vague intuition said "we either need factors or we don't, we do > because we need to perform the test, so we compute it". That's wrong, so > a posteriori the explanation must be something like this: > > 1. someone knows we want factor() to perform an equality test > > 2. someone knows an equality test between lists is False as soon as we > have a mismatch, left to right > > 3. thus, instead of evaluating factors completely we are going to build > sublists of the result and perform the tests on those ones against [1, n]. > > That's a lot of *context* about that particular evaluation of factors, > in particular step puzzles me. Can anyone explain how lazy evaluation > fits there? I suspect the key is the implementation of == together with > the fact that list comprehensions are lazy themselves, is that right? > > -- fxn > > [*] Which notation do you use for functions in text? is f() ok? > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe From derek.a.elkins at gmail.com Wed Aug 22 19:43:45 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Wed Aug 22 19:35:01 2007 Subject: [Haskell-cafe] help understanding lazy evaluation In-Reply-To: <404396ef0708221628w56066827o9193b1f02af9b654@mail.gmail.com> References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> <404396ef0708221628w56066827o9193b1f02af9b654@mail.gmail.com> Message-ID: <1187826225.5384.5.camel@derek-laptop> > > > [*] Which notation do you use for functions in text? is f() ok? > > Sure, although a little unusual for Haskell where f() means f applied > to the empty tuple. Some people use |f| (generally those who use > latex), but generally it can be inferred from the context what is a > function Neil's answer was complete I just want to elaborate on this last point. f is the most logical (and for Haskell things appropriate) notation. It's an odd historical quirk of mathematical notation that using f(x) for f is still so common. From benjamin.franksen at bessy.de Wed Aug 22 19:47:38 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Wed Aug 22 19:39:08 2007 Subject: [Haskell-cafe] Re: Re: Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D ) References: <837db430708100022j16cce934scb997a596cd8a74f@mail.gmail.com> <46BC26E3.1030902@cs.caltech.edu> <837db430708100158m3f2f42e3k91712350933e7e5c@mail.gmail.com> <837db430708212027p56348f57x5feadecdf716ccd7@mail.gmail.com> Message-ID: Hugh Perkins wrote: > On 8/11/07, Benjamin Franksen wrote: >> A certain amount >> of dynamism wrt the message content (high level protocol) is necessary for >> systems for which Erlang was designed, namely large distributed control >> systems with minimum down-times. For large distributed installations it is >> a matter of practicality to be able to upgrade one component w/o needing to >> recompile (and then re-start) all the other components that it communicates >> with -- for systems with expected down-times of 3 Minutes per year it is a >> matter of being able to meet the specifications. You'll have a hard time >> finding high-availability or large control systems which use an IDL >> approach for communication. > > Hmmm, that's interesting. I'd never considered lack of typing to be a > good thing for system robustness before! I didn't use the term robustness, which is typically used to express how well a program handles unexpected run-time conditions. What I refered to is maintainability in the face of continually changing requirements and the need to gradually upgrade components. (And rest assured I'm normally all for static typing!) > Question: to what extent does interface versioning get around this > problem? I assume the issue we're trying to address is to be able to > upgrade clients/servers/peers independently, without losing > connectivity with unupgraded systems? Yes (to the latter), and 'to a certain extent' to the former. > So, using versioned interfaces: > > Initially we have: > client1 marketinterface1 > server marketinterface1 > client2 marketinterface1 > > Then, we upgrade the server with a new interface, marketinterface2. > Significantly, we keep the old interface. So now we have: > > client1 marketinterface1 > server marketinterface1, marketinterface2 > client2 marketinterface1 > > The whole system continues to work: client1 and client2 continue to > chat with server on marketinterface1. > > Now we upgrade client1: > > client1 marketinterface2 > server marketinterface1, marketinterface2 > client2 marketinterface1 > > ... and client2: > > client1 marketinterface2 > server marketinterface1, marketinterface2 > client2 marketinterface2 > > Finally, we deprecate/remove marketinterface1 from the server: > > client1 marketinterface2 > server marketinterface2 > client2 marketinterface2 Yes, you can somewhat reduce the impact of an IDL based approach if you introduce the new interface in addition to the old one (and only deprecate the old interface after all components have been upgraded). However, this approach has its limits, especially if you consider large installation with 10s to 1000s of servers and clients (many of them being both at the same time), especially if upgrades are very frequent due to changing physical parameters, new requirements, additional instrumentation, etc. Let us be clear on one point: It is of course not possible for a client to make use of new features offered by a server if they do not know about these features. With an IDL approach, knowledge about new features need re-compilation and usually also new code to handle the new information. With a dynamic approach, this becomes largely a matter of changing the /configuration/ of a client, which is a much less disruptive process. Cheers Ben From dons at cse.unsw.edu.au Wed Aug 22 20:17:50 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Wed Aug 22 20:09:28 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <2eb8984a0708221235r53c98b83kd2ae96c79196047a@mail.gmail.com> References: <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> <20070822181337.GA4124@localhost.localdomain> <46CC8B0B.7020603@gmail.com> <2eb8984a0708221235r53c98b83kd2ae96c79196047a@mail.gmail.com> Message-ID: <20070823001750.GA7715@cse.unsw.EDU.AU> overdrigzed: > > Using the fromInteger (and fromRational) axioms should only *increase* > > precission, I don't see how that is such a bad thing. > > I think it's bad if the behaviour of your program depends on the > optimisation level. > Isn't this how the thread started? $ gcc t.c -o a $ ./a 100000000 zsh: segmentation fault (core dumped) ./a 100000000 $ gcc -O3 t.c -o b $ ./b 100000000 987459712 ;) -- Don From derek.a.elkins at gmail.com Wed Aug 22 20:30:20 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Wed Aug 22 20:21:34 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <20070823001750.GA7715@cse.unsw.EDU.AU> References: <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> <20070822181337.GA4124@localhost.localdomain> <46CC8B0B.7020603@gmail.com> <2eb8984a0708221235r53c98b83kd2ae96c79196047a@mail.gmail.com> <20070823001750.GA7715@cse.unsw.EDU.AU> Message-ID: <1187829020.5384.7.camel@derek-laptop> On Thu, 2007-08-23 at 10:17 +1000, Donald Bruce Stewart wrote: > overdrigzed: > > > Using the fromInteger (and fromRational) axioms should only *increase* > > > precission, I don't see how that is such a bad thing. > > > > I think it's bad if the behaviour of your program depends on the > > optimisation level. > > > > Isn't this how the thread started? > > $ gcc t.c -o a > $ ./a 100000000 > zsh: segmentation fault (core dumped) ./a 100000000 > > $ gcc -O3 t.c -o b > $ ./b 100000000 > 987459712 Don't make me pull out sum. From ryani.spam at gmail.com Wed Aug 22 20:39:54 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Wed Aug 22 20:31:06 2007 Subject: [Haskell-cafe] help understanding lazy evaluation In-Reply-To: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> Message-ID: <2f9b2d30708221739w6d20d0a6la24e061f22e6d213@mail.gmail.com> The insight is that the functions called can be lazy internally; the computation doesn't proceed by either fully evaluating something or not, but rather by rewriting parts of the computation graph. Here is a trace of the evaluation of "prime" for integers n > 1: prime n => factors n == [1,n] => factors n == 1 : n : [] -- remove syntactical sugar from the list => [x | x <- [1..n], n `mod` x == 0] == 1 : n : [] =>* 1 : [x | x <- [2..n], n `mod` x == 0] == 1 : n : [] -- n mod 1 is always 0 => 1 == 1 && [x | x <- [2..n], n `mod` x == 0] == n : [] => True && [x | x <- [2..n], n `mod` x == 0] == n : [] => [x | x <- [2..n], n `mod` x == 0] == n : [] This much computation happens for every single n. One of two things happens here; either we have another factor < N, or we don't. Case 1: There is at least one other factor < n. Let z be the smallest such factor: =>* z : [x | x <- [(z+1)..n], n `mod` x == 0] == n : [] => z == n && [x | x <- [(z+1)..n], n `mod` x == 0] == [] => False && [x | x <- [(z+1)..n], n `mod` x == 0] == [] => False Case 2: There are no other factors < n. =>* n : [x | x <- [], n `mod` x == 0] == n : [] => n == n && [x | x <- [], n `mod` x == 0] == [] => True && [x | x <- [], n `mod` x == 0] == [] => [x | x <- [], n `mod` x == 0] == [] => [] == [] => True Exercise: Annotate each line in the above trace with a description of why the reduction is valid. To be totally clear with this trace, you would need to desguar the list comprehension and some of the more primitive functions. The lines marked with =>* are a bit handwavy because they skip evaluation. Here's the desugaring of this list comprehension and full definitions of the other functions in used in this example: [x | x <- [1..n], n `mod` x == 0] => concatMap ok [1..n] where ok x = if n `mod` x == 0 then [x] else [] concatMap :: (a -> [b]) -> [a] -> [b] concatMap f [] = [] concatMap f (x:xs) = f x ++ concatMap f xs (++) :: [a] -> [a] -> [a] (x:xs) ++ ys = x : (xs ++ ys) [] ++ ys = ys (&&) :: Bool -> Bool -> Bool True && x = x False && _ = False (==) :: [Int] -> [Int] -> Bool -- specialized via typeclass "Eq [Int]" (x:xs) == (y:ys) = x == y && xs == ys [] == [] = True _ == _ = False All other functions used are primitives. Exercise: Write out a full execution trace for n == 3 and n == 4 with the desugaring and Prelude functions given above. On 8/22/07, Xavier Noria wrote: > > I am learning Haskell with "Programming in Haskell" (an excellent > book BTW). > > I have background in several languages but none of them has lazy > evaluation. By now I am getting along with the intuitive idea that > things are not evaluated until needed, but there's an example I don't > understand (which means the intuitive idea needs some revision :-). > > We have factors(), defined on page 39 like this[*]: > > factors :: Int -> [Int] > factors n = [x | x <- [1..n], n `mod` x == 0] > > and we base prime() on it this way: > > prime :: Int -> Bool > prime n = factors n == [1, n] > > Now, the books says prime does not necessarily compute all of the > factors of n because of lazy evaluation. Meaning that if n is > composite as soon as some non-trivial divisor appears we halt > computation and return False. > > My vague intuition said "we either need factors or we don't, we do > because we need to perform the test, so we compute it". That's wrong, > so a posteriori the explanation must be something like this: > > 1. someone knows we want factor() to perform an equality test > > 2. someone knows an equality test between lists is False as soon as > we have a mismatch, left to right > > 3. thus, instead of evaluating factors completely we are going to > build sublists of the result and perform the tests on those ones > against [1, n]. > > That's a lot of *context* about that particular evaluation of > factors, in particular step puzzles me. Can anyone explain how lazy > evaluation fits there? I suspect the key is the implementation of == > together with the fact that list comprehensions are lazy themselves, > is that right? > > -- fxn > > [*] Which notation do you use for functions in text? is f() ok? > > _______________________________________________ > 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/haskell-cafe/attachments/20070822/46841c4f/attachment.htm From benjamin.franksen at bessy.de Wed Aug 22 20:53:23 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Wed Aug 22 20:44:44 2007 Subject: [Haskell-cafe] Re: Using Collections: ElemsView and KeysView References: Message-ID: Jean-Philippe Bernardy wrote: > foldr on ElemsView is defined as such: > >> foldr f i (ElemsView c) = foldr (f . snd) i c > > so, for example: > >> getElementList = toList . ElemViews Ok, thanks, this helps. I had forgot to look at the instances. > When I designed this code (some years ago), I didn't like the "fold" of Map to > have the type: > >> fold :: (a -> b -> b) -> b -> Map k a -> b > > This just doesn't make sense if we see maps as a collection of (key, value) > pairs. (Indeed, toList :: Map k a -> [(k, a)]) > > In order to be consistent, but to provide an easy way to migrate to the new > collection classes I was designing, I provided the ElemViews/KeyViews to > "switch" to the former behaviour on a case by case basis. I understand the motivation. Could you say something about the functions withElems and withKeys? Their types contain a mysterious type constructor 'T' that is not documented in the haddock docs. The source file says 'type T a = a->a' so I guess this is for cases where I want to 'lift' a function mapping e.g. keys to keys to a fucntion on Maps? > This also allows for definining optimized versions of foldr, etc. for each types > that supports "Views", but this was tedious, so I never did it. GHC "RULE" > pragma is probably better suited to the purpose anyway. > > As for the lack of documentation, everyone is very welcome to contribute ;) I'd love to, but my understanding is still somewhat limited... Cheers (and thanks) Ben P.S. The collections framework is great, but the type errors one sometimes gets are horrible. When I started to see whether I had understood what you wrote above I got: Couldn't match expected type `c' (a rigid variable) against inferred type `Str' `c' is bound by the type signature for `macros' at MacroSubst.hs:13:24 Expected type: (Str, c) Inferred type: (Str, Str) When using functional dependencies to combine Foldable (Data.Map.Map k a) (k, a), arising from the instance declaration at Defined in Data.Collections Foldable (Data.Map.Map Str Str) (Str, c), arising from use of `unions' at Gadgets.hs:95:13-30 When trying to generalise the type inferred for `macros' Signature type: forall c1. (Collection c1 String, Set c1 String) => Attributes -> c1 Type to generalise: forall c1. (Collection c1 String, Set c1 String) => Attributes -> c1 From rich.neswold at gmail.com Wed Aug 22 21:34:53 2007 From: rich.neswold at gmail.com (Rich Neswold) Date: Wed Aug 22 21:26:04 2007 Subject: [Haskell-cafe] Help using CGIT In-Reply-To: <20070822212828.GA26256@matrix.chaos.earth.li> References: <14cf844b0708221126l37c1654bhd8b120e78855377c@mail.gmail.com> <20070822212828.GA26256@matrix.chaos.earth.li> Message-ID: <14cf844b0708221834na33ffekb237b253d1b04ab1@mail.gmail.com> On 8/22/07, Ian Lynagh wrote: > > On Wed, Aug 22, 2007 at 01:27:00PM -0500, Rich Neswold wrote: > > > > > newtype App a = App (ReaderT Connection (CGIT IO) a) > > > deriving (Monad, MonadIO, MonadReader Connection) > > > > Unfortunately, when another module tries to actually use the monad, I > > get warnings about "No instance for (MonadCGI App)". I tried making an > > instance: > > > > > instance MonadCGI App where > > > cgiAddHeader = ? > > > cgiGet = ? > > You have three choices: > > 1: > > 2: > > 3: > Provide a single instance for App that does the whole thing: > instance MonadCGI App where > cgiAddHeader n v = App $ lift $ cgiAddHeader n v > cgiGet x = App $ lift $ cgiGet x > This one you would obviously have to change if you added a StateT. > Bingo! Method #3 works beautifully! I missed the using-lift-with-the-constructor permutation. Thanks for your help! -- Rich JID: rich@neswold.homeunix.net AIM: rnezzy -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/f4fe0015/attachment.htm From ok at cs.otago.ac.nz Wed Aug 22 22:44:13 2007 From: ok at cs.otago.ac.nz (ok) Date: Wed Aug 22 22:35:33 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708212007v60cf2b64m53a8a0b98e047168@mail.gmail.com> References: <837db430708092113k3d33a412u7b9fc71229464ec5@mail.gmail.com> <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <125EACD0CAE4D24ABDB4D148C4593DA901BDFC0D@GBLONXMB02.corp.amvescap.net> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> <46CB21C7.4070708@btinternet.com> <837db430708212007v60cf2b64m53a8a0b98e047168@mail.gmail.com> Message-ID: <5AE478EE-4057-4DCE-A9C5-EE001813346E@cs.otago.ac.nz> > On 8/21/07, Andrew Coppin wrote: >> I highly doubt that automatic threading will happen any time this >> decade Hm. I happen to have an old Sun C compiler on my old UltraSPARC box. cc -V => Sun Workshop 6 update 2 C 5.3 2001/05/15. One of its options is '-xautopar'. I'll let you guess what that does... I note that a company called Tilera claim to be shipping a 64 CPU (some flavour of MIPS, I gather) chip. From dukedave at gmail.com Thu Aug 23 01:04:54 2007 From: dukedave at gmail.com (Dave Tapley) Date: Thu Aug 23 00:56:05 2007 Subject: [Haskell-cafe] Tackling IO (the correct way) Message-ID: Hi again all, I could do with some design pointers for a project I'm working on combining Haskell with a robot. My situation is: I read sensor data from the robot lazily a line at a time, as soon as a line is read in my code sends out a response down a pipe. Implemented in this fashion: > mapM_ (updateFunction myIORef) fromRobot ::IO () > fromRobot :: String > updateFunction :: IORef -> String -> IO () Now I wish to update a HOpenGL window synchronously with this. To establish this I make a new HOpenGL window & return an IORef (IO ()) which holds the actions to draw my graphics. In this fashion: > myIORef <- makeWindow --- Above code --- > mainLoop This can be passed to updateFunction as shown above so every time it processes a new line from the robot is can update the graphics via the IORef. Because neither 'mapM_ (updateFunction myIORef) fromRobot' nor 'mainLoop' terminate I've been using 'forkIO' to split one off. This way the lazy evaluation keeps running and then window keeps updating itself. This works, sort of. I have problems because the my HOpenGL code also has magic to allow you to change the point of view using the keyboard. But when I do I get this after a while: LOCK SET! Previous intel_span.c:210 Current: intel_batchbuffer.c:63 Can anyone suggest how to resolve this "two functions which never terminate but both share IORefs" problem? Many thanks, Dave From hughperkins at gmail.com Thu Aug 23 01:16:38 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 23 01:07:47 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46CC8B0B.7020603@gmail.com> References: <46C82F23.9020509@btinternet.com> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> <20070822181337.GA4124@localhost.localdomain> <46CC8B0B.7020603@gmail.com> Message-ID: <837db430708222216x3ee0ee61w6b5ea82a5c11b6b7@mail.gmail.com> On 8/22/07, Twan van Laarhoven wrote: > But Double is already quite badly behaved: > > let x = 1e20 > > Prelude> 1 + (x - x) > > 1.0 > > Prelude> (1 + x) - x > > 0.0 Ewwww. Whilst that's understandable and unavoidable, that kindof rings alarm bells for folds of Doubles in an automatic threading situation. Ie, if we split our fold between 4 cores, we might get a different answer than if we split it between 8 cores? From stefanor at cox.net Thu Aug 23 01:18:14 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 23 01:09:30 2007 Subject: [Haskell-cafe] Tackling IO (the correct way) In-Reply-To: References: Message-ID: <20070823051814.GA5692@localhost.localdomain> On Thu, Aug 23, 2007 at 06:04:54AM +0100, Dave Tapley wrote: ... > Now I wish to update a HOpenGL window synchronously with this. > To establish this I make a new HOpenGL window & return an IORef (IO > ()) which holds the actions to draw my graphics. In this fashion: ... > Because neither 'mapM_ (updateFunction myIORef) fromRobot' nor > 'mainLoop' terminate I've been using 'forkIO' to split one off. This > way the lazy evaluation keeps running and then window keeps updating > itself. ... > This works, sort of. > I have problems because the my HOpenGL code also has magic to allow > you to change the point of view using the keyboard. But when I do I > get this after a while: > > LOCK SET! > Previous intel_span.c:210 > Current: intel_batchbuffer.c:63 > > Can anyone suggest how to resolve this "two functions which never > terminate but both share IORefs" problem? I don't know if this is your problem, but calling OpenGL from a thread created using forkIO is an extremely bad idea. forkIO does not guarantee a one-to-one mapping between Haskell threads and OS threads used for foreign calls, which horribly breaks broken APIs like OpenGL that use thread local state. Use forkOS instead for things like this. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/cb61e484/attachment.bin From hughperkins at gmail.com Thu Aug 23 01:27:43 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 23 01:18:53 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <20070822143927.GA4864@heave.ugcs.caltech.edu> References: <837db430708100631r4461b7e1g866505c8cb465f87@mail.gmail.com> <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> <46CB21C7.4070708@btinternet.com> <837db430708212007v60cf2b64m53a8a0b98e047168@mail.gmail.com> <20070822143927.GA4864@heave.ugcs.caltech.edu> Message-ID: <837db430708222227r3874ec40udf9fb283d1a6a742@mail.gmail.com> On 8/22/07, Brandon Michael Moore wrote: > Automatic threading is inherently limited by data dependencies. > You can't run a function that branches on an argument in parallel > with the computation producing that argument. Even with arbitrarily > many processors and no communication overhead there is a limit to > how much parallelism you can squeeze from any given program. Yes. Its worse than that in fact, because many real-world problems will involve functions that have side-effects, but we know the side-effects dont matter. The parallelisation algo of course doesnt know they dont matter (unless we tell it). Example: imagine we want to copy files from one machine to five others. Copying a file has a clear side-effect, but since we're copying to 5 independent machines, we can copy to each machine in parallel. The algo doesnt know that this is ok. > > You should read > "Feedback Directed Implicit Parallelism" > http://research.microsoft.com/~tharris/papers/2007-fdip.pdf > and perhaps > "Limits to Implicit Parallelism in Functional Applications" > http://www.detreville.org/papers/Limits.pdf Ok > In short, with zero overhead and an oracle for scheduling you can > get a factor of at most 2x to 32x by implicitly parallelizing > existing Haskell code. In practice, with execution overhead it's a > gain of perhaps 10% to 80% on a 4-core system. This is a good argument that it's not enough to prototype on a 4 core system, but we really need some way to simulate a 1024 core system to carry out meaningful benchmarks. > > You can do a lot better if you expect people to rewrite code, > but "automatic threading" suggests something completely effortless. Yes, I tend to overuse the word "automatic" ;-) > I think you can get much better results if you work on the programming > style in connection with a better runtime. You can think of data parallel > Haskell as a new programming style with more implicit parallelims, > and the runtime support to exploit it. Yes, you're right. > If you have cores to waste, you might try rewrites like > > f x > => > case x of > C1 a1 a2 -> f (C1 a1 a2) > C2 b -> f (C2 b) > C3 -> f C3 > > and then speculatively execute several of the case branches. > If you don't throw away too much type information you should > even be able to do it at runtime. That's a good observation. Sortof anti-laziness :-D From stefanor at cox.net Thu Aug 23 01:39:56 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 23 01:31:12 2007 Subject: [Haskell-cafe] Dynamic thread management? In-Reply-To: <837db430708222227r3874ec40udf9fb283d1a6a742@mail.gmail.com> References: <837db430708101027q5d9a49b1h4d49fe1ab0c89098@mail.gmail.com> <784a62100708101914u7df25e91i3d9d4699fed7a74e@mail.gmail.com> <837db430708102032i4ea4aae9ka18a25de5d5d8ae6@mail.gmail.com> <837db430708210006n7034a038q1bbfd4ed1fdcc146@mail.gmail.com> <4683d9370708210014p4bbd278asfae32b4a924e83c7@mail.gmail.com> <46CB21C7.4070708@btinternet.com> <837db430708212007v60cf2b64m53a8a0b98e047168@mail.gmail.com> <20070822143927.GA4864@heave.ugcs.caltech.edu> <837db430708222227r3874ec40udf9fb283d1a6a742@mail.gmail.com> Message-ID: <20070823053956.GA5807@localhost.localdomain> On Thu, Aug 23, 2007 at 06:27:43AM +0100, Hugh Perkins wrote: > On 8/22/07, Brandon Michael Moore wrote: > > Automatic threading is inherently limited by data dependencies. > > You can't run a function that branches on an argument in parallel > > with the computation producing that argument. Even with arbitrarily > > many processors and no communication overhead there is a limit to > > how much parallelism you can squeeze from any given program. > > Yes. Its worse than that in fact, because many real-world problems > will involve functions that have side-effects, but we know the > side-effects dont matter. The parallelisation algo of course doesnt > know they dont matter (unless we tell it). > > Example: imagine we want to copy files from one machine to five > others. Copying a file has a clear side-effect, but since we're > copying to 5 independent machines, we can copy to each machine in > parallel. The algo doesnt know that this is ok. Actually, the algorithm was right, and the intuitive argument is wrong. Suppose all five computers are actually re-exporting network filesystem hosted on a sixth server, and the file names alias. By overruling the algorithm, you've introduced a corner case bug that will go unnoticed for years. > > If you have cores to waste, you might try rewrites like > > > > f x > > => > > case x of > > C1 a1 a2 -> f (C1 a1 a2) > > C2 b -> f (C2 b) > > C3 -> f C3 > > > > and then speculatively execute several of the case branches. > > If you don't throw away too much type information you should > > even be able to do it at runtime. > > That's a good observation. Sortof anti-laziness :-D It's called speculative execution, and microprocessors have been doing it for many years as part of their built-in automatic parallelization circuitry. (If you think emulator-based autoparallelization is going to be easy, consider that it takes a couple million transistors to do a reasonable job - and a chunk of 90's silicon can already do a million things at once, so you're at a huge starting disadvantage. Just my two cents.) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070822/8254a297/attachment.bin From fxn at hashref.com Thu Aug 23 04:00:00 2007 From: fxn at hashref.com (Xavier Noria) Date: Thu Aug 23 03:51:18 2007 Subject: [Haskell-cafe] help understanding lazy evaluation In-Reply-To: <404396ef0708221628w56066827o9193b1f02af9b654@mail.gmail.com> References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> <404396ef0708221628w56066827o9193b1f02af9b654@mail.gmail.com> Message-ID: You people rock. Responses were really helpful and I understand how the computation goes now. I see I need to reprogram my eyes to expect lazy evaluation in places where I am used to one-shot results. I see lazy evaluation is all around in Haskell builtins. From a formal point of view how does this work? The specifications in http://www.haskell.org/onlinereport/standard-prelude.html include the lazy aspect of the definitions albeit they do not require that exact implementation, right? On the other hand, where does Haskell 98 say == is lazy on lists? -- fxn From stefanor at cox.net Thu Aug 23 04:23:52 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Thu Aug 23 04:15:10 2007 Subject: [Haskell-cafe] help understanding lazy evaluation In-Reply-To: References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> <404396ef0708221628w56066827o9193b1f02af9b654@mail.gmail.com> Message-ID: <20070823082352.GA6104@localhost.localdomain> On Thu, Aug 23, 2007 at 10:00:00AM +0200, Xavier Noria wrote: > You people rock. Responses were really helpful and I understand how the > computation goes now. > > I see I need to reprogram my eyes to expect lazy evaluation in places where > I am used to one-shot results. I see lazy evaluation is all around in > Haskell builtins. > > From a formal point of view how does this work? As is usual for mathematical things, there are many equivalent definitions. My two favorites are: 1. Normal order reduction In the ?-calculus, lazy evaluation can be defined as the (unique up to always giving the same answer) evaluation method, which, if *any* evaluation order would finish, works. This is a rather subtle theorem, not a trivial definition, so it could be hard to use. 3. Closed partial ordering Add a value ? to every type, recursively (so Bool contains ?, True, False; while [()] contains ?, [], (?:?), (():?), (?:[]), ...) The semantics for case contain a new rule: case ? of { ... } ===> ? Define a partial order ? by: ? ? x for all x (C a b c) ? (D e f g) if C = D and a ? e, b ? f, c ? g It is easily verified that this is a closed partial order with bottom element ?. It can be easily verified that all functions definable using these operations are monotonic (a ? b implies f a ? f b). Now, define: let x = y in z as: (?x. z) (fix (?x. y)) where fix :: (? -> ?) -> ? is the operation which returns a minimal fixed point of its argument, which by Kleene's Fixed-point Theorem is guaranteed to exist and be unique. In many ways this is much less obvious than even the previous one, but it happens to be very useful. Strictness analysis is trivial to understand once you grok the application of Kleene's Theorem to lazy programs. > The specifications in > > http://www.haskell.org/onlinereport/standard-prelude.html > > include the lazy aspect of the definitions albeit they do not require that > exact implementation, right? Indeed, you've caught on an important technical distinction. Lazy: Always evaluating left-outermost-first. Non-strict: Behaving as if it were lazy. Haskell's semantics are non-strict in nature, but there is no requirement for laziness. All optimizing haskell compilers are non-lazy. > On the other hand, where does Haskell 98 say == is lazy on lists? Chapter 8, Standard Prelude. The code, when intepreted using a non-strict semantics, implements a non-strict ==. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070823/fea2326c/attachment.bin From bulat.ziganshin at gmail.com Thu Aug 23 04:20:06 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 23 04:15:53 2007 Subject: [Haskell-cafe] help understanding lazy evaluation In-Reply-To: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> Message-ID: <410314487.20070823122006@gmail.com> Hello Xavier, Thursday, August 23, 2007, 3:08:25 AM, you wrote: > I am learning Haskell with "Programming in Haskell" (an excellent > book BTW). scheme of lazy evaluation called "graph reduction" you may consider it as repetitive replacing right parts of function definitions with their left parts. as far as some part of graph isn't required to compute final result, it's abandoned and not computed down to final value simple example: consider evaluation of "head [1..]". [1..] may be represented with the following recursive function: list n = n:list n+1 so we have "head (list 1)" where head defined as head (x:_) = x let's evaluate expression: head (list 1) => head (1:list 2) => 1 as you see, "list 2" was just dropped during evaluation. the same applies to your case - as far as "==" found different values in list, it skips its further evaluation, so rest of divisors remains uncalculated -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From malte at gmx-topmail.de Thu Aug 23 04:49:19 2007 From: malte at gmx-topmail.de (Malte Milatz) Date: Thu Aug 23 04:40:20 2007 Subject: [Haskell-cafe] help understanding lazy evaluation In-Reply-To: <20070823082352.GA6104@localhost.localdomain> References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> <404396ef0708221628w56066827o9193b1f02af9b654@mail.gmail.com> <20070823082352.GA6104@localhost.localdomain> Message-ID: <20070823104919.3c1461c6@aligatoro.ret> Stefan O'Rear wrote: > As is usual for mathematical things, there are many equivalent > definitions. My two favorites are: > > 1. Normal order reduction > > In the ?-calculus, lazy evaluation can be defined as the (unique up to > always giving the same answer) evaluation method, which, if *any* > evaluation order would finish, works. This is a rather subtle theorem, > not a trivial definition, so it could be hard to use. Hudak in his HSoE book gives a less precise, but more concrete definition of normal-order reduction (shamelessly quoted here): ?If a rule or rules can be applied to more than one position in an expression, use the rule corresponding to the *outermost* position in the expression.? Bulat Ziganshin wrote elsewhere: > simple example: consider evaluation of "head [1..]". With the rule above, we have: head [1..] {- We cannot apply the definition of head yet, because the first element of the list ist not visible, so we apply the definition of [..] -} = head (1 : [(succ 1)..]) {- Now we could apply either the definition of succ 1, or [..], or head. But head is the outermost, so: -} = 1. Malte From jon.fairbairn at cl.cam.ac.uk Thu Aug 23 05:33:39 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Thu Aug 23 05:25:02 2007 Subject: [Haskell-cafe] Re: help understanding lazy evaluation References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> <404396ef0708221628w56066827o9193b1f02af9b654@mail.gmail.com> <20070823082352.GA6104@localhost.localdomain> Message-ID: Stefan O'Rear writes: > Indeed, you've caught on an important technical distinction. > > Lazy: Always evaluating left-outermost-first. I think most people would rather use the term "normal order? for that; lazy means evaluating in normal order /and/ not evaluating the same expression twice. normal order: (\a -> a + a) (2+2) => (2+2) + (2+2) => 4 + (2+2) => 4 + 4 => 8 lazy: (\a -> a + a) (2+2) => (2+2) + (2+2) -- but we still know that both these (2+2)s are the same => 4 + 4 => 8 That might be slightly confusing because I've used (+), which is strict. It might have been better to use Ss and Ks, but less succinct... > Non-strict: Behaving as if it were lazy. non-strict: giving the same answers as if it were normal order. A haskell implementation could, in principle, conform to the non-strict requirement without doing any of the update in place that makes laziness. > Haskell's semantics are non-strict in nature, but there is no > requirement for laziness. All optimizing haskell compilers are > non-lazy. ???? -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From isaacdupree at charter.net Thu Aug 23 08:05:44 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Thu Aug 23 07:58:55 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <837db430708222216x3ee0ee61w6b5ea82a5c11b6b7@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <46CB2057.90303@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> <20070822181337.GA4124@localhost.localdomain> <46CC8B0B.7020603@gmail.com> <837db430708222216x3ee0ee61w6b5ea82a5c11b6b7@mail.gmail.com> Message-ID: <46CD7818.1080309@charter.net> Hugh Perkins wrote: > On 8/22/07, Twan van Laarhoven wrote: >> But Double is already quite badly behaved: >> > let x = 1e20 >> > Prelude> 1 + (x - x) >> > 1.0 >> > Prelude> (1 + x) - x >> > 0.0 > > Ewwww. Whilst that's understandable and unavoidable, that kindof > rings alarm bells for folds of Doubles in an automatic threading > situation. Ie, if we split our fold between 4 cores, we might get a > different answer than if we split it between 8 cores? Yep, Double's (+) isn't associative. I was trying to come up with ANY common mathematical property that Double fulfills and this was what I came up with: --> for all x::Float. not (x > x + 1) I'm not even sure it's true in the presence of very large numbers, optimizations and extra precision being added in the CPU. Note that it's not (x <= x + 1) because of NaN. Is Double's (+) commutative? I don't know for sure. Its (==) isn't reflexive (is it transitive? probably, at least if there aren't too many optimizations, but floating-point transitive equality isn't very useful). --> Okay... so (+), (*), (==) are probably symmetric too. Any others? Isaac From ronguida at mindspring.com Thu Aug 23 08:14:41 2007 From: ronguida at mindspring.com (Ronald Guida) Date: Thu Aug 23 08:05:47 2007 Subject: [Haskell-cafe] help understanding lazy evaluation In-Reply-To: <2f9b2d30708221739w6d20d0a6la24e061f22e6d213@mail.gmail.com> References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> <2f9b2d30708221739w6d20d0a6la24e061f22e6d213@mail.gmail.com> Message-ID: <46CD7A31.5050601@mindspring.com> I'm trying to understand lazy evaluation as well. I created an example for myself and I'm wondering if I've got it right. > let adder n = \x -> n + x in (map (adder 12) [1,2,3]) !! 1 So the first thing I did is draw a graph to represent my expression. (map (adder 12) [1,2,3]) !! 1 = | (!!) ----/ \ / 1 map / \ / \ adder (:)--(:)--(:) | | | | \ 12 1 2 3 [] In order to proceed, I need definitions for adder, map and (!!). adder n = \x -> n + x map f [] = [] map f (x:xs) = (f x) : xs (x:xs) !! 0 = x (x:xs) !! n = xs !! (n-1) Here is how I think the evaluation would proceed: 0 => (map (adder 12) [1,2,3]) !! 1 The top node is (!!). In order to evaluate (!!), I need to expand the left hand side to get at least the first node of a list. I'll expand "map". 1 => ( (adder 12 1) : (map (adder 12) [2,3]) ) !! 1 I evaluated "map" once to get a list with an expression for the head and an expression for the tail. head: adder 12 1 tail: map (adder 12) [2,3] I proceed to evaluate (!!) for one step; this time n /= 0 so I extract the tail of the list and recursively call (!!). 2 => ( (map (adder 12) [2,3]) ) !! 0 The top node is (!!) again. I need to expand "map" again. 3 => ( (adder 12 2) : (map (adder 12) [3]) ) !! 0 I evaluate (!!) and this time n == 0 so I match the base case for (!!) and take the head of the list. 4 => adder 12 2 => (adder 12) 2 In order to proceed, I need to expand (adder 12). The adder function take one argument, "12", and produces a closure. I'll express it as a "let" expressions. Note: It is at this point (steps 4 to 7) that I'm confused about what's supposed to happen with closures and let expressions. 5 => (let n = 12 in \x -> n + x) 2 I'll substitute "2" into the let statement. 6 => (let n = 12 in n + 2) I'll substitute "12" for "n". 7 => 12 + 2 8 => 14 Can anyone tell me if I've got this right? -- Ron From ndmitchell at gmail.com Thu Aug 23 08:17:11 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Thu Aug 23 08:08:20 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <46CD7818.1080309@charter.net> References: <46C82F23.9020509@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> <20070822181337.GA4124@localhost.localdomain> <46CC8B0B.7020603@gmail.com> <837db430708222216x3ee0ee61w6b5ea82a5c11b6b7@mail.gmail.com> <46CD7818.1080309@charter.net> Message-ID: <404396ef0708230517r49f7153bw71c6d73f3bbce62c@mail.gmail.com> Hi > Its (==) isn't > reflexive (is it transitive? probably, at least if there aren't too many > optimizations, but floating-point transitive equality isn't very useful). It's not even referentially transparent in all cases. a == b may fail while the double's are in the high precision registers, and then succeed later on in the program once they are truncated. I think you have to specify -fexcess-precision with GHC to get this behaviour. Thanks Neil From isaacdupree at charter.net Thu Aug 23 08:17:52 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Thu Aug 23 08:10:59 2007 Subject: [Haskell-cafe] Tackling IO (the correct way) In-Reply-To: References: Message-ID: <46CD7AF0.8030601@charter.net> Dave Tapley wrote: > Hi again all, I could do with some design pointers for a project I'm > working on combining Haskell with a robot. > > My situation is: > > I read sensor data from the robot lazily a line at a time, as soon as > a line is read in my code sends out a response down a pipe. > Implemented in this fashion: > >> mapM_ (updateFunction myIORef) fromRobot ::IO () >> fromRobot :: String >> updateFunction :: IORef -> String -> IO () > > Now I wish to update a HOpenGL window synchronously with this. > To establish this I make a new HOpenGL window & return an IORef (IO > ()) which holds the actions to draw my graphics. In this fashion: > >> myIORef <- makeWindow > --- Above code --- >> mainLoop > > This can be passed to updateFunction as shown above so every time it > processes a new line from the robot is can update the graphics via the > IORef. > > Because neither 'mapM_ (updateFunction myIORef) fromRobot' nor > 'mainLoop' terminate I've been using 'forkIO' to split one off. This > way the lazy evaluation keeps running and then window keeps updating > itself. > > This works, sort of. > I have problems because the my HOpenGL code also has magic to allow > you to change the point of view using the keyboard. But when I do I > get this after a while: > > LOCK SET! > Previous intel_span.c:210 > Current: intel_batchbuffer.c:63 > > Can anyone suggest how to resolve this "two functions which never > terminate but both share IORefs" problem? Using IORefs in two different threads probably needs MVars [1] or TVars (atomically :: STM a -> IO a) [2] instead, to do it safely, which are both similar to IORefs (choose whichever interface fits your usage better, I guess). (And using forkOS like Stefan says) [1] [2] no documentation where it should be: but some documentation here: Isaac From lemming at henning-thielemann.de Thu Aug 23 08:32:51 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Thu Aug 23 08:24:06 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <404396ef0708230517r49f7153bw71c6d73f3bbce62c@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <46CB4E5B.1080201@charter.net> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> <20070822181337.GA4124@localhost.localdomain> <46CC8B0B.7020603@gmail.com> <837db430708222216x3ee0ee61w6b5ea82a5c11b6b7@mail.gmail.com> <46CD7818.1080309@charter.net> <404396ef0708230517r49f7153bw71c6d73f3bbce62c@mail.gmail.com> Message-ID: On Thu, 23 Aug 2007, Neil Mitchell wrote: > Hi > >> Its (==) isn't >> reflexive (is it transitive? probably, at least if there aren't too many >> optimizations, but floating-point transitive equality isn't very useful). > > It's not even referentially transparent in all cases. a == b may fail > while the double's are in the high precision registers, and then > succeed later on in the program once they are truncated. I think you > have to specify -fexcess-precision with GHC to get this behaviour. That's really bad. This will invalidate the clever algorithms for computing (+) and (*) with doubled precision (EFT - error free transformations). http://66.102.9.104/search?q=cache:8vni-CqtINkJ:www.ti3.tu-harburg.de/paper/rump/Ru05c.pdf+TwoSum&hl=de&ct=clnk&cd=1&gl=de From hthiel.char at zonnet.nl Thu Aug 23 09:02:39 2007 From: hthiel.char at zonnet.nl (Hans van Thiel) Date: Thu Aug 23 08:52:51 2007 Subject: [Haskell-cafe] Ann: Gtk2Hs Tutorial Port Message-ID: <1187874159.3266.57.camel@localhost.localdomain> Hello All, I've already announced this on the Gtk2Hs users' list, but for those who are not using Gtk2Hs at the moment, but who might be interested: I've started a port of the Gtk+2.0 tutorial by Tony Gail and Ian Main and the first part is available on: http://darcs.haskell.org/gtk2hs/docs/tutorial/Tutorial_Port/ The chapters are: Contents and Copyright Notice chap1.html Getting Started chap3.html Packing Widgets chap4.html Packing Demonstration Program chap5a.html Packing Using Tables chap5b.html The Button Widget chap6.html Adjustments, Scale and Range chap7.html All examples are also available as .hs files. For a beginner, working through these should be sufficient, so that he/she can carry on with the original C based tutorial. The correlation between the examples and the Gtk2Hs API is (mostly) straightforward. But I'm working on the other widgets in the Gtk+2.0 tutorial too (might take a while). Currently available on my own web site (but no .hs files): Labels chap8.html Arrows and Tooltips chap9.html http://j-van-thiel.speedlinq.nl/gtk2hs/chap8.html http://j-van-thiel.speedlinq.nl/gtk2hs/chap9.html New additions will be listed in chap1.html As said, probably the second part of the port is not really needed, as the Gtk2Hs API documentation maps (mostly) very clearly onto the C functions. Note 1: I'm not a Gtk2Hs expert, but I'm journaling my own learning experience. The code works, but feel free to comment. Someone has kindly promised to review this version, so it will certainly be improved later on. Note 2: the Gtk+2.0 tutorial has not been updated since 2002 (if the copyright notice is to be trusted) and does not cover everything. The same applies to the port. Moreover, advanced widgets like Tree List are large and complicated and will not be treated at all. Note 3: This tutorial, and in particular the 'Getting Started' chapter, replaces the old 'Getting Started' page, which has been removed. Many Thanks, Hans van Thiel From bulat.ziganshin at gmail.com Thu Aug 23 08:48:42 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 23 09:10:26 2007 Subject: [Haskell-cafe] Tackling IO (the correct way) In-Reply-To: <46CD7AF0.8030601@charter.net> References: <46CD7AF0.8030601@charter.net> Message-ID: <173967352.20070823164842@gmail.com> Hello Isaac, Thursday, August 23, 2007, 4:17:52 PM, you wrote: > Using IORefs in two different threads probably needs MVars [1] or TVars > no documentation where it should be: the best documentation still is "Tackling the awkward squad: monadic input/output, concurrency, exceptions, and foreign-language calls in Haskell" http://research.microsoft.com/Users/simonpj/papers/marktoberdorf/marktoberdorf.ps.gz -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From apfelmus at quantentunnel.de Thu Aug 23 13:54:00 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Thu Aug 23 13:45:26 2007 Subject: [Haskell-cafe] Re: help understanding lazy evaluation In-Reply-To: <46CD7A31.5050601@mindspring.com> References: <8FC344FB-9455-4FB3-A4DC-FB3914AEBBB3@hashref.com> <2f9b2d30708221739w6d20d0a6la24e061f22e6d213@mail.gmail.com> <46CD7A31.5050601@mindspring.com> Message-ID: Ronald Guida wrote: > Can anyone tell me if I've got this right? Yes, you got. The let-statement you introduce that embodies the sharing of the argument n = 12 probably should be present in the first parts, too. But this doesn't really matter, the formalities of graph reduction vary with the formalizer :) Regards, apfelmus From apfelmus at quantentunnel.de Thu Aug 23 14:00:24 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Thu Aug 23 13:51:43 2007 Subject: [Haskell-cafe] Re: Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <404396ef0708211223y4bcf7984u6650762b1f06731b@mail.gmail.com> References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> <20070820191526.GD3098@localhost.localdomain> <404396ef0708211223y4bcf7984u6650762b1f06731b@mail.gmail.com> Message-ID: Neil Mitchell wrote: >>> sum (enum 1 10) => >>> sum' 0 (enum 1 10) => >>> ... >>> >>> sum' 36 (9 : enum (9+1) 10) => >>> (sum' $! (36+9)) (enum (9+1) 10) => >>> sum' 45 (enum (9+1) 10) => >>> sum' 45 [] => >>> 45 >>> >>> (I need to find some way to automate making these trails :) ) >> Yes! We'd need such an automatic tool for the wikibook, too. > > The problem is that Haskell is ridiculously complex, and the "small > step" interpretation is much harder than you'd think. For example, sum > may well be defined as foldl' (+) 0, which is a CAF, so gets reduced > once. The 0 won't actually be a 0, but will be fromInteger 0, which > will correspond to looking up an item in the dictionary and applying > it. Dictionaries especially make the "simple" interpretation > completely wrong. > > It's easy to do informally, but once you start being more precise, its > very complex. Yeah, the precise details may vary, even :) But for teaching, an automatic tool that does graph reduction would be great. I don't mind if it's sloppy (directly apply definitions & pattern matching VS everything is a lambda abstraction) and only does simply typed lambda calculus (no type applications, no type classes). Regards, apfelmus From andrewcoppin at btinternet.com Thu Aug 23 14:43:52 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 23 14:34:04 2007 Subject: [Haskell-cafe] Re: Graph reduction [Was: Where is StackOverflow on the Wiki?] In-Reply-To: References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> <20070820191526.GD3098@localhost.localdomain> <404396ef0708211223y4bcf7984u6650762b1f06731b@mail.gmail.com> Message-ID: <46CDD568.4080007@btinternet.com> apfelmus wrote: > Yeah, the precise details may vary, even :) But for teaching, an > automatic tool that does graph reduction would be great. I don't mind > if it's sloppy (directly apply definitions & pattern matching VS > everything is a lambda abstraction) and only does simply typed lambda > calculus (no type applications, no type classes). Well come ON people, there's *got* to be enough big-wigs on this list to put *something* together! ;-) Like I said, a while back I wrote something in Tcl that would produce a reduction sequence for the standard example code for quicksort or the Fibonacci numbers. All very simplistic. (I wrote it in *Tcl*! It doesn't even have *types*!!) No type checking. Use any constructor names you want. Typeclasses could *never* have worked. Also, I later learned about a whole bunch of Haskell features that would have required a massive refactor to implement. (*cough* curried functions, case-expressions, let-expressions, lambda functions...) Anyway, I'll see if I can't put something skeletal together sometime. It will probably only work 50% of the time, but maybe that will be useful to somebody... From ndmitchell at gmail.com Thu Aug 23 15:05:48 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Thu Aug 23 14:56:57 2007 Subject: [Haskell-cafe] Re: Graph reduction [Was: Where is StackOverflow on the Wiki?] In-Reply-To: <46CDD568.4080007@btinternet.com> References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> <20070820191526.GD3098@localhost.localdomain> <404396ef0708211223y4bcf7984u6650762b1f06731b@mail.gmail.com> <46CDD568.4080007@btinternet.com> Message-ID: <404396ef0708231205n6addceefl9feb8f3e3223752a@mail.gmail.com> Hi > > Yeah, the precise details may vary, even :) But for teaching, an > > automatic tool that does graph reduction would be great. I don't mind > > if it's sloppy (directly apply definitions & pattern matching VS > > everything is a lambda abstraction) and only does simply typed lambda > > calculus (no type applications, no type classes). > > Well come ON people, there's *got* to be enough big-wigs on this list to > put *something* together! ;-) It's been done, but never got to a released state: http://haskell.org/haskellwiki/Haskell_Equational_Reasoning_Assistant http://www.cs.york.ac.uk/fp/darcs/proof/ (screenshot: http://www-users.cs.york.ac.uk/~ndm/temp/proof.png) And neither of them will be of much use to a beginner. Haskell is too complex to reason about formally for a beginner, and reasoning "informally" isn't very easy to do - because its not a precise description of what to do. Thanks Neil From bf3 at telenet.be Thu Aug 23 15:26:56 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Thu Aug 23 15:18:04 2007 Subject: [Haskell-cafe] Re: Newbie question: Where is StackOverflow on the Wiki? Message-ID: I think DrScheme does that for Scheme. So a must have for Haskell! Maybe could be added to the Helium project? >----- Oorspronkelijk bericht ----- >Van: apfelmus [mailto:apfelmus@quantentunnel.de] >Verzonden: donderdag, augustus 23, 2007 08:00 PM >Aan: haskell-cafe@haskell.org >Onderwerp: [Haskell-cafe] Re: Newbie question: Where is StackOverflow on the Wiki? > >Neil Mitchell wrote: >>>> sum (enum 1 10) => >>>> sum' 0 (enum 1 10) => >>>> ... >>>> >>>> sum' 36 (9 : enum (9+1) 10) => >>>> (sum' $! (36+9)) (enum (9+1) 10) => >>>> sum' 45 (enum (9+1) 10) => >>>> sum' 45 [] => >>>> 45 >>>> >>>> (I need to find some way to automate making these trails :) ) >>> Yes! We'd need such an automatic tool for the wikibook, too. >> >> The problem is that Haskell is ridiculously complex, and the "small >> step" interpretation is much harder than you'd think. For example, sum >> may well be defined as foldl' (+) 0, which is a CAF, so gets reduced >> once. The 0 won't actually be a 0, but will be fromInteger 0, which >> will correspond to looking up an item in the dictionary and applying >> it. Dictionaries especially make the "simple" interpretation >> completely wrong. >> >> It's easy to do informally, but once you start being more precise, its >> very complex. > >Yeah, the precise details may vary, even :) But for teaching, an >automatic tool that does graph reduction would be great. I don't mind if >it's sloppy (directly apply definitions & pattern matching VS everything >is a lambda abstraction) and only does simply typed lambda calculus (no >type applications, no type classes). > >Regards, >apfelmus > >_______________________________________________ >Haskell-Cafe mailing list >Haskell-Cafe@haskell.org >http://www.haskell.org/mailman/listinfo/haskell-cafe > > From bf3 at telenet.be Thu Aug 23 15:35:43 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Thu Aug 23 15:26:51 2007 Subject: [Haskell-cafe] Bug in Gtk2HS 0.9.12/SOE on WinXP? Or is it just me? Message-ID: First of all, I'm really excited that GTK2HS 0.9.12 now allows launching SOE apps using GHCI. However, in the code below the blue and green triangle should render on top of each other, but the green triangle is rendered incorrectly. Being a newbie, I hesitate to file a bug report... Can anyone reproduce this? Maybe it works fine on unix? Thanks, Peter module Main where import Graphics.SOE.Gtk shape = [(200,100), (200,200), (100,200), (200,100)] main = runGraphics $ do w <- openWindow "Buggy polgon fill?" (300,300) setGraphic w $ (withColor Red $ polyline shape) `overGraphic` (withColor Green $ drawRegion $ createPolygon shape) drawInWindow w $ (withColor Red $ polyline shape) `overGraphic` (withColor Blue $ polygon shape) waitForClose w closeWindow w waitForClose w = do e <- getWindowEvent w case e of Closed -> return () otherwise -> waitForClose w From v.dijk.bas at gmail.com Thu Aug 23 17:31:40 2007 From: v.dijk.bas at gmail.com (Bas van Dijk) Date: Thu Aug 23 17:22:49 2007 Subject: [Haskell-cafe] Newbie question: Where is StackOverflow on the Wiki? In-Reply-To: <20070820191526.GD3098@localhost.localdomain> References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> <20070820191526.GD3098@localhost.localdomain> Message-ID: On 8/20/07, Stefan O'Rear wrote: > ... > (I need to find some way to automate making these trails :) ) > ... I think you can come a long way with the debugger in GHC HEAD. It provides a :trace command that, when applied to an expression with some breakpoint in it, remembers the history of evaluation steps. You can view the history with :hist. See: http://www.haskell.org/ghc/dist/current/docs/users_guide/ghci-debugger.html#tracing regards, Bas From alangley at gmail.com Thu Aug 23 18:20:53 2007 From: alangley at gmail.com (Adam Langley) Date: Thu Aug 23 18:12:08 2007 Subject: [Haskell-cafe] GHC optimisations In-Reply-To: <404396ef0708230517r49f7153bw71c6d73f3bbce62c@mail.gmail.com> References: <46C82F23.9020509@btinternet.com> <46CB9BDA.4090408@gmail.com> <404396ef0708220143vf3c3710j451bba580620b36f@mail.gmail.com> <46CC7280.7060408@vex.net> <404396ef0708221036i613d24cbj7d6631f43ebd9408@mail.gmail.com> <20070822181337.GA4124@localhost.localdomain> <46CC8B0B.7020603@gmail.com> <837db430708222216x3ee0ee61w6b5ea82a5c11b6b7@mail.gmail.com> <46CD7818.1080309@charter.net> <404396ef0708230517r49f7153bw71c6d73f3bbce62c@mail.gmail.com> Message-ID: <396556a20708231520y3f2f0e92g20a92edb6be49232@mail.gmail.com> On 8/23/07, Neil Mitchell wrote: > It's not even referentially transparent in all cases. a == b may fail > while the double's are in the high precision registers, and then > succeed later on in the program once they are truncated. I think you > have to specify -fexcess-precision with GHC to get this behaviour. Also, if you tell GCC to use SSE (there are a number of flags, like -march and -msse, -msse2 etc which can do this). It can stop using the 80-bit x87 registers for floating point and switch to 64-bit SSE registers. Then you *don't* get this affect, but I'm not sure you can be sure that you don't ever get it. Floating point numbers make me sad :( AGL -- Adam Langley agl@imperialviolet.org http://www.imperialviolet.org 650-283-9641 From brock.peabody at gmail.com Thu Aug 23 19:12:56 2007 From: brock.peabody at gmail.com (Brock Peabody) Date: Thu Aug 23 19:04:04 2007 Subject: [Haskell-cafe] newbie - how to call a Haskell interpreter from C Message-ID: Hi, I've been trying to find place to use Haskell at work, and I think a good opportunity will be to use it for our scripting language. To do that, I need to be able to invoke an interpreter directly from another language. I've investigated using HaskellScript (too web/ActiveX centric), but really I just want to compile ghci or hugs into my executable/library. It seems like this is something I should be able to figure out easily, but so far I've failed and have not found any reference to others succeeding. any advice? thanks in advance, Brock -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070823/d23d1d3c/attachment.htm From bradypus at xs4all.nl Fri Aug 24 03:18:24 2007 From: bradypus at xs4all.nl (Arie Groeneveld) Date: Fri Aug 24 03:07:02 2007 Subject: [Haskell-cafe] Style Message-ID: <46CE8640.8040508@xs4all.nl> Hi, I defined several functions for calculating the number of trailing zero's of n! tm = sum . takeWhile(>0) . iterate f . f where f = flip div 5 tm1 n = sum . takeWhile(>0) . map (div n . (5^)) $ [1..] tm2 n = sum . takeWhile(>0) . map (div n) $ iterate ((*)5) 5 tm3 = sum . takeWhile(>0) . flip map (iterate ((*)5) 5) . div Questions: Which one is the most elegant one generally speaking? Which one is most natural in Haskell? Is there more 'beauty' to possible? My personal choice is 'tm'. I like 'tm3' (a revised version of tm2) in terms of pointlessness and not having a 'where', but I think it's a bit contrived because of the 'flip'. Comments? Thanks @@i From bringert at cs.chalmers.se Fri Aug 24 03:38:15 2007 From: bringert at cs.chalmers.se (Bjorn Bringert) Date: Fri Aug 24 03:28:21 2007 Subject: [Haskell-cafe] Help using CGIT In-Reply-To: <14cf844b0708221834na33ffekb237b253d1b04ab1@mail.gmail.com> References: <14cf844b0708221126l37c1654bhd8b120e78855377c@mail.gmail.com> <20070822212828.GA26256@matrix.chaos.earth.li> <14cf844b0708221834na33ffekb237b253d1b04ab1@mail.gmail.com> Message-ID: On Aug 23, 2007, at 3:34 , Rich Neswold wrote: > On 8/22/07, Ian Lynagh wrote: > On Wed, Aug 22, 2007 at 01:27:00PM -0500, Rich Neswold wrote: > > > > > newtype App a = App (ReaderT Connection (CGIT IO) a) > > > deriving (Monad, MonadIO, MonadReader Connection) > > > > Unfortunately, when another module tries to actually use the > monad, I > > get warnings about "No instance for (MonadCGI App)". I tried > making an > > instance: > > > > > instance MonadCGI App where > > > cgiAddHeader = ? > > > cgiGet = ? > > You have three choices: > > 1: > > 2: > > 3: > Provide a single instance for App that does the whole thing: > instance MonadCGI App where > cgiAddHeader n v = App $ lift $ cgiAddHeader n v > cgiGet x = App $ lift $ cgiGet x > This one you would obviously have to change if you added a StateT. > > Bingo! Method #3 works beautifully! I missed the using-lift-with- > the-constructor permutation. > > Thanks for your help! I started writing a tutorial for Haskell web programming with the cgi package a while back, but haven't worked on it for a while, see http://www.haskell.org/haskellwiki/Practical_web_programming_in_Haskell I haven't added it to the list of tutorials yet, since it's still rather incomplete. The section on using CGIT is just a stub, perhaps you would like to contribute to it? See http://www.haskell.org/haskellwiki/ Practical_web_programming_in_Haskell#Extending_the_CGI_monad_with_monad_ transformers /Bj?rn From bringert at cs.chalmers.se Fri Aug 24 03:45:44 2007 From: bringert at cs.chalmers.se (Bjorn Bringert) Date: Fri Aug 24 03:35:49 2007 Subject: [Haskell-cafe] Style In-Reply-To: <46CE8640.8040508@xs4all.nl> References: <46CE8640.8040508@xs4all.nl> Message-ID: On Aug 24, 2007, at 9:18 , Arie Groeneveld wrote: > Hi, > > I defined several functions for calculating the number > of trailing zero's of n! > > > tm = sum . takeWhile(>0) . iterate f . f > where f = flip div 5 > > tm1 n = sum . takeWhile(>0) . map (div n . (5^)) $ [1..] > tm2 n = sum . takeWhile(>0) . map (div n) $ iterate ((*)5) 5 > tm3 = sum . takeWhile(>0) . flip map (iterate ((*)5) 5) . div > > > > Questions: > > Which one is the most elegant one generally speaking? > Which one is most natural in Haskell? > Is there more 'beauty' to possible? > > > My personal choice is 'tm'. > I like 'tm3' (a revised version of tm2) in terms of > pointlessness and not having a 'where', but I think > it's a bit contrived because of the 'flip'. > > Comments? Here's a much more inefficient version, but it has the merit of being very easy to understand: tm_silly n = length $ takeWhile (=='0') $ reverse $ show $ product [1..n] /Bj?rn From luc.taesch at googlemail.com Fri Aug 24 03:45:33 2007 From: luc.taesch at googlemail.com (Luc TAESCH) Date: Fri Aug 24 03:36:40 2007 Subject: [Haskell-cafe] latest cabal conflict? Message-ID: <1be091cf0708240045v298597f1hd29c39afe49c4fae@mail.gmail.com> when trying to build the latest cabal from darcs, I got luc@haserv:~/src/cabinstall/cabal$ runghc Setup.lhs configure Distribution/Simple.hs:110:7: Could not find module `System.FilePath': it was found in multiple packages: filepath-1.0 FilePath-0.11 luc@haserv:~/src/cabinstall/cabal$ sound like a conflict , i still have ghc 6.6, not 6.6.1. what should I do ? hide FilePath-0.11 in Distribution/Simple.hs imports ? ( and for all othe files? any way to just have FilePath out of the way via a Cabal statement? thks From bradypus at xs4all.nl Fri Aug 24 04:08:49 2007 From: bradypus at xs4all.nl (Arie Groeneveld) Date: Fri Aug 24 03:57:21 2007 Subject: [Haskell-cafe] Style In-Reply-To: References: <46CE8640.8040508@xs4all.nl> Message-ID: <46CE9211.9020602@xs4all.nl> Bjorn Bringert wrote: > > > > Here's a much more inefficient version, but it has the merit of being > > very easy to understand: > > > > tm_silly n = length $ takeWhile (=='0') $ reverse $ show $ product [1..n] > > > You're rigth. I came up with that one too the first time. But for large value's of n it takes too much time. You may improve that (time) by using another product formula: *Main> length $ takeWhile (=='0') $ reverse $ show $ foldl' (*) 1 [1..30000] 7498 (0.96 secs, 790685000 bytes) *Main> length $ takeWhile (=='0') $ reverse $ show $ product [1..30000] 7498 (4.05 secs, 792259140 bytes) But: *Main> tm 30000 7498 (0.00 secs, 524924 bytes) Thanks @@i From lemming at henning-thielemann.de Fri Aug 24 04:40:05 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Fri Aug 24 04:31:40 2007 Subject: [Haskell-cafe] Style In-Reply-To: <46CE8640.8040508@xs4all.nl> References: <46CE8640.8040508@xs4all.nl> Message-ID: On Fri, 24 Aug 2007, Arie Groeneveld wrote: > I defined several functions for calculating the number > of trailing zero's of n! > > > tm = sum . takeWhile(>0) . iterate f . f > where f = flip div 5 This is very elegant! You could also inline 'f' tm4 = sum . takeWhile(>0) . tail . iterate (flip div 5) From simonmarhaskell at gmail.com Fri Aug 24 04:40:38 2007 From: simonmarhaskell at gmail.com (Simon Marlow) Date: Fri Aug 24 04:31:49 2007 Subject: [Haskell-cafe] Re: Haddock: documenting parameters of functional arguments In-Reply-To: References: Message-ID: <46CE9986.1030706@microsoft.com> Henning Thielemann wrote: > I like to write documentation comments like > > fix :: > ( a {- ^ local argument -} > -> a {- ^ local output -} ) > -> a {- ^ global output -} > > but Haddock doesn't allow it. Or is there a trick to get it work? Haddock only supports documenting the "top-level" arguments of a function right now. Cheers, Simon From rahn at ira.uka.de Fri Aug 24 05:04:09 2007 From: rahn at ira.uka.de (Mirko Rahn) Date: Fri Aug 24 04:55:25 2007 Subject: [Haskell-cafe] Style In-Reply-To: <46CE8640.8040508@xs4all.nl> References: <46CE8640.8040508@xs4all.nl> Message-ID: <46CE9F09.708@ira.uka.de> > tm = sum . takeWhile(>0) . iterate f . f > where f = flip div 5 Quite nice. I like tm5 0 = 0 tm5 n = let q = div n 5 in q + tm5 q This version corresponds to what I'm think when parsing |tm|, so I wrote it down directly. Also possible tm6 = sum . unfoldr ( \ n -> case div n 5 of 0 -> mzero q -> return (q,q) ) I tend to not use |iterate|, when it is known in advance, which prefix of the so constructed infinite list is used. /BR -- -- Mirko Rahn -- Tel +49-721 608 7504 -- --- http://liinwww.ira.uka.de/~rahn/ --- From simonpj at microsoft.com Fri Aug 24 05:08:51 2007 From: simonpj at microsoft.com (Simon Peyton-Jones) Date: Fri Aug 24 04:59:59 2007 Subject: [Haskell-cafe] Re: Remember the future In-Reply-To: References: <46C5F84F.8020404@btinternet.com> <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> <625b74080708171543g3945b0cag3bf62ae610e8b016@mail.gmail.com> <46C6B6E4.2060704@btinternet.com> Message-ID: | >From the ghc manual: | | ----------- | 7.3.3. The recursive do-notation | ... | | It is unfortunate that the manual does not give the translation rules, or at | least the translation for the given example. Hmm. OK. I've improved the manual with a URL to the main paper http://citeseer.ist.psu.edu/erk02recursive.html which is highly readable. And I've given the translation for the example as you suggest Simon From coeus at gmx.de Fri Aug 24 05:14:07 2007 From: coeus at gmx.de (Marc A. Ziegert) Date: Fri Aug 24 05:05:23 2007 Subject: [Haskell-cafe] Style In-Reply-To: <46CE9211.9020602@xs4all.nl> References: <46CE8640.8040508@xs4all.nl> <46CE9211.9020602@xs4all.nl> Message-ID: <200708241114.12518.coeus@gmx.de> "Marc A. Ziegert" > tm_parallelizable_v1 = \n -> sum . takeWhile (>0) $ map (div n) fives > where fives = iterate (*5) 1 > tm_improved_v1 n = sum . takeWhile (>0) $ iterate (div `flip` 5) (div n 5) > tm_fastestIMHO n = let m=div n 5 in if m<5 then m else m+tm_fastestIMHO m Henning Thielemann > tm4 = sum . takeWhile(>0) . tail . iterate (flip div 5) Bjorn Bringert > tm_silly n = length $ takeWhile (=='0') $ reverse $ show $ product [1..n] Arie Groeneveld > tm = sum . takeWhile(>0) . iterate f . f > where f = flip div 5 > tm1 n = sum . takeWhile(>0) . map (div n . (5^)) $ [1..] > tm2 n = sum . takeWhile(>0) . map (div n) $ iterate ((*)5) 5 > tm3 = sum . takeWhile(>0) . flip map (iterate ((*)5) 5) . div -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070824/39229c6e/attachment.bin From duncan.coutts at worc.ox.ac.uk Fri Aug 24 05:40:42 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Fri Aug 24 05:30:31 2007 Subject: [Haskell-cafe] latest cabal conflict? In-Reply-To: <1be091cf0708240045v298597f1hd29c39afe49c4fae@mail.gmail.com> References: <1be091cf0708240045v298597f1hd29c39afe49c4fae@mail.gmail.com> Message-ID: <1187948442.13368.2.camel@localhost> On Fri, 2007-08-24 at 09:45 +0200, Luc TAESCH wrote: > when trying to build the latest cabal from darcs, > I got > luc@haserv:~/src/cabinstall/cabal$ runghc Setup.lhs configure > > Distribution/Simple.hs:110:7: > Could not find module `System.FilePath': > it was found in multiple packages: filepath-1.0 FilePath-0.11 > luc@haserv:~/src/cabinstall/cabal$ > > sound like a conflict , i still have ghc 6.6, not 6.6.1. Hide or unregister the old FilePath-0.11. filepath-1.0 is the latest version. Duncan From girodt at gmail.com Fri Aug 24 05:48:13 2007 From: girodt at gmail.com (Thomas Girod) Date: Fri Aug 24 05:39:21 2007 Subject: [Haskell-cafe] newbie : multi-parameter type classes Message-ID: Hi there. I'm trying to define a generic graph type here and don't understand on one error I get. Here I come. module Graph where class (Eq n, Eq e) => Topo a n e where empty :: a nodes :: a -> [n] edges :: a -> [e] data Node n = Node n deriving (Eq,Show) data Edge n e = Edge e (Node n) (Node n) deriving (Show) instance (Eq e) => Eq (Edge n e) where (Edge e1 _ _) == (Edge e2 _ _) = e1 == e2 data Graph n e = Graph [Node n] [Edge n e] deriving (Eq,Show) instance (Eq n, Eq e) => Topo (Graph n e) (Node n) (Edge n e) where empty = Graph [] [] nodes (Graph ns _) = ns edges (Graph _ es) = es My class Topo (for topography) is supposed to give the basic interface any graph should have. My instance is Topo (Graph n e) (Node n) (Edge n e), so the infered types of the functions should be : empty :: Graph n e nodes :: Graph n e -> [Nodes n] edges :: Graph n e -> [Edge n e] right ? When I load the code in GHCi, no errors. But then : *Graph> let g = Graph [Node 0, Node 1] [] *Graph> nodes g :1:0: No instance for (Topo (Graph Integer e1) n e) arising from use of `nodes' at :1:0-6 Possible fix: add an instance declaration for (Topo (Graph Integer e1) n e) In the expression: nodes g In the definition of `it': it = nodes g *Graph> And I don't understand this. How can he search for an instance of Topo (Graph integer e1) n e) ? regards, Thomas -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070824/5a694b66/attachment-0001.htm From malte at gmx-topmail.de Fri Aug 24 05:58:17 2007 From: malte at gmx-topmail.de (Malte Milatz) Date: Fri Aug 24 05:49:31 2007 Subject: [Haskell-cafe] Bug in Gtk2HS 0.9.12/SOE on WinXP? Or is it just me? In-Reply-To: References: Message-ID: <20070824115817.247543da@aligatoro.ret> Peter Verswyvelen : > However, in the code below the blue and green triangle should render on top of each other, but the green triangle is rendered incorrectly. > > Being a newbie, I hesitate to file a bug report... Can anyone reproduce this? Maybe it works fine on unix? I can reproduce this with 0.9.12. $ uname -srmo Linux 2.6.20-16-generic i686 GNU/Linux I'm quoting your program below because I'll Cc this to the gtk2hs-users list. > module Main where > > import Graphics.SOE.Gtk > > shape = [(200,100), (200,200), (100,200), (200,100)] > > main = runGraphics $ do > w <- openWindow "Buggy polgon fill?" (300,300) > setGraphic w $ (withColor Red $ polyline shape) `overGraphic` (withColor Green $ drawRegion $ createPolygon shape) > drawInWindow w $ (withColor Red $ polyline shape) `overGraphic` (withColor Blue $ polygon shape) > waitForClose w > closeWindow w > > waitForClose w = do > e <- getWindowEvent w > case e of > Closed -> return () > otherwise -> waitForClose w From ndmitchell at gmail.com Fri Aug 24 06:17:29 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Fri Aug 24 06:08:38 2007 Subject: [Haskell-cafe] Re: [Haskell] Issue about use of WinHugs In-Reply-To: <9BEAE1973EF50D4AAF3A413C1028737E98ED47@AUSYMS12.ca.com> References: <9BEAE1973EF50D4AAF3A413C1028737E98ED47@AUSYMS12.ca.com> Message-ID: <404396ef0708240317o4ab86a2es7f4b3581a9623d4b@mail.gmail.com> Hi > I'm new to WinHugs, what's wrong with isUpper of my WinHugs? Nothing. The book/tutorial you are going from is out of date. Before using the isUpper/isLower functions you first have to type ":load Char": Hugs> :load Char Hugs> filter isUpper "ABCDEfgh" "ABCDE" The ":load Char" loads the Char module into scope, which provides the isUpper function. The haskell@ mailing list is mainly for announcements, so I've sent this email to haskell-cafe@ - which is the right place for questions like this. Thanks Neil From lemming at henning-thielemann.de Fri Aug 24 06:26:26 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Fri Aug 24 06:17:34 2007 Subject: [Haskell-cafe] Style In-Reply-To: <46CE9F09.708@ira.uka.de> References: <46CE8640.8040508@xs4all.nl> <46CE9F09.708@ira.uka.de> Message-ID: On Fri, 24 Aug 2007, Mirko Rahn wrote: >> tm = sum . takeWhile(>0) . iterate f . f >> where f = flip div 5 > > Quite nice. I like > > tm5 0 = 0 > tm5 n = let q = div n 5 in q + tm5 q > > This version corresponds to what I'm think when parsing |tm|, so I wrote it > down directly. Since the original poster used the message title "style", I want to mention that his solution is good style, because it keeps logical steps separated, and thus lets you inspect meaningful interim results. (iterate f . f) computes the number of natural numbers up to n with factors 5, 5^2, 5^3 and so on. Then you like to sum these up (sum), but before this, you must limit the list to a reasonable finite prefix (takeWhile (>0)). Of course, using 'show' and counting the zeros is more intuitive. It is not efficient, but it will serve as a nice test of 'tm's correctness. From bf3 at telenet.be Fri Aug 24 06:31:42 2007 From: bf3 at telenet.be (peterv) Date: Fri Aug 24 06:23:03 2007 Subject: [Haskell-cafe] 2D game graphics library for Haskell? Message-ID: <000b01c7e639$f8469c90$e8d3d5b0$@be> I’m currently playing around with SOE to make some simple interactive math exercises for students. This worked fine, although I could have done this much faster using C# (which I know very well), but since I’m addicted to Haskell now, I used the latter language ;) Furthermore, I hope that one day, I will know enough Haskell to learn it to the students, because I feel that functional programming should not be given in the last bachelor or master years, since most software engineering students then know OO programming extremely well and have a horrible time with FP (I currently did not meet anyone in my sector of game development that liked FP, and many of those people had a masters degree and some were PhDs) Anyway, SOE is great for learning Haskell, but it lacks a couple of fundamental functions to make it really attractive, like: - Support for images - Support for rendering to an “offscreen graphics surface” and reading the pixels from that surface (for pixel-wise collision detection) - Support for detecting non-ASCII key presses (cursor keys, etc) - Support for joysticks Concurrent Clean seems to have a nice 2D game library and PLT/DrScheme also has nice support for basic 2D graphics, but somehow I feel Haskell is more mature and more elegant. So before digging into “advanced” APIs (like GTK itself, which I know nothing about, I’m a Win32 GDI/XNA/WPF expert), I should ask the question if something similar exists? It has to be as simple as SOE. Would it be possible to extend the GTK SOE with support for the features mentioned above? Is this insanely difficult for someone like me who knows a lot about Win32 but little Haskell? Thanks, Peter Verswyvelen No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.484 / Virus Database: 269.12.4/969 - Release Date: 23/08/2007 16:04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070824/1716fef0/attachment.htm From bradypus at xs4all.nl Fri Aug 24 08:19:32 2007 From: bradypus at xs4all.nl (Arie Groeneveld) Date: Fri Aug 24 08:08:02 2007 Subject: [Haskell-cafe] Style In-Reply-To: <46CE8640.8040508@xs4all.nl> References: <46CE8640.8040508@xs4all.nl> Message-ID: <46CECCD4.4090405@xs4all.nl> Thanks for all the instructive replies and alternatives! Learned a bit more in terms of feeling about style and improvement of some of the functions: f.e. 'killing' the 'where' in my number one choice. Thanks @@i From Christian.Maeder at dfki.de Fri Aug 24 08:33:06 2007 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Fri Aug 24 08:24:15 2007 Subject: [Haskell-cafe] Re: newbie : multi-parameter type classes In-Reply-To: References: Message-ID: <46CED002.2000009@dfki.de> Thomas Girod wrote: > Hi there. > > I'm trying to define a generic graph type here and don't understand on > one error I get. Here I come. > > module Graph > where > > class (Eq n, Eq e) => Topo a n e where > empty :: a > nodes :: a -> [n] > edges :: a -> [e] This does not work without functional dependencies. Try: class (Eq n, Eq e) => Topo a n e | a -> n e where HTH Christian P.S. Integer comes in via defaulting (of 0 or 1) From Christian.Maeder at dfki.de Fri Aug 24 08:47:47 2007 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Fri Aug 24 08:39:00 2007 Subject: [Haskell-cafe] Re: newbie : multi-parameter type classes In-Reply-To: References: Message-ID: <46CED373.7000109@dfki.de> Thomas Girod wrote: > class (Eq n, Eq e) => Topo a n e where > empty :: a empty does not allow to infer the types n and e > nodes :: a -> [n] also nodes leaves the type e undetermined http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#functional-dependencies Unfortunately http://www.cse.ogi.edu/~mpj/pubs/fundeps.html is broken. Christian From bradypus at xs4all.nl Fri Aug 24 08:58:36 2007 From: bradypus at xs4all.nl (Arie Groeneveld) Date: Fri Aug 24 08:47:06 2007 Subject: [Haskell-cafe] Style In-Reply-To: References: <46CE8640.8040508@xs4all.nl> Message-ID: <46CED5FC.9070708@xs4all.nl> Henning Thielemann wrote: > > tm4 = sum . takeWhile(>0) . tail . iterate (flip div 5) > FWIW: as a result of all this I learned to write this as: tm41 = sum . takeWhile(>0) . tail . iterate (`div` 5) @@i From haskell at brecknell.org Fri Aug 24 08:58:19 2007 From: haskell at brecknell.org (Matthew Brecknell) Date: Fri Aug 24 08:49:25 2007 Subject: [Haskell-cafe] Re: newbie : multi-parameter type classes In-Reply-To: <46CED373.7000109@dfki.de> References: <46CED373.7000109@dfki.de> Message-ID: <1187960299.14769.1207084021@webmail.messagingengine.com> > Unfortunately > http://www.cse.ogi.edu/~mpj/pubs/fundeps.html > is broken. http://web.cecs.pdx.edu/~mpj/pubs/fundeps.html From Ben.Lippmeier at anu.edu.au Fri Aug 24 09:02:17 2007 From: Ben.Lippmeier at anu.edu.au (Ben Lippmeier) Date: Fri Aug 24 08:53:23 2007 Subject: [Haskell-cafe] 2D game graphics library for Haskell? Message-ID: <03aa01c7e64f$00076d00$00164700$@Lippmeier@anu.edu.au> Hi Peter, The OpenGL/GLUT bindings support all the things you would want, but it's a bit too much pain for first year students. For the last couple of years at the ANU (Australian National University, Canberra) we've been using a front end library that I wrote which is similar to SOE/HGL but with support for images, animation, alpha blending and some other things. I think the real trick is hiding enough of the OpenGL/GLUT internals to make it suitable for first year students, while at the same time exposing enough functionality so they don't feel constrained by what they can do with the library. Usually we think of the project we want the students to do, then supply most of the infrastructure via the library - leaving the students to fill in the 'fun' stuff. There is the added benefit that the OpenGL/GLUT bindings (and hence our library also) compiles out of the box on both Linux and Windows. We use linux machines at uni for the student labs, but students have been able to take their code home and get it running on their home Windows PC's without much difficulty. You can get our library (with examples) from my homepage at http://cs.anu.edu.au/people/Ben.Lippmeier/ I've also got a simple asteroids game which I wrote with an extended version of it. There is a playable version, but unfortunately it's on my home machine that is now packed in storage while I'm at MSR, Cambridge. I'm getting back to Canberra late October so if you're still interested I can dig it out and send you a copy then. Cheers, Ben. From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of peterv Sent: 24 August 2007 11:32 To: haskell-cafe@haskell.org Subject: [Haskell-cafe] 2D game graphics library for Haskell? I'm currently playing around with SOE to make some simple interactive math exercises for students. This worked fine, although I could have done this much faster using C# (which I know very well), but since I'm addicted to Haskell now, I used the latter language ;) Furthermore, I hope that one day, I will know enough Haskell to learn it to the students, because I feel that functional programming should not be given in the last bachelor or master years, since most software engineering students then know OO programming extremely well and have a horrible time with FP (I currently did not meet anyone in my sector of game development that liked FP, and many of those people had a masters degree and some were PhDs) Anyway, SOE is great for learning Haskell, but it lacks a couple of fundamental functions to make it really attractive, like: - Support for images - Support for rendering to an "offscreen graphics surface" and reading the pixels from that surface (for pixel-wise collision detection) - Support for detecting non-ASCII key presses (cursor keys, etc) - Support for joysticks Concurrent Clean seems to have a nice 2D game library and PLT/DrScheme also has nice support for basic 2D graphics, but somehow I feel Haskell is more mature and more elegant. So before digging into "advanced" APIs (like GTK itself, which I know nothing about, I'm a Win32 GDI/XNA/WPF expert), I should ask the question if something similar exists? It has to be as simple as SOE. Would it be possible to extend the GTK SOE with support for the features mentioned above? Is this insanely difficult for someone like me who knows a lot about Win32 but little Haskell? Thanks, Peter Verswyvelen No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.484 / Virus Database: 269.12.4/969 - Release Date: 23/08/2007 16:04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070824/2cc891cf/attachment-0001.htm From sievers at math2.nat.tu-bs.de Fri Aug 24 09:50:40 2007 From: sievers at math2.nat.tu-bs.de (sievers@math2.nat.tu-bs.de) Date: Fri Aug 24 11:13:52 2007 Subject: [Haskell-cafe] Style In-Reply-To: <46CE8640.8040508@xs4all.nl> References: <46CE8640.8040508@xs4all.nl> Message-ID: <18126.57904.645110.699666@gauss00.math2.nat.tu-bs.de> Arie Groeneveld wrote: > tm = sum . takeWhile(>0) . iterate f . f > where f = flip div 5 > Which one is the most elegant one generally speaking? I like that tm only uses div. > My personal choice is 'tm'. > I like 'tm3' (a revised version of tm2) in terms of > pointlessness and not having a 'where', but I think > it's a bit contrived because of the 'flip'. You can make tm whereless by noticing that you use because you use the function twice in iterate f . f, which is because you don't want the initial value that iterate gives. You can instead use tail on iterate's result, and use a section to avoid flip: tm = sum . takeWhile (>0) . tail . iterate (`div` 5) (Hope that works, can't test now...) All the best Christian Sievers From aneumann at inf.fu-berlin.de Fri Aug 24 10:12:36 2007 From: aneumann at inf.fu-berlin.de (Adrian Neumann) Date: Fri Aug 24 11:14:40 2007 Subject: [Haskell-cafe] IO inside CGI Message-ID: <46CEE754.6050706@inf.fu-berlin.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: RIPEMD160 I'm toying around with web programming in Haskell. I'm trying to write a script which GETs an id and returns a couple of random numbers. Something like this: cgiMain :: CGI CGIResult cgiMain = do inp <- getInput "id" let gen = parse inp output $ take 10 (randoms gen) parse :: Maybe String-> StdGen parse (Just x) = read x parse Nothing = undefined Now I'd like to get a new StdGen, in case no id was supplied to the script. cgiMain :: CGI CGIResult cgiMain = do inp <- getInput "id" gen <- parse inp output $ take 10 (randoms gen) parse :: Maybe String-> IO StdGen parse (Just x) = return $ read x parse Nothing = getStdGen Obviously this doesn't work because I'm trying to do IO inside CGI (right?). Is there some incantation I can perform to make this possible? Like gen <- arcaneMagic parse inp As you probably have noticed I don't know very much about monads, all I did until now was reading or writing some files. Thanks in advance -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGzudU11V8mqIQMRsRA33RAJ9buZDHgz/eXi8Jw9OBwbTErDccRgCfbGrr 1WXiGHmxlTBe01E409yJyv8= =XSDj -----END PGP SIGNATURE----- From apfelmus at quantentunnel.de Fri Aug 24 10:56:23 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Fri Aug 24 11:15:08 2007 Subject: [Haskell-cafe] Re: IO inside CGI In-Reply-To: <46CEE754.6050706@inf.fu-berlin.de> References: <46CEE754.6050706@inf.fu-berlin.de> Message-ID: Adrian Neumann wrote: > Now I'd like to get a new StdGen, in case no id was supplied to the script. > > parse :: Maybe String-> IO StdGen > parse (Just x) = return $ read x > parse Nothing = getStdGen > > Obviously this doesn't work because I'm trying to do IO inside CGI > (right?). Is there some incantation I can perform to make this possible? Abracadabra, the incantation is liftIO :: IO a -> CGI a i.e. parse :: Maybe String-> CGI StdGen parse (Just x) = return $ read x parse Nothing = liftIO getStdGen Regards, apfelmus From chaddai.fouche at gmail.com Fri Aug 24 11:11:01 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Fri Aug 24 11:15:15 2007 Subject: [Haskell-cafe] IO inside CGI In-Reply-To: <46CEE754.6050706@inf.fu-berlin.de> References: <46CEE754.6050706@inf.fu-berlin.de> Message-ID: 2007/8/24, Adrian Neumann : > Obviously this doesn't work because I'm trying to do IO inside CGI > (right?). Is there some incantation I can perform to make this possible? > Like > > gen <- arcaneMagic parse inp As doing IO in the CGI Monad is a current need, it's an instance of MonadIO and as such provide liftIO, so your arcaneMagic is called liftIO : cgiMain :: CGI CGIResult cgiMain = do inp <- getInput "id" gen <- liftIO $ parse inp output $ take 10 (randoms gen) parse :: Maybe String-> IO StdGen parse (Just x) = return $ read x parse Nothing = getStdGen -- Jeda? From benjamin.franksen at bessy.de Fri Aug 24 12:36:45 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Fri Aug 24 12:28:16 2007 Subject: [Haskell-cafe] RE: Re: Remember the future References: <46C5F84F.8020404@btinternet.com> <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> <625b74080708171543g3945b0cag3bf62ae610e8b016@mail.gmail.com> <46C6B6E4.2060704@btinternet.com> Message-ID: Simon Peyton-Jones wrote: > | It is unfortunate that the [ghc] manual does not give the translation rules, or at > | least the translation for the given example. > > Hmm. OK. I've improved the manual with a URL to the main paper > http://citeseer.ist.psu.edu/erk02recursive.html > which is highly readable. And I've given the translation for the example as you suggest Cool, thanks. BTW, the Haskell' wiki says its adoption status is 'probably no' which I find unfortunate. IMHO recursive do is a /very/ useful and practical feature and the cons listed on http://hackage.haskell.org/trac/haskell-prime/wiki/RecursiveDo don't weigh enough against that. Ok, just my (relatively uninformed) 2 cents. Cheers Ben From haskell at list.mightyreason.com Fri Aug 24 14:03:42 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Fri Aug 24 13:55:09 2007 Subject: [Haskell-cafe] Re: Remember the future In-Reply-To: References: <46C5F84F.8020404@btinternet.com> <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> <625b74080708171543g3945b0cag3bf62ae610e8b016@mail.gmail.com> <46C6B6E4.2060704@btinternet.com> Message-ID: <46CF1D7E.4000600@list.mightyreason.com> Benjamin Franksen wrote: > Simon Peyton-Jones wrote: >> | It is unfortunate that the [ghc] manual does not give the translation > rules, or at >> | least the translation for the given example. >> >> Hmm. OK. I've improved the manual with a URL to the main paper >> http://citeseer.ist.psu.edu/erk02recursive.html >> which is highly readable. And I've given the translation for the example > as you suggest > > Cool, thanks. > > BTW, the Haskell' wiki says its adoption status is 'probably no' which I > find unfortunate. IMHO recursive do is a /very/ useful and practical > feature and the cons listed on > http://hackage.haskell.org/trac/haskell-prime/wiki/RecursiveDo don't weigh > enough against that. Ok, just my (relatively uninformed) 2 cents. > > Cheers > Ben I will assume that the current compilers will keep the current "mdo" desugaring. It is incredibly valuable, and I use it in two different monad stacks in the regex-tdfa package I released. It has been an implemented extension for quite several version of GHC, and with the separate "mdo" keyword it does not interfere with other code. Why have a lazy language with added monad "do" sugaring support and balk at adding such a well tested and deployed way to use sugar for combining laziness and monads? Toy there g is an identity monadic version of f and h shows the kind of logic I tend to intersperse in an mdo block: > module Main where > > import Control.Monad.Fix > import Control.Monad.Identity > import Control.Monad.Writer > > f x = do > let a = x*b > b = x+1 > return a > > test_f = runIdentity (f 2) -- 6 > > g x = mdo > a <- return (x*b) > b <- return (x+1) > return a > > test_g = runIdentity (g 2) -- 6 > > h x = mdo > a <- return (x*b) > if even b then tell [('a',a)] else return () > b <- return (x+1) > tell [('b',b)] > return a > > test_h1 = (runWriter (h 1)) -- (2,[('a',2),('b',2)]) > test_h2 = (runWriter (h 2)) -- (6,[('b',3)]) -- Chris From andrewcoppin at btinternet.com Fri Aug 24 14:13:46 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 24 14:03:52 2007 Subject: [Haskell-cafe] Re: Graph reduction [Was: Where is StackOverflow on the Wiki?] In-Reply-To: <548bba360708231434g19c0fd2cne66a27c98caaabd7@mail.gmail.com> References: <000101c7e1c6$8724d260$956e7720$@be> <46C9BF6D.40806@cisco.com> <20070820191526.GD3098@localhost.localdomain> <404396ef0708211223y4bcf7984u6650762b1f06731b@mail.gmail.com> <46CDD568.4080007@btinternet.com> <548bba360708231434g19c0fd2cne66a27c98caaabd7@mail.gmail.com> Message-ID: <46CF1FDA.6070504@btinternet.com> Shiqi Cao wrote: > Check out this > > http://www.cas.mcmaster.ca/~kahl/HOPS/ > > Heh. I was thinking about trying to build something *exactly like* this... OOC, how the heck did they make it work through a "document interface"? Surely that's impossible? From edward.ing at gmail.com Fri Aug 24 15:49:38 2007 From: edward.ing at gmail.com (Edward Ing) Date: Fri Aug 24 15:40:46 2007 Subject: [Haskell-cafe] Haskellnet could not find network-any dependency. Message-ID: <8f66da400708241249i2111203du92460e7878b3cd53@mail.gmail.com> Hi, I am trying to install Haskellnet. But the configuration breaks on dependency of network-any in GHC 6.6. I thought network-any was part of Hierarchical libraries? If not where do I get it? Edaward. From rich.neswold at gmail.com Sat Aug 25 00:17:49 2007 From: rich.neswold at gmail.com (Rich Neswold) Date: Sat Aug 25 00:08:54 2007 Subject: [Haskell-cafe] Help using CGIT In-Reply-To: References: <14cf844b0708221126l37c1654bhd8b120e78855377c@mail.gmail.com> <20070822212828.GA26256@matrix.chaos.earth.li> <14cf844b0708221834na33ffekb237b253d1b04ab1@mail.gmail.com> Message-ID: <14cf844b0708242117v4aa363d5xdcb67cbe6a62be0f@mail.gmail.com> On 8/24/07, Bjorn Bringert wrote: > > On Aug 23, 2007, at 3:34 , Rich Neswold wrote: > > > Bingo! Method #3 works beautifully! I missed the using-lift-with- > > the-constructor permutation. > > > > Thanks for your help! > > I started writing a tutorial for Haskell web programming with the cgi > package a while back, but haven't worked on it for a while, see > http://www.haskell.org/haskellwiki/Practical_web_programming_in_Haskell > I haven't added it to the list of tutorials yet, since it's still > rather incomplete. > > The section on using CGIT is just a stub, perhaps you would like to > contribute to it? See > http://www.haskell.org/haskellwiki/ > Practical_web_programming_in_Haskell#Extending_the_CGI_monad_with_monad_ > transformers > Done. As I learn more about using CGIT, I'll try to remember to add more content. Any suggestions to improve it are welcome! -- Rich JID: rich@neswold.homeunix.net AIM: rnezzy -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070824/a162bb7a/attachment.htm From coeus at gmx.de Sat Aug 25 01:34:10 2007 From: coeus at gmx.de (Marc A. Ziegert) Date: Sat Aug 25 01:25:38 2007 Subject: [Haskell-cafe] Style In-Reply-To: <46CEDC87.7030401@xs4all.nl> References: <46CE8640.8040508@xs4all.nl> <200708241114.12518.coeus@gmx.de> <46CEDC87.7030401@xs4all.nl> Message-ID: <200708250734.17225.coeus@gmx.de> whops... i did check it, but that was a copypaste mistake. buggy: > tm_parallelizable_v1 = \n -> sum . takeWhile (>0) $ map (div n) fives > where fives = iterate (*5) 1 should be: > tm_parallelizable_v1 = \n -> sum . takeWhile (>0) $ map (div n) fives > where fives = iterate (*5) 5 - marc Am Freitag, 24. August 2007 schrieben Sie: > Hi Marc > > First off, thanks for your reply. > >> tm_parallelizable_v1 = \n -> sum . takeWhile (>0) $ map (div n) fives > >> where fives = iterate (*5) 1 > Did you check this one? IMHO I think it's producing the 'wrong' answer. > > *Main> tm_parallelizable_v1 100 > 124 > (0.00 secs, 0 bytes) > > *Main> tm 100 > 24 > (0.00 secs, 0 bytes) > > If comparing the result to the other variants is accepted as a sort > of proof. ;-) > > But calculating the number of trailing zero's of n! is a matter of > counting powers of five in the factorized n!: f.e.: > > 10! = 1 2 3 2^2 5 2*3 7 2^3 3^2 2*5 > --> 5^2 --> picking up enough powers of 2 --> (2*5)^2 = 100 > > So you will have to correct your 'fives' to f.e. > > fives = tail $ iterate (*5) 1 > > > > Regards > > > @@i > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070825/493bf06e/attachment-0001.bin From bf3 at telenet.be Sat Aug 25 05:18:27 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sat Aug 25 05:09:25 2007 Subject: [Haskell-cafe] How to fix linker errors when creating a package using cabal Message-ID: <000201c7e6f8$e53608b0$afa21a10$@be> I'm trying to make a package of Ben.Lippmeier's very nice ANUPlot graphics library (http://cs.anu.edu.au/people/Ben.Lippmeier) IMHO this would be a great contribution to the Haskell library, it's very clean code for newbies :) I created the following cabal file: name: Plot version: 1.1 license: AllRightsReserved maintainer: Ben.Lippmeier@anu.edu.au exposed-modules: Graphics.Plot.Display, Graphics.Plot.Picture, Graphics.Plot.Primitive, Graphics.Plot.Render, Graphics.Plot.Colors, Graphics.Plot.Util, Graphics.Plot.RenderState, Graphics.Plot.Animate, Graphics.Plot.View, Graphics.Plot.Wrapper, Graphics.Plot Build-Depends: base, OpenGL, GLUT ghc-options: -fglasgow-exts and then tried runhaskell Setup.hs configure runhaskell Setup.hs build runhaskell Setup.hs install which all seemed to work fine (see log below). However, when building an example that uses that package, I get a lot of linker errors (see log below) Is this because I configured the cabal files incorrectly, or do I have to adjust the module sources so they explicitly export the missing symbols? Thanks, Peter ------------------ LOG ------------------------------- L:\3rdParty\ANUPlot\src>runhaskell Setup.hs unregister Unregistering Plot-1.1... Saving old package config file... done. Writing new package config file... done. L:\3rdParty\ANUPlot\src>runhaskell Setup.hs clean cleaning... L:\3rdParty\ANUPlot\src>runhaskell Setup.hs configure --global Configuring Plot-1.1... configure: Dependency base-any: using base-2.1.1 configure: Dependency OpenGL-any: using OpenGL-2.2.1 configure: Dependency GLUT-any: using GLUT-2.1.1 configure: Using install prefix: C:\Program Files configure: Binaries installed in: C:\Program Files\Haskell\bin configure: Libraries installed in: C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1 configure: Private binaries installed in: C:\Program Files\Plot-1.1 configure: Data files installed in: C:\Program Files\Common Files\Plot-1.1 configure: Using compiler: c:\app\ghc\bin\ghc.exe configure: Compiler flavor: GHC configure: Compiler version: 6.6.1 configure: Using package tool: c:\app\ghc\bin\ghc-pkg.exe configure: Using ar found on system at: c:\app\ghc\bin\ar.exe configure: No haddock found configure: No pfesetup found configure: No ranlib found configure: Using runghc found on system at: c:\app\ghc\bin\runghc.exe configure: No runhugs found configure: No happy found configure: No alex found configure: Using hsc2hs: c:\app\ghc\bin\hsc2hs.exe configure: No c2hs found configure: No cpphs found configure: No greencard found L:\3rdParty\ANUPlot\src>runhaskell Setup.hs build Preprocessing library Plot-1.1... Building Plot-1.1... L:\3rdParty\ANUPlot\src>runhaskell Setup.hs register Registering Plot-1.1... Reading package info from ".installed-pkg-config" ... done. Saving old package config file... done. Writing new package config file... done. L:\3rdParty\ANUPlot\src>runhaskell Setup.hs install Installing: C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1 & C:\Program Files\Haskell\bin Plot-1.1... Registering Plot-1.1... Reading package info from ".installed-pkg-config" ... done. Saving old package config file... done. Writing new package config file... done. Linking AnimClock.exe ... C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Wrapper.o)(.text+0x2f1):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_Display_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Wrapper.o)(.text+0xc7c):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Wrapper.o)(.text+0xdcb):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_Idle_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Wrapper.o)(.text+0xdfc):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_Display_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Wrapper.o)(.text+0xe3b):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_Display_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Wrapper.o)(.text+0xe68):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_Display_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Wrapper.o)(.rodata+0x54):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(RenderState.o)(.text+0x3d6) :fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(RenderState.o)(.text+0x652) :fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(RenderState.o)(.text+0x8ce) :fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(RenderState.o)(.text+0xb4a) :fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(RenderState.o)(.text+0xdc8) :fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_KeyMouse_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(RenderState.o)(.rodata+0x10 ):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x190b):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x19cc):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x1b9b):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x1c5c):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x20c9):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x21fc):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x22f0):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x2400):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x2e83):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x2f74):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x305c):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x37f9):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x3954):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x3a60):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x3b88):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x3dec):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x3ebc):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x402a):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x43c1):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x45f2):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x4975):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x4c5a):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x4efe):fake: more undefined references to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' follow C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x5b0a):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_Reshape_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x5b38):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_Motion_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.text+0x5b65):fake: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_KeyMouse_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.rodata+0x130):fake : undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.rodata+0x134):fake : undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.rodata+0x144):fake : undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.rodata+0x148):fake : undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.rodata+0x170):fake : undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.rodata+0x174):fake : undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.rodata+0x1a4):fake : undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(View.o)(.rodata+0x1a8):fake : undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Render.o)(.text+0x1e2b):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziTexture_cacheTexture_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Render.o)(.text+0x2146):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziRaster_withRasterCoords_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Render.o)(.text+0x2484):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziRaster_withRasterCoords_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Render.o)(.rodata+0xc0):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziRaster_withRasterCoords_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Render.o)(.rodata+0xc4):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziTexture_cacheTexture_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x322):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x511):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x75c):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x838):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x908):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x1111):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x1220):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x151a):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x16bc):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziCallback_KeyMouse_con_info' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x17bd):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x18b4):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.text+0x1a24):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.rodata+0x28):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.rodata+0x2c):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.rodata+0x98):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.rodata+0xac):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zhzh_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Animate.o)(.rodata+0xb0):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziUtilOp_zlzhzhzg_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Display.o)(.text+0x766):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziDump_dumpFragmentState_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Display.o)(.text+0x76d):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziDump_dumpFramebufferState_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Display.o)(.text+0x7d7):fak e: undefined reference to `Plotzm1zi1_GraphicsziPlotziDump_dumpGlutState_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Display.o)(.rodata+0xa4):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziDump_dumpGlutState_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Display.o)(.rodata+0xa8):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziDump_dumpFramebufferState_closure' C:\Program Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Display.o)(.rodata+0xac):fa ke: undefined reference to `Plotzm1zi1_GraphicsziPlotziDump_dumpFragmentState_closure' collect2: ld returned 1 exit status From malte at gmx-topmail.de Sat Aug 25 06:11:05 2007 From: malte at gmx-topmail.de (Malte Milatz) Date: Sat Aug 25 06:02:06 2007 Subject: [Haskell-cafe] How to fix linker errors when creating a package using cabal In-Reply-To: <000201c7e6f8$e53608b0$afa21a10$@be> References: <000201c7e6f8$e53608b0$afa21a10$@be> Message-ID: <20070825121105.4a0f5c3f@aligatoro.ret> Peter Verswyvelen: > However, when building an example that uses that package, I get a lot of > linker errors (see log below) What options did you use when compiling the example? From benjamin.franksen at bessy.de Sat Aug 25 07:12:16 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Sat Aug 25 07:03:42 2007 Subject: [Haskell-cafe] RE: Re: Remember the future References: <46C5F84F.8020404@btinternet.com> <625b74080708171510p19b3c2d1j5722d07dee367d94@mail.gmail.com> <625b74080708171543g3945b0cag3bf62ae610e8b016@mail.gmail.com> <46C6B6E4.2060704@btinternet.com> Message-ID: Simon Peyton-Jones wrote: > | >From the ghc manual: > | > | ----------- > | 7.3.3. The recursive do-notation > | ... > > | > | It is unfortunate that the manual does not give the translation rules, or at > | least the translation for the given example. > > Hmm. OK. I've improved the manual with a URL to the main paper > http://citeseer.ist.psu.edu/erk02recursive.html > which is highly readable. And I've given the translation for the example as you suggest After finally reading the paper I agree that repeating the translation in teh manual is not a good idea. However, I suggest the manual should mention the restrictions imposed for mdo (wrt the normal do) * no shadowing allowed for generator bound variables * let bindings must be monomorphic Both of them might cause confusion if someone hits them by accident and starts to wonder what's wrong with her code, in which case it would be helpful if this information were directly available in teh manual. No need to give a detailed rationale (that's what the paper can be read for), just say that they are there. BTW, I agree with the paper that the restrictions are sensible and typically don't hurt. Thanks Ben From bf3 at telenet.be Sat Aug 25 07:16:17 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sat Aug 25 07:07:13 2007 Subject: [Haskell-cafe] How to fix linker errors when creating a package using cabal In-Reply-To: <20070825121105.4a0f5c3f@aligatoro.ret> References: <000201c7e6f8$e53608b0$afa21a10$@be> <20070825121105.4a0f5c3f@aligatoro.ret> Message-ID: <000301c7e709$5b5caa70$1215ff50$@be> Oops, I forget to paste that in. Just GHC --make AnimClock.hs with ANUPlot\src\Demo As the current directory. -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Malte Milatz Sent: Saturday, August 25, 2007 12:11 PM To: haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] How to fix linker errors when creating a package using cabal Peter Verswyvelen: > However, when building an example that uses that package, I get a lot of > linker errors (see log below) What options did you use when compiling the example? _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From benjamin.franksen at bessy.de Sat Aug 25 07:22:36 2007 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Sat Aug 25 07:13:49 2007 Subject: [Haskell-cafe] Re: Haskellnet could not find network-any dependency. References: <8f66da400708241249i2111203du92460e7878b3cd53@mail.gmail.com> Message-ID: Edward Ing wrote: > Hi, > I am trying to install Haskellnet. But the configuration breaks on > dependency of network-any in GHC 6.6. > > I thought network-any was part of Hierarchical libraries? > > If not where do I get it? The generic place for libraries nowadays is hackage: http://hackage.haskell.org/packages/archive/pkg-list.html where you find http://hackage.haskell.org/cgi-bin/hackage-scripts/package/network-2.0 The 'Hierarchical Libraries' do not exist as such; all modern Haskell libraries use the hierarchical module name extension for their exported modules. There are, however, a certain number of libraries that are regularly shipped together with Haskell implementations. All of them, except those which work only together with a certain compiler/interpreter version (e.g. 'base'), are avaiable from hackage. BTW, it would be nice if hackage would list repository locations, too, if available. The one for 'network' library is not mentioned on hackage; I found one here: http://darcs.haskell.org/packages/network/ Cheers Ben From hjgtuyl at chello.nl Sat Aug 25 07:35:24 2007 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Sat Aug 25 07:26:24 2007 Subject: [Haskell-cafe] newbie - how to call a Haskell interpreter from C In-Reply-To: References: Message-ID: The easiest way to run Haskell software from a C program is to give the shell command: runhaskell Foo.hs This command is part of the GHC package. A more advanced way is, to link Haskell libraries by means of the foreign function interface (FFI) [1]. There are several tools to support FFI development [2]. I am sure my list of URL's is not complete. [1] http://www.cse.unsw.edu.au/~chak/haskell/ffi/ http://www.haskell.org/haskellwiki/FFI_Introduction http://www.haskell.org/haskellwiki/FFI_cook_book [2] http://www.haskell.org/haskellwiki/FFI_imports_packaging_utility http://www.haskell.org/haskellwiki/HSFFIG Met vriendelijke groet, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- On Fri, 24 Aug 2007 01:12:56 +0200, Brock Peabody wrote: > I've been trying to find place to use Haskell at work, and I think a good > opportunity will be to use it for our scripting language. To do that, I > need > to be able to invoke an interpreter directly from another language. > > I've investigated using HaskellScript (too web/ActiveX centric), but > really > I just want to compile ghci or hugs into my executable/library. It seems > like this is something I should be able to figure out easily, but so far > I've failed and have not found any reference to others succeeding. -- From andrewcoppin at btinternet.com Sat Aug 25 07:50:29 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 07:40:31 2007 Subject: [Haskell-cafe] Ideas Message-ID: <46D01785.7070503@btinternet.com> How easy would it be to make / would anybody care / has somebody already made ... in Haskell? - Blogging software. (Because there isn't enough of it in the world yet.) - A wiki program. (Ditto.) - A general CMS. - An interactive function plotter. (GNUplot is nice, but it can't plot recursive functions...) - A "graphical programming tool". (You add boxes and put in lines, it constructs a "program" that you can run.) From ndmitchell at gmail.com Sat Aug 25 08:11:36 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Sat Aug 25 08:02:40 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D01785.7070503@btinternet.com> References: <46D01785.7070503@btinternet.com> Message-ID: <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> Hi > - Blogging software. (Because there isn't enough of it in the world yet.) Hope (google: Haskell Hope) > - A wiki program. (Ditto.) Flippi (google: Haskell Flippi) > - A general CMS. Hope > - An interactive function plotter. (GNUplot is nice, but it can't plot > recursive functions...) None that I know of. > - A "graphical programming tool". (You add boxes and put in lines, it > constructs a "program" that you can run.) You mean a programming tool with a horrible syntax and user interface? If you want to remove the joy from programming, just use Ada. Alternatively, use PureData, which can be extended with Haskell, and gives boxes and lines. http://haskell.org/haskellwiki/AngloHaskell/2007#Abstracts Thanks Neil From andrewcoppin at btinternet.com Sat Aug 25 08:33:20 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 08:23:23 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> Message-ID: <46D02190.8030106@btinternet.com> Neil Mitchell wrote: > >> - A wiki program. (Ditto.) >> > > Flippi (google: Haskell Flippi) > ...and yet haskell.org uses WikiMedia? (Which is written in something bizzare like Perl...) >> - A general CMS. >> > > Hope > Woo! I'll have to go play with this for a while... >> - An interactive function plotter. (GNUplot is nice, but it can't plot >> recursive functions...) >> > > None that I know of. > Mmm, OK. I would have thought it would be a nice project for somebody... >> - A "graphical programming tool". (You add boxes and put in lines, it >> constructs a "program" that you can run.) >> > > You mean a programming tool with a horrible syntax and user interface? > LOL! That's not entirely what I meant... ;-) Have you ever played with KLogic? You draw boxes and lines, and it makes some logic. (As in the digital electronics sense of "logic".) I have some (very expensive) software called Reaktor. You draw boxes and lines, it does DSP algorithms. You build synthesizers and effects boxes with it. You get the idea. (The trouble with KLogic is its utter buggyness... I'd love to have a tool like it that actually works properly!) > If you want to remove the joy from programming, just use Ada. > Or Perl. Or Java. Or C. Or C++. Or VB. Or... > Alternatively, use PureData, which can be extended with Haskell, and > gives boxes and lines. > http://haskell.org/haskellwiki/AngloHaskell/2007#Abstracts > OK, I'll take a cool. From ndmitchell at gmail.com Sat Aug 25 08:38:58 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Sat Aug 25 08:29:59 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D02190.8030106@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> Message-ID: <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> Hi > > Flippi (google: Haskell Flippi) > > ...and yet haskell.org uses WikiMedia? (Which is written in something > bizzare like Perl...) Yes, but WikiMedia is a result of years of work, Flippi is a lot less. Wikipedia uses WikiMedia - its a tried and proven solution. > >> - A "graphical programming tool". (You add boxes and put in lines, it > >> constructs a "program" that you can run.) > > Have you ever played with KLogic? You draw boxes and lines, and it makes > some logic. (As in the digital electronics sense of "logic".) > > I have some (very expensive) software called Reaktor. You draw boxes and > lines, it does DSP algorithms. You build synthesizers and effects boxes > with it. That sounds exactly like PureData - you can also do graphics as well with PureData, the demo I saw was very cool. Of course, PureData is written in C with Haskell as an extension language. The last two ideas you mentioned require a graphical user interface, which is an area of Haskell which is comparatively weak, compared to the rest of Haskell. Thanks Neil PS: Apologies to Andrew for 2 copies of this message. From flippa at flippac.org Sat Aug 25 08:39:54 2007 From: flippa at flippac.org (Philippa Cowderoy) Date: Sat Aug 25 08:31:07 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D02190.8030106@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> Message-ID: On Sat, 25 Aug 2007, Andrew Coppin wrote: > Neil Mitchell wrote: > > > > > - A wiki program. (Ditto.) > > > > > > > Flippi (google: Haskell Flippi) > > > > ...and yet haskell.org uses WikiMedia? (Which is written in something > bizzare like Perl...) > Flippi is... rather minimalistic. And fugly. You can tell it was written by someone who has trouble getting things done! I get the impression it did a certain amount of good as a proof of concept and a reminder that doing things the old-fashioned way still works though. > > > - A general CMS. > > > > > > > Hope > > > > Woo! I'll have to go play with this for a while... > While I haven't looked at it much, Hope's seeing a lot more actual use. -- flippa@flippac.org Society does not owe people jobs. Society owes it to itself to find people jobs. From flippa at flippac.org Sat Aug 25 08:49:37 2007 From: flippa at flippac.org (Philippa Cowderoy) Date: Sat Aug 25 08:40:49 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> Message-ID: On Sat, 25 Aug 2007, Neil Mitchell wrote: > Hi > > > > Flippi (google: Haskell Flippi) > > > > ...and yet haskell.org uses WikiMedia? (Which is written in something > > bizzare like Perl...) > > Yes, but WikiMedia is a result of years of work, Flippi is a lot less. The original version was the result of a certain amount of thinking, an overnight hack and a few tweaks :-) > > Have you ever played with KLogic? You draw boxes and lines, and it makes > > some logic. (As in the digital electronics sense of "logic".) > > > > I have some (very expensive) software called Reaktor. You draw boxes and > > lines, it does DSP algorithms. You build synthesizers and effects boxes > > with it. > > That sounds exactly like PureData - you can also do graphics as well > with PureData, the demo I saw was very cool. Of course, PureData is > written in C with Haskell as an extension language. > Reaktor is rather nicer to use than PureData though, in that it's designed to work with mainstream sequencers (or any VST - I work with trackers myself) and be used by non-hackers. Also, I'm not entirely sure it's fair to say that it has Haskell as an extension language as such - but Claude's slides'll give a better explanation than I can. > The last two ideas you mentioned require a graphical user interface, > which is an area of Haskell which is comparatively weak, compared to > the rest of Haskell. > Yep. It would be nice to have a library for doing that kind of stuff though, I suspect there're many nifty projects that would be easy to implement once that was done - Haskell's good at manipulating the underlying structures. -- flippa@flippac.org "The reason for this is simple yet profound. Equations of the form x = x are completely useless. All interesting equations are of the form x = y." -- John C. Baez From bf3 at telenet.be Sat Aug 25 08:53:57 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sat Aug 25 08:44:54 2007 Subject: [Haskell-cafe] How to fix linker errors when creating a package using cabal In-Reply-To: <46D02057.2060200@ed.ac.uk> References: <000201c7e6f8$e53608b0$afa21a10$@be> <46D02057.2060200@ed.ac.uk> Message-ID: <000401c7e717$002cf980$0086ec80$@be> Indeed, adding the non-exposed modules to the other-modules fixed it. Thanks Allan! Cheers, Peter -----Original Message----- From: Allan Clark [mailto:a.d.clark@ed.ac.uk] Sent: Saturday, August 25, 2007 2:28 PM To: Peter Verswyvelen Subject: Re: [Haskell-cafe] How to fix linker errors when creating a package using cabal Peter Verswyvelen wrote: > I'm trying to make a package of Ben.Lippmeier's very nice ANUPlot graphics > library (http://cs.anu.edu.au/people/Ben.Lippmeier) > > IMHO this would be a great contribution to the Haskell library, it's very > clean code for newbies :) > > I created the following cabal file: > > name: Plot > version: 1.1 > license: AllRightsReserved > maintainer: Ben.Lippmeier@anu.edu.au > exposed-modules: > Graphics.Plot.Display, > Graphics.Plot.Picture, > Graphics.Plot.Primitive, > Graphics.Plot.Render, > Graphics.Plot.Colors, > Graphics.Plot.Util, > Graphics.Plot.RenderState, > Graphics.Plot.Animate, > Graphics.Plot.View, > Graphics.Plot.Wrapper, > Graphics.Plot > Build-Depends: base, OpenGL, GLUT > ghc-options: -fglasgow-exts > > and then tried > runhaskell Setup.hs configure > runhaskell Setup.hs build > runhaskell Setup.hs install > > which all seemed to work fine (see log below). > > However, when building an example that uses that package, I get a lot of > linker errors (see log below) > > Is this because I configured the cabal files incorrectly, or do I have to > adjust the module sources so they explicitly export the missing symbols? > > Thanks, > Peter > [ snip ] > Files\Haskell\Plot-1.1\ghc-6.6.1/libHSPlot-1.1.a(Wrapper.o)(.text+0x2f1):fak > e: undefined reference to > `Plotzm1zi1_GraphicsziPlotziCallback_Display_con_info' > Hi, I'm not cabal expert, but basically I had a similar problem, and I fixed it by adding a missing module in the 'exposed-modules' part. Basically where is con_info defined, it's probably in a module which isn't exposed. If so then either put it in the 'exposed-modules' section or if you do not wish to expose it then maybe you could try putting it in a 'other-modules' section. regards allan From cmb21 at kent.ac.uk Sat Aug 25 09:43:34 2007 From: cmb21 at kent.ac.uk (C.M.Brown) Date: Sat Aug 25 09:34:54 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D01785.7070503@btinternet.com> References: <46D01785.7070503@btinternet.com> Message-ID: > - A "graphical programming tool". (You add boxes and put in lines, it > constructs a "program" that you can run.) I'm not entirely exactly sure what you mean by this. If you mean one can create programs by creating them visually then perhaps you could consider Vital: http://www.cs.kent.ac.uk/projects/vital/ It's a document-centered implementation of Haskell. Allowing one to display and directly manipulate Haskell data structures in real-time. Chris. From bf3 at telenet.be Sat Aug 25 09:45:27 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sat Aug 25 09:36:22 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> Message-ID: <000601c7e71e$31c83cf0$9558b6d0$@be> >> - A "graphical programming tool". (You add boxes and put in lines, it >> constructs a "program" that you can run.) > You mean a programming tool with a horrible syntax and user interface? > If you want to remove the joy from programming, just use Ada. For programmers or scientists, I agree. For designers/artists who want to make cool stuff without learning a textual programming language, I totally disagree. Look at Apple Shake, SideFX Houdini, Werkzeug, Shader FX, Unreal 3, or even National Instruments Labview, and more... They all have a (albeit very limited) visual programming language. People get real "procedural" work done with these tools. Almost every 3D movie uses at least one of tools I mentioned. Peter From newptcai at gmail.com Sat Aug 25 09:57:48 2007 From: newptcai at gmail.com (Peter Cai) Date: Sat Aug 25 09:48:52 2007 Subject: [Haskell-cafe] Question of a manual computation on Reader Monad. Message-ID: Hi all, In order to improve my understanding of monad, I am trying to do some manual computation on "Reader Monad" but I got some problem. The computation is like this: --instance Monad (Reader e) where -- return a = Reader $ \e -> a -- (Reader r) >>= f = Reader $ \e -> f (r e) e runReader (do { b <- Reader $ show; return b } ) -- This is the initial expression, it should equals "show" runReader (Reader $ show >>= \b -> return b) -- remove do notion runReader (Reader $ \e -> return( show e ) e) -- apply the definition of ">>=" runReader (Reader $ \e -> (Reader $ \e1 -> show(e)) e) -- apply the definition of "return" But the last expression is incorrect, and I don't know how to go on. Could anyone explain this for me? Thanks in advance! Reference : http://www.haskell.org/all_about_monads/html/readermonad.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070825/ccdb6227/attachment-0001.htm From malte at gmx-topmail.de Sat Aug 25 10:45:37 2007 From: malte at gmx-topmail.de (Malte Milatz) Date: Sat Aug 25 10:36:40 2007 Subject: [Haskell-cafe] Question of a manual computation on Reader Monad. In-Reply-To: References: Message-ID: <20070825164537.4c17be64@aligatoro.ret> Peter Cai: > Hi all, > > In order to improve my understanding of monad, I am trying to do some manual > computation on "Reader Monad" but I got some problem. > > The computation is like this: > > --instance Monad (Reader e) where > -- return a = Reader $ \e -> a > -- (Reader r) >>= f = Reader $ \e -> f (r e) e This cannot work out because this definition is ill-typed, which you will notice if you try to compile it (or if you contemplate about what the type of (f (r e) e) is). Here is a way to define a reader monad: newtype Reader e a = Reader { runReader :: (e -> a) } instance Monad (Reader e) where return a = Reader $ \_ -> a Reader r >>= f = Reader $ \e -> runReader (f (r e)) e You can then do your calculation like this: Reader show >>= return = Reader $ \e -> runReader (return (show e)) e = Reader $ \e -> runReader (Reader (\_ -> show e)) e = Reader $ \e -> (\_ -> show e) e = Reader $ \e -> show e = Reader show; -- Note that, except for the use of ?show? as a specific -- example, the above is equivalent to proving that the -- second monad law holds for (Reader e). runReader (Reader show >>= return) = runReader (Reader show) = show. Malte From a.biurvOir4 at asuhan.com Sat Aug 25 11:10:47 2007 From: a.biurvOir4 at asuhan.com (Kim-Ee Yeoh) Date: Sat Aug 25 11:01:49 2007 Subject: [Haskell-cafe] Question of a manual computation on Reader Monad. In-Reply-To: References: Message-ID: <12326875.post@talk.nabble.com> ??? wrote: > > runReader (do { b <- Reader $ show; return b } ) -- This is the initial > expression, it should equals "show" > > runReader (Reader $ show >>= \b -> return b) -- remove do notion > I'm not sure that's the right un-do-ization. It so happens that the exponent monad ((->) r) and the Reader monads are semantically identically. Is this a homework question? ??? wrote: > > runReader (Reader $ \e -> return( show e ) e) -- apply the definition of > ">>=" > > runReader (Reader $ \e -> (Reader $ \e1 -> show(e)) e) -- apply the > definition of "return" > > But the last expression is incorrect, and I don't know how to go on. > -- View this message in context: http://www.nabble.com/Question-of-a-manual-computation-on-Reader-Monad.-tf4328025.html#a12326875 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From brock.peabody at gmail.com Sat Aug 25 12:34:45 2007 From: brock.peabody at gmail.com (Brock Peabody) Date: Sat Aug 25 12:25:47 2007 Subject: [Haskell-cafe] newbie - how to call a Haskell interpreter from C In-Reply-To: References: Message-ID: On 8/25/07, Henk-Jan van Tuyl wrote: > > > The easiest way to run Haskell software from a C program is to give the > shell command: > runhaskell Foo.hs I'm a newbie but not that new :) I really have to be able to interpret the Haskell from within the same process. A more advanced way is, to link Haskell libraries by means of the foreign > function interface (FFI) [1]. > There are several tools to support FFI development [2]. I am sure my list > of URL's is not complete. > > [1] http://www.cse.unsw.edu.au/~chak/haskell/ffi/ > > http://www.haskell.org/haskellwiki/FFI_Introduction > http://www.haskell.org/haskellwiki/FFI_cook_book > > [2] http://www.haskell.org/haskellwiki/FFI_imports_packaging_utility > http://www.haskell.org/haskellwiki/HSFFIG My understanding is that FFI helps you to call into other languages from Haskell and vice-versa. I will definitely need this, but what I can't figure out how to do is to invoke the ghci or hugs interpreter programmatically, in-process. I didn't see a way to do that in the links you listed, am I missing something? Much thanks, Brock Peabody -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070825/0974d3ed/attachment.htm From stefanor at cox.net Sat Aug 25 12:55:01 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sat Aug 25 12:46:08 2007 Subject: [Haskell-cafe] newbie - how to call a Haskell interpreter from C In-Reply-To: References: Message-ID: <20070825165500.GA4877@localhost.localdomain> On Sat, Aug 25, 2007 at 12:34:45PM -0400, Brock Peabody wrote: > On 8/25/07, Henk-Jan van Tuyl wrote: > > > > > > The easiest way to run Haskell software from a C program is to give the > > shell command: > > runhaskell Foo.hs > > > I'm a newbie but not that new :) I really have to be able to interpret the > Haskell from within the same process. > > > A more advanced way is, to link Haskell libraries by means of the foreign > > function interface (FFI) [1]. > > There are several tools to support FFI development [2]. I am sure my list > > of URL's is not complete. > > > > [1] http://www.cse.unsw.edu.au/~chak/haskell/ffi/ > > > > http://www.haskell.org/haskellwiki/FFI_Introduction > > http://www.haskell.org/haskellwiki/FFI_cook_book > > > > [2] http://www.haskell.org/haskellwiki/FFI_imports_packaging_utility > > http://www.haskell.org/haskellwiki/HSFFIG > > > My understanding is that FFI helps you to call into other languages from > Haskell and vice-versa. I will definitely need this, but what I can't figure > out how to do is to invoke the ghci or hugs interpreter programmatically, > in-process. I didn't see a way to do that in the links you listed, am I > missing something? No, you're not missing anything, and there are no deliberately embeddable Haskell interpreters. Your options are: 1a. GHC, native code: Link libHSplugins.a into your program (compile Don's hs-plugins library). Then call the external functions described in http://www.cse.unsw.edu.au/~dons/hs-plugins/hs-plugins-Z-H-4.html#node_sec_7.2, Pro: Full GHC runtime speed Con: Full GHC compile-time sloth As big as GHC (20mbytes file size) Leaks memory 1b. GHC, bytecode: Write a binding to the GHC-API runStmt function. foreign export it. Pro: As fast as GHCi No leaks Con: Still huge Slow runtime 2. Hugs Link Hugs. Study the source code to runhugs. Pro: Much faster loading Much smaller footprint Con: Less polished Slow runtime Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070825/bec32ab5/attachment.bin From andrewcoppin at btinternet.com Sat Aug 25 14:36:02 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 14:26:05 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <20070825153604.GA4587@zombie.inf.tu-dresden.de> References: <46D01785.7070503@btinternet.com> <20070825153604.GA4587@zombie.inf.tu-dresden.de> Message-ID: <46D07692.1050606@btinternet.com> Bertram Felgenhauer wrote: > Hi, > > You wrote: > >> - An interactive function plotter. (GNUplot is nice, but it can't plot >> recursive functions...) >> > > Actually you can express a lot of those with the ?: operator. > Ooo... interesting. I don't recall seeing *that* in the manual! > gnuplot> f(x) = x < 1 ? 0 : f(x/2) + 1 > gnuplot> plot f(x) > > works just as expected. Mutually recursive functions defined that > way work, too. > > Still, support could be a lot better here. > OK... so how do I plot a graph of the Fibonacci numbers? Similarly, how do I plot (what Haskell calls) interate f 0? From andrewcoppin at btinternet.com Sat Aug 25 14:41:15 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 14:31:16 2007 Subject: [Haskell-cafe] Parsec is being weird at me Message-ID: <46D077CB.5010106@btinternet.com> Anybody want to explain to me why this doesn't work? ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.6.1, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base ... linking ... done. Prelude> :m Text.ParserCombinators.Parsec Prelude Text.ParserCombinators.Parsec> parseTest (endBy anyToken (char '#')) "abc#" Loading package parsec-2.0 ... linking ... done. parse error at (line 1, column 1): unexpected "b" expecting "#" From andrewcoppin at btinternet.com Sat Aug 25 14:43:30 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 14:33:35 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> Message-ID: <46D07852.4080808@btinternet.com> Neil Mitchell wrote: > HI > > >>> Flippi (google: Haskell Flippi) >>> >> ...and yet haskell.org uses WikiMedia? (Which is written in something >> bizzare like Perl...) >> > > Yes, but WikiMedia is a result of years of work, Flippi is a lot less. > Wikipedia uses WikiMedia - its a tried and proven solution. > Well, I guess... I just thought, you know, the Tcl wiki is written in Tcl, why isn't the Haskell wiki written in Haskell? Hey, aren't we trying to tell people is a *useful* language that people should learn and use? ;-) >>>> - A "graphical programming tool". (You add boxes and put in lines, it >>>> constructs a "program" that you can run.) >>>> >> Have you ever played with KLogic? You draw boxes and lines, and it makes >> some logic. (As in the digital electronics sense of "logic".) >> >> I have some (very expensive) software called Reaktor. You draw boxes and >> lines, it does DSP algorithms. You build synthesizers and effects boxes >> with it. >> > > That sounds exactly like PureData - you can also do graphics as well > with PureData, the demo I saw was very cool. Of course, PureData is > written in C with Haskell as an extension language. > Oh. Ah well.. > The last two ideas you mentioned require a graphical user interface, > which is an area of Haskell which is comparatively weak, compared to > the rest of Haskell. > Yeah, I noticed. Though actually Gtk2hs isn't too bad. (There's a few corners that require bit-flipping and other low-level strangeness...) From andrewcoppin at btinternet.com Sat Aug 25 14:45:37 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 14:35:38 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> Message-ID: <46D078D1.6080100@btinternet.com> Philippa Cowderoy wrote: > Flippi is... rather minimalistic. And fugly. You can tell it was written > by someone who has trouble getting things done! I get the impression it > did a certain amount of good as a proof of concept and a reminder that > doing things the old-fashioned way still works though. > Ah yes, nothing like a good proof-of-concept implementation. Except that you usually can't do any "real" stuff with it. ;-) Some of you may remember a few years back, it seemed that Java was a programming language invented for implementing Tic-Tac-Toe programs... From andrewcoppin at btinternet.com Sat Aug 25 14:49:24 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 14:39:26 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> Message-ID: <46D079B4.9040700@btinternet.com> Philippa Cowderoy wrote: >>> I have some (very expensive) software called Reaktor. You draw boxes and >>> lines, it does DSP algorithms. You build synthesizers and effects boxes >>> with it. >>> >> That sounds exactly like PureData - you can also do graphics as well >> with PureData, the demo I saw was very cool. Of course, PureData is >> written in C with Haskell as an extension language. >> > > Reaktor is rather nicer to use than PureData though, in that it's designed > to work with mainstream sequencers (or any VST - I work with trackers > myself) and be used by non-hackers. Also, I'm not entirely sure it's fair > to say that it has Haskell as an extension language as such - but Claude's > slides'll give a better explanation than I can. > Reaktor has a few limitations though. 1. It's virtually impossible to debug the thing! (I.e., if your synth doesn't work... good luck working out why.) 2. It lacks looping capabilities. For example, you cannot build a variable-size convolution block - only a fixed-size one. (If you want to draw *a lot* of wires!) If you look through the standard library, you'll find no end of instruments that use a "hack" of using voice polyphony to crudely simulate looping... but it's not too hot. Would be nice if I could build something in Haskell that overcomes these. OTOH, does Haskell have any way to talk to the audio hardware? From allbery at ece.cmu.edu Sat Aug 25 14:50:17 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sat Aug 25 14:41:22 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D07852.4080808@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> <46D07852.4080808@btinternet.com> Message-ID: <68496E26-D2E4-4A12-92AE-238ABFEADEB8@ece.cmu.edu> On Aug 25, 2007, at 14:43 , Andrew Coppin wrote: > Neil Mitchell wrote: >> HI >> >> >>>> Flippi (google: Haskell Flippi) >>>> >>> ...and yet haskell.org uses WikiMedia? (Which is written in >>> something >>> bizzare like Perl...) >>> >> >> Yes, but WikiMedia is a result of years of work, Flippi is a lot >> less. >> Wikipedia uses WikiMedia - its a tried and proven solution. >> > > Well, I guess... > > I just thought, you know, the Tcl wiki is written in Tcl, why isn't > the Haskell wiki written in Haskell? Hey, aren't we trying to tell > people is a *useful* language that people should learn and use? ;-) Are you volunteering to take the time to write and test it? -- 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 andrewcoppin at btinternet.com Sat Aug 25 14:51:34 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 14:41:36 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: References: <46D01785.7070503@btinternet.com> Message-ID: <46D07A36.8010508@btinternet.com> C.M.Brown wrote: >> - A "graphical programming tool". (You add boxes and put in lines, it >> constructs a "program" that you can run.) >> > > I'm not entirely exactly sure what you mean by this. I wasn't especially specific about it, that's true enough. I actually had several different things in mind... > If you mean one can > create programs by creating them visually then perhaps you could consider > Vital: > > http://www.cs.kent.ac.uk/projects/vital/ > > It's a document-centered implementation of Haskell. Allowing one to > display and directly manipulate Haskell data structures in real-time. > Looks very interesting... and very low-tech visuals. :-/ From andrewcoppin at btinternet.com Sat Aug 25 14:56:04 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 14:46:06 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <68496E26-D2E4-4A12-92AE-238ABFEADEB8@ece.cmu.edu> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> <46D07852.4080808@btinternet.com> <68496E26-D2E4-4A12-92AE-238ABFEADEB8@ece.cmu.edu> Message-ID: <46D07B44.1010709@btinternet.com> Brandon S. Allbery KF8NH wrote: > > On Aug 25, 2007, at 14:43 , Andrew Coppin wrote: > >>> Yes, but WikiMedia is a result of years of work, Flippi is a lot less. >>> Wikipedia uses WikiMedia - its a tried and proven solution. >>> >> >> Well, I guess... >> >> I just thought, you know, the Tcl wiki is written in Tcl, why isn't >> the Haskell wiki written in Haskell? Hey, aren't we trying to tell >> people is a *useful* language that people should learn and use? ;-) > > Are you volunteering to take the time to write and test it? > Are you offering to pay me? :-D Oh, wait, "volunteer"... Well, let's put it this way: If I ever get round to making something and it turns out to be any good, you're free to use it... Don't hold your breath... ;-) PS. Do paid Haskell jobs really exist? From haskell at orangesquash.org.uk Sat Aug 25 14:56:59 2007 From: haskell at orangesquash.org.uk (Iain Lane) Date: Sat Aug 25 14:48:01 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D01785.7070503@btinternet.com> References: <46D01785.7070503@btinternet.com> Message-ID: > - Blogging software. (Because there isn't enough of it in the world yet.) In addition (because a little competition can't help ;), I'm going to be experimenting with writing a blog engine for my final year project at Uni next year - 2007/08. Hopefully some good will come of it, i.e. something that people (I) can actually use. It'll probably be more blog less CMS than Hope. At the minute I'm looking at using HAppS for most of it. Should be fun! Iain ps. Sorry for the spam Andrew. From andrewcoppin at btinternet.com Sat Aug 25 14:58:08 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 14:48:13 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: References: <46D01785.7070503@btinternet.com> Message-ID: <46D07BC0.2020708@btinternet.com> Iain Lane wrote: >> - Blogging software. (Because there isn't enough of it in the world yet.) >> > > In addition (because a little competition can't help ;), I'm going to > be experimenting with writing a blog engine for my final year project > at Uni next year - 2007/08. Hopefully some good will come of it, i.e. > something that people (I) can actually use. It'll probably be more > blog less CMS than Hope. At the minute I'm looking at using HAppS for > most of it. Should be fun! > Good luck with that - should be enjoyable at least. ;-) I'm going to have a go at it myself as well. My current blog uses something called "word press", and I don't like it especially much. (It *insists* on chewing up all my carefully applied formatting. And the people providing it have locked it down so there's loads I can't change...) So I'm hoping to write something nice to replace it with. But we'll see... From trebla at vex.net Sat Aug 25 15:02:32 2007 From: trebla at vex.net (Albert Y. C. Lai) Date: Sat Aug 25 14:53:38 2007 Subject: [Haskell-cafe] Parsec is being weird at me In-Reply-To: <46D077CB.5010106@btinternet.com> References: <46D077CB.5010106@btinternet.com> Message-ID: <46D07CC8.1020603@vex.net> Andrew Coppin wrote: > Prelude> :m Text.ParserCombinators.Parsec > Prelude Text.ParserCombinators.Parsec> parseTest (endBy anyToken (char > '#')) "abc#" > Loading package parsec-2.0 ... linking ... done. > parse error at (line 1, column 1): > unexpected "b" > expecting "#" I read the doc and determined that it is perfectly correct behaviour. Hint: anyToken becomes anyChar because your input is [Char]. From stefanor at cox.net Sat Aug 25 15:08:04 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sat Aug 25 14:59:07 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D07852.4080808@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> <46D07852.4080808@btinternet.com> Message-ID: <20070825190804.GA5305@localhost.localdomain> On Sat, Aug 25, 2007 at 07:43:30PM +0100, Andrew Coppin wrote: > Neil Mitchell wrote: >> HI >> >> >>>> Flippi (google: Haskell Flippi) >>>> >>> ...and yet haskell.org uses WikiMedia? (Which is written in something >>> bizzare like Perl...) >>> >> >> Yes, but WikiMedia is a result of years of work, Flippi is a lot less. >> Wikipedia uses WikiMedia - its a tried and proven solution. >> > > Well, I guess... > > I just thought, you know, the Tcl wiki is written in Tcl, why isn't the > Haskell wiki written in Haskell? Hey, aren't we trying to tell people is a > *useful* language that people should learn and use? ;-) Actually, we aren't. You might not have been able to tell, but a core goal of our community is to stay small and avoid success at all costs; our language is not practical, not designed to be practical, and if it ever becomes practical, it will have done so only by a terrible streak of bad luck. Remember, success breeds inertia, and inertia would ruin our fundamental goal of being an agile research language. :) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070825/bec16ae3/attachment.bin From haskell at list.mightyreason.com Sat Aug 25 15:13:03 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Sat Aug 25 15:04:29 2007 Subject: [Haskell-cafe] Re: Parsec is being weird at me In-Reply-To: <46D077CB.5010106@btinternet.com> References: <46D077CB.5010106@btinternet.com> Message-ID: <46D07F3F.50604@list.mightyreason.com> Andrew Coppin wrote: > Anybody want to explain to me why this doesn't work? > > ___ ___ _ > / _ \ /\ /\/ __(_) > / /_\// /_/ / / | | GHC Interactive, version 6.6.1, for Haskell 98. > / /_\\/ __ / /___| | http://www.haskell.org/ghc/ > \____/\/ /_/\____/|_| Type :? for help. > > Loading package base ... linking ... done. > Prelude> :m Text.ParserCombinators.Parsec > Prelude Text.ParserCombinators.Parsec> parseTest (endBy anyToken (char > '#')) "abc#" > Loading package parsec-2.0 ... linking ... done. > parse error at (line 1, column 1): > unexpected "b" > expecting "#" anyToken is singular: it accepts a single token, in this case 'a'. Then endBy expects (char '#') to match and reads 'b' instead and gives the error message. So using (many anyToken) gets further: > Prelude Text.ParserCombinators.Parsec> parseTest (endBy (many anyToken) (char '#')) "abc#" > Loading package parsec-2.0 ... linking ... done. > parse error at (line 1, column 1): > unexpected end of input > expecting "#" > Prelude Text.ParserCombinators.Parsec> parseTe Here (many anyToken) reads all of "abc#" and then endBy wants to read (char '#') and get the end of input instead. So the working version of endBy is thus: > Prelude Text.ParserCombinators.Parsec> parseTest (endBy (many (noneOf "#")) (char '#')) "abc#" > ["abc"] Or you may need to not use endBy... From andrewcoppin at btinternet.com Sat Aug 25 15:16:10 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 15:06:12 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <20070825190804.GA5305@localhost.localdomain> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> <46D07852.4080808@btinternet.com> <20070825190804.GA5305@localhost.localdomain> Message-ID: <46D07FFA.9030000@btinternet.com> Stefan O'Rear wrote: > On Sat, Aug 25, 2007 at 07:43:30PM +0100, Andrew Coppin wrote: > >> Hey, aren't we trying to tell people is a >> *useful* language that people should learn and use? ;-) >> > > Actually, we aren't. You might not have been able to tell, but a core > goal of our community is to stay small and avoid success at all costs; > our language is not practical, not designed to be practical, and if it > ever becomes practical, it will have done so only by a terrible streak > of bad luck. Remember, success breeds inertia, and inertia would ruin > our fundamental goal of being an agile research language. > Heh. Well, that told me... o_O Maybe *this* is why everybody else thinks I'm an idiot for using Haskell... :-( PS. Wasn't one of the explicit design goals "to design a standardised language for teaching FP"? From andrewcoppin at btinternet.com Sat Aug 25 15:18:29 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 15:08:34 2007 Subject: [Haskell-cafe] Re: Parsec is being weird at me In-Reply-To: <46D07F3F.50604@list.mightyreason.com> References: <46D077CB.5010106@btinternet.com> <46D07F3F.50604@list.mightyreason.com> Message-ID: <46D08085.6050205@btinternet.com> ChrisK wrote: > Andrew Coppin wrote: > >> Anybody want to explain to me why this doesn't work? >> >> ___ ___ _ >> / _ \ /\ /\/ __(_) >> / /_\// /_/ / / | | GHC Interactive, version 6.6.1, for Haskell 98. >> / /_\\/ __ / /___| | http://www.haskell.org/ghc/ >> \____/\/ /_/\____/|_| Type :? for help. >> >> Loading package base ... linking ... done. >> Prelude> :m Text.ParserCombinators.Parsec >> Prelude Text.ParserCombinators.Parsec> parseTest (endBy anyToken (char >> '#')) "abc#" >> Loading package parsec-2.0 ... linking ... done. >> parse error at (line 1, column 1): >> unexpected "b" >> expecting "#" >> > > anyToken is singular: it accepts a single token, in this case 'a'. > > Then endBy expects (char '#') to match and reads 'b' instead and gives the error > message. > > So using (many anyToken) gets further: > > >> Prelude Text.ParserCombinators.Parsec> parseTest (endBy (many anyToken) (char '#')) "abc#" >> Loading package parsec-2.0 ... linking ... done. >> parse error at (line 1, column 1): >> unexpected end of input >> expecting "#" >> Prelude Text.ParserCombinators.Parsec> parseTe >> > > Here (many anyToken) reads all of "abc#" and then endBy wants to read (char '#') > and get the end of input instead. > > So the working version of endBy is thus: > > >> Prelude Text.ParserCombinators.Parsec> parseTest (endBy (many (noneOf "#")) (char '#')) "abc#" >> ["abc"] >> > > Or you may need to not use endBy... > But hang on a minute... "many" parses 0 or more occurrances of an item. "sepBy" parses 0 or more occurrances of an item, seperated by another item. "endBy" parses 0 or more occurrances of an item, terminated by another item. "sepEndBy" parses 0 or more occurrances of an item, seperated *and* terminated by another item. ...except that "endBy" doesn't seem to be working right. :-S From andrewcoppin at btinternet.com Sat Aug 25 15:37:28 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 15:27:30 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D07A36.8010508@btinternet.com> References: <46D01785.7070503@btinternet.com> <46D07A36.8010508@btinternet.com> Message-ID: <46D084F8.6020207@btinternet.com> Andrew Coppin wrote: > C.M.Brown wrote: >> If you mean one can >> create programs by creating them visually then perhaps you could >> consider >> Vital: >> >> http://www.cs.kent.ac.uk/projects/vital/ >> >> It's a document-centered implementation of Haskell. Allowing one to >> display and directly manipulate Haskell data structures in real-time. >> > > Looks very interesting... and very low-tech visuals. :-/ Hang on a minute... it's written in Java... and it can run Haskell code...? o_O Now that's interesting! (Re. the other thread about "we should have an automatic expression reducing program"...) From bf3 at telenet.be Sat Aug 25 15:37:26 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sat Aug 25 15:28:20 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <20070825190804.GA5305@localhost.localdomain> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> <46D07852.4080808@btinternet.com> <20070825190804.GA5305@localhost.localdomain> Message-ID: <002001c7e74f$5e0f4480$1a2dcd80$@be> >> *useful* language that people should learn and use? ;-) >Actually, we aren't. You might not have been able to tell, >but a core goal of our community is to stay small and avoid >success at all costs; our language is not practical, >not designed to be practical, and if it ever becomes practical, >it will have done so only by a terrible streak of bad luck. >Remember, success breeds inertia, and inertia would ruin >our fundamental goal of being an agile research language. Well, IMHO the only reasons why Haskell is not a language for the masses are: - No marketing. If a company as big as Microsoft would decide that Haskell is to become the standard language, then it would be so. - Ancient IDEs. When someone comes from Eclipse or Visual Studio it feels one is teleported back to the stone ages. Although Visual Haskell looks promising, it seems to be in the pre-beta stage. - Although the documentation is very good, it is rather bulky, which can scare away newbies. - As Haskell is currently used a lot by people with an average IQ of 160, the available packages and programming approaches are not easily absorbed for the average software engineer with an IQ of 120 ;-) However, once you take your time to dig deep into the matter, one often sees the beauty behind it. But many newbies just feel really stupid when they look at Haskell code :) I certainly did and still do, but fortunately I know I'm not very clever, so that's okay ;) - I haven't looked at the debuggers, but I've heared Haskell is really hard to debug. Anyway, although my IQ is far below 160, I find Haskell the most exciting language I have ever learned (and I've only scratched the bare surface of the language) Cheers, Peter Verswyvelen From stefanor at cox.net Sat Aug 25 15:37:59 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sat Aug 25 15:29:05 2007 Subject: [Haskell-cafe] Re: Parsec is being weird at me In-Reply-To: <46D08085.6050205@btinternet.com> References: <46D077CB.5010106@btinternet.com> <46D07F3F.50604@list.mightyreason.com> <46D08085.6050205@btinternet.com> Message-ID: <20070825193759.GA5402@localhost.localdomain> On Sat, Aug 25, 2007 at 08:18:29PM +0100, Andrew Coppin wrote: > But hang on a minute... > > "many" parses 0 or more occurrances of an item. > > "sepBy" parses 0 or more occurrances of an item, seperated by another item. > > "endBy" parses 0 or more occurrances of an item, terminated by another > item. > > "sepEndBy" parses 0 or more occurrances of an item, seperated *and* > terminated by another item. > > ...except that "endBy" doesn't seem to be working right. :-S There is one other little bit of documented behavior. Parsec's normal combinators only parse LL(1) grammars. Consult any work on formal languages for the exact meaning and all the consequences, however for this example it serves to note that after seeing abc, the single character of lookahead '#' is not sufficient to determine the correct parse. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070825/c7bed87d/attachment.bin From bf3 at telenet.be Sat Aug 25 15:41:27 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sat Aug 25 15:32:20 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D084F8.6020207@btinternet.com> References: <46D01785.7070503@btinternet.com> <46D07A36.8010508@btinternet.com> <46D084F8.6020207@btinternet.com> Message-ID: <002101c7e74f$ed50da00$c7f28e00$@be> I tried vital, and at first sight it is very nice, but they only support a very limited subset of Haskell, perform no type checking at all, don't support the indent rule, etc... Anyway it is an amazing piece of work. Regarding your question about visual programming, GEM Cutter from the Open Quark Framework is also nice. http://labs.businessobjects.com/cal. But they also wrote their own Haskell98 (with some Hugs extension) compiler in... Java. Cheers, Peter Verswyvelen -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Andrew Coppin Sent: Saturday, August 25, 2007 9:37 PM To: haskell-cafe@haskell.org Subject: Re: [Haskell-cafe] Ideas Andrew Coppin wrote: > C.M.Brown wrote: >> If you mean one can >> create programs by creating them visually then perhaps you could >> consider >> Vital: >> >> http://www.cs.kent.ac.uk/projects/vital/ >> >> It's a document-centered implementation of Haskell. Allowing one to >> display and directly manipulate Haskell data structures in real-time. >> > > Looks very interesting... and very low-tech visuals. :-/ Hang on a minute... it's written in Java... and it can run Haskell code...? o_O Now that's interesting! (Re. the other thread about "we should have an automatic expression reducing program"...) _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From andrewcoppin at btinternet.com Sat Aug 25 15:49:02 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 15:39:04 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <002101c7e74f$ed50da00$c7f28e00$@be> References: <46D01785.7070503@btinternet.com> <46D07A36.8010508@btinternet.com> <46D084F8.6020207@btinternet.com> <002101c7e74f$ed50da00$c7f28e00$@be> Message-ID: <46D087AE.9070000@btinternet.com> Peter Verswyvelen wrote: > I tried vital, and at first sight it is very nice, but they only support a > very limited subset of Haskell, perform no type checking at all, don't > support the indent rule, etc... Anyway it is an amazing piece of work. > > Regarding your question about visual programming, GEM Cutter from the Open > Quark Framework is also nice. http://labs.businessobjects.com/cal. But they > also wrote their own Haskell98 (with some Hugs extension) compiler in... > Java. > > Cheers, > Peter Verswyvelen > Vital seems to have a really damn nice concept behind it. The visuals don't look quite so hot though... ;-) If I could figure out how to do the whole "drag boxes around, draw lines" stuff with Gtk2hs, I might have a go at bettering this myself... but that's unlikely. GEM Cutter also falls into the category of "hey, that's interesting, I should go find out about this stuff..." ;-) From qdunkan at gmail.com Sat Aug 25 15:54:15 2007 From: qdunkan at gmail.com (Evan Laforge) Date: Sat Aug 25 15:45:18 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D079B4.9040700@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> Message-ID: <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> > Reaktor has a few limitations though. > > 1. It's virtually impossible to debug the thing! (I.e., if your synth > doesn't work... good luck working out why.) > > 2. It lacks looping capabilities. For example, you cannot build a > variable-size convolution block - only a fixed-size one. (If you want to > draw *a lot* of wires!) If you look through the standard library, you'll > find no end of instruments that use a "hack" of using voice polyphony to > crudely simulate looping... but it's not too hot. > > Would be nice if I could build something in Haskell that overcomes > these. OTOH, does Haskell have any way to talk to the audio hardware? Nyquist is a music language from a whlie back that I liked (in theory, not so much in practice). It has a functional model in that "instruments" are just functions that return sample streams, so there's no difference between signal processing and signal generating functions (or orchestra and score, for the csounders out there). This was made efficient by lazily evaluating the streams and some custom hackery where it would e.g. notice that one signal going into (+) had ended and simply unlink the entire operation from the call graph, and some gc hackery to reclaim sound blocks quickly. The other interesting feature was "behaviours" which were just dynamically scoped variables that would propagate down to the nearest function that cared to interpret them, e.g. (transpose 5 (seq (melody 1) (melody 2))) would transpose the tones generated by (melody) by setting a dynamic variable that would later be read by the underlying oscillators or whatever that melody used. "seq" used the mechanism to shift or scale the beginnings end endings of notes. It was also more powerful than e.g. csound, supecollider, or reaktor style languages because in the former you have to compile a static call graph (the "orchestra") and then "play" it with signals dynamically (the "score"), whereas in nyquist there's no orchestra and score division. The disadvantage is that the immutable signals made it hard to implement real-time synthesis. The practical problem was that it was implemented in a hacked up XLisp which was primitive and hard to debug. Added to that, you had to be careful to wrap signals in functions or macros so the eager interpreter wouldn't evaluate the whole signal and kill performance. To get this back to haskell, at the time I wondered if a more natural implementation might be possible in haskell, seeing as it was more naturally lazy. Not sure how to implement the behaviours though (which were simply macros around a let of *dynamic-something*). I'm sure people have done plenty of signal processing, and there's always haskore... but what about a sound generation language like csound or clm or nyquist? It could fit in nicely below haskore. Also, as another reaktor user I agree it would have been so much nicer were it simply a real language. Drawing those boxes and lines and the complete lack of abstraction (beyond copy and paste) is a real pain. Supercollider is more promising in that way, but less polished of course. It also has that two-level imperative model though where you create and modify your signal graph with imperative techniques, then run it, rather than your program *being* the signal graph. From andrewcoppin at btinternet.com Sat Aug 25 15:56:34 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 15:46:34 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <002001c7e74f$5e0f4480$1a2dcd80$@be> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> <46D07852.4080808@btinternet.com> <20070825190804.GA5305@localhost.localdomain> <002001c7e74f$5e0f4480$1a2dcd80$@be> Message-ID: <46D08972.5010500@btinternet.com> Peter Verswyvelen wrote: > Well, IMHO the only reasons why Haskell is not a language for the masses > are: > > - No marketing. If a company as big as Microsoft would decide that Haskell > is to become the standard language, then it would be so. > See, for example, Java... > - Ancient IDEs. > Can't comment. Every IDE I've used recently sucked anyway. ;-) > - As Haskell is currently used a lot by people with an average IQ of 160, > the available packages and programming approaches are not easily absorbed > for the average software engineer with an IQ of 120 ;-) However, once you > take your time to dig deep into the matter, one often sees the beauty behind > it. But many newbies just feel really stupid when they look at Haskell code > :) I certainly did and still do, but fortunately I know I'm not very clever, > so that's okay ;) > I have an IQ of 103. Apparently. (This makes me officially the most stupid person on the povray.off-topic newsgroup...) > - I haven't looked at the debuggers, but I've heared Haskell is really hard > to debug. > OTOH, Haskell requires less debugging in the first place. ;-) > Anyway, although my IQ is far below 160, I find Haskell the most exciting > language I have ever learned (and I've only scratched the bare surface of > the language) > Indeed. Personally, I don't *want* Haskell to be a research language. I want Haskell to be The Next Big Thing. I want to see newspapers full of people trying to recruit Haskell programmers rather than all this C / C++ / Java stuff. ;-) Still, it will never happen... Would be nice if I could convince people that Haskell isn't just for idiots though. From andrewcoppin at btinternet.com Sat Aug 25 16:02:29 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 15:52:33 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> Message-ID: <46D08AD5.80102@btinternet.com> Evan Laforge wrote: > To get this back to haskell, at the time I wondered if a more natural > implementation might be possible in haskell, seeing as it was more > naturally lazy. Not sure how to implement the behaviours though > (which were simply macros around a let of *dynamic-something*). I'm > sure people have done plenty of signal processing, and there's always > haskore... but what about a sound generation language like csound or > clm or nyquist? It could fit in nicely below haskore. > Indeed, you can write certain DSP algorithms beautifully in Haskell. Now, if only it could talk to the audio hardware... (Or just use common file formats even.) > Also, as another reaktor user I agree it would have been so much nicer > were it simply a real language. Drawing those boxes and lines and the > complete lack of abstraction (beyond copy and paste) is a real pain. > Supercollider is more promising in that way, but less polished of > course. It also has that two-level imperative model though where you > create and modify your signal graph with imperative techniques, then > run it, rather than your program *being* the signal graph. > Reaktor has abstraction. You can build a gizmo that does something useful, call it a macro, and then use it whereever you want. If you want to build a gizmo that takes a siganl "x" and computes "8*x*x*x - 8*x*x + 1" (i.e., the 4th Chebyshev polynomial), you've going to have to draw *a lot* of wires! It would be nice if there was some feature for quickly building complicated chunks of pure algebra like that. It would also be nice if there were some way to *programmatically* construct the graph... but never mind. (Maybe in Reaktor 6?) From andrewcoppin at btinternet.com Sat Aug 25 16:04:55 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sat Aug 25 15:54:56 2007 Subject: [Haskell-cafe] Re: Parsec is being weird at me In-Reply-To: <20070825193759.GA5402@localhost.localdomain> References: <46D077CB.5010106@btinternet.com> <46D07F3F.50604@list.mightyreason.com> <46D08085.6050205@btinternet.com> <20070825193759.GA5402@localhost.localdomain> Message-ID: <46D08B67.7050108@btinternet.com> Stefan O'Rear wrote: > On Sat, Aug 25, 2007 at 08:18:29PM +0100, Andrew Coppin wrote: > >> But hang on a minute... >> >> "many" parses 0 or more occurrances of an item. >> >> "sepBy" parses 0 or more occurrances of an item, seperated by another item. >> >> "endBy" parses 0 or more occurrances of an item, terminated by another >> item. >> >> "sepEndBy" parses 0 or more occurrances of an item, seperated *and* >> terminated by another item. >> >> ...except that "endBy" doesn't seem to be working right. :-S >> > > There is one other little bit of documented behavior. Parsec's normal > combinators only parse LL(1) grammars. Consult any work on formal > languages for the exact meaning and all the consequences, however for > this example it serves to note that after seeing abc, the single > character of lookahead '#' is not sufficient to determine the correct > parse. > Heh. Starting to wish I had a significantly higher IQ... I thought the whole *purpose* of the endBy combinator was to keep applying one parser until the other one succeeds? In the example I posted, the two parsers are quite trivial. But in the real problem I actually want to solve, they are very non-trivial... From qdunkan at gmail.com Sat Aug 25 16:14:24 2007 From: qdunkan at gmail.com (Evan Laforge) Date: Sat Aug 25 16:05:26 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D08AD5.80102@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> <46D08AD5.80102@btinternet.com> Message-ID: <2518b95d0708251314h6f65ee3fl3e45b585ceea2b58@mail.gmail.com> > Indeed, you can write certain DSP algorithms beautifully in Haskell. > Now, if only it could talk to the audio hardware... (Or just use common > file formats even.) Oh, that's easy. I wrote an FFI interface to portaudio a while back to write a delay-looping type utility in haskell. It was pretty trivial. You could do the same for libsndfile or whatever. The only thing I'm uncertain about is whether it would have good enough time and space performance. All the real work is writing yet another set of basic envelope, oscillator, and fft primitives. You *should* be able to go all the way down to the samples in pure haskell though, which would be more elegant than those other languages :) > Reaktor has abstraction. You can build a gizmo that does something > useful, call it a macro, and then use it whereever you want. Well, except that if you then change your macro you have re-copy it into every instrument or ensemble or other macro that uses it. So I consider the macros basically a copy and paste mechanism. From cmb21 at kent.ac.uk Sat Aug 25 16:58:57 2007 From: cmb21 at kent.ac.uk (C.M.Brown) Date: Sat Aug 25 16:50:16 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <002101c7e74f$ed50da00$c7f28e00$@be> References: <46D01785.7070503@btinternet.com> <46D07A36.8010508@btinternet.com> <46D084F8.6020207@btinternet.com> <002101c7e74f$ed50da00$c7f28e00$@be> Message-ID: > I tried vital, and at first sight it is very nice, but they only support a > very limited subset of Haskell, perform no type checking at all, don't > support the indent rule, etc... Anyway it is an amazing piece of work. I believe that type-sensitive manipulation was certainly being investigated; however, I can't confirm as to how far it *was* investigated. What intriged me mostly was how it can display infinite data structures lazily. I think it's certainly a great tool for teaching some aspects of functional programming: helping newbies to understand and define data structures, say. Chris. From jerzy.karczmarczuk at info.unicaen.fr Sat Aug 25 17:36:01 2007 From: jerzy.karczmarczuk at info.unicaen.fr (jerzy.karczmarczuk@info.unicaen.fr) Date: Sat Aug 25 17:26:25 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <2518b95d0708251314h6f65ee3fl3e45b585ceea2b58@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> <46D08AD5.80102@btinternet.com> <2518b95d0708251314h6f65ee3fl3e45b585ceea2b58@mail.gmail.com> Message-ID: Evan Laforge writes: >> Indeed, you can write certain DSP algorithms beautifully in Haskell. >> Now, if only it could talk to the audio hardware... (Or just use common >> file formats even.) > > Oh, that's easy. I wrote an FFI interface to portaudio a while back > to write a delay-looping type utility in haskell. It was pretty > trivial. You could do the same for libsndfile or whatever. > > The only thing I'm uncertain about is whether it would have good > enough time and space performance. All the real work is writing yet > another set of basic envelope, oscillator, and fft primitives. You > *should* be able to go all the way down to the samples in pure haskell > though, which would be more elegant than those other languages :) == Well, if you want to see what you can do with a lazy functional language, not necessarily Haskell, but Clean (sorry for advertizing a competitor on this list...), perhaps have a look on my PADL paper http://users.info.unicaen.fr/~karczma/arpap/cleasyn.pdf I generated .wav files as output, from lazy streams, so the sound was off-line. My ambition was to code in a very, very compact way some musical instruments, with looping replaced by co-recursion. It cannot be extremely efficient, but it seems quite elegant and powerful. Jerzy Karczmarczuk From chris.casinghino at gmail.com Sat Aug 25 17:37:28 2007 From: chris.casinghino at gmail.com (Chris Casinghino) Date: Sat Aug 25 17:28:29 2007 Subject: [Haskell-cafe] Re: Parsec is being weird at me In-Reply-To: References: <46D077CB.5010106@btinternet.com> <46D07F3F.50604@list.mightyreason.com> <46D08085.6050205@btinternet.com> <20070825193759.GA5402@localhost.localdomain> <46D08B67.7050108@btinternet.com> Message-ID: The following two messages didn't make it to the list the first time because I sent from the wrong address. oops! Hopefully these answer the question. Message 1: On 8/25/07, Andrew Coppin wrote: > Stefan O'Rear wrote: > > There is one other little bit of documented behavior. Parsec's normal > > combinators only parse LL(1) grammars. Consult any work on formal > > languages for the exact meaning and all the consequences, however for > > this example it serves to note that after seeing abc, the single > > character of lookahead '#' is not sufficient to determine the correct > > parse. > > > > I thought the whole *purpose* of the endBy combinator was to keep > applying one parser until the other one succeeds? I don't think this is a lookahead problem, but rather just a misreading of the spec of endBy. Here it is: (endBy p sep) parses zero or more occurrences of p, seperated and ended by sep. Returns a list of values returned by p. The key text is "seperated and ended by sep". Not just ended by. Of course, the lookahead restriction is real, so just writing do {s <- many anyToken; char '#'; return s} won't work either. I'm not sure there is a built in combinator for what you want, but you could perhaps write: do {s <- many (satisfy (/= '#')); char '#'; return s} perhaps there is a more efficient way. --Chris ------ Message 2: > > I'm not sure there is a built in combinator for what you want, > I guess I should have looked harder. What you want is manyTill: "manyTill :: GenParser tok st a -> GenParser tok st end -> GenParser tok st [a] (manyTill p end) applies parser p zero or more times until parser end succeeds. Returns the list of values returned by p." --Chris From flippa at flippac.org Sat Aug 25 17:51:13 2007 From: flippa at flippac.org (Philippa Cowderoy) Date: Sat Aug 25 17:42:22 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D079B4.9040700@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> Message-ID: On Sat, 25 Aug 2007, Andrew Coppin wrote: > Would be nice if I could build something in Haskell that overcomes these. > OTOH, does Haskell have any way to talk to the audio hardware? > It would definitely be nice if someone wrote a binding to the VST SDK or a wrapper for it. Unfortunately I suspect it's too windows-specific for most of those on the list, and there isn't a sufficiently good portable and widely-used/available alternative. -- flippa@flippac.org "The reason for this is simple yet profound. Equations of the form x = x are completely useless. All interesting equations are of the form x = y." -- John C. Baez From bf3 at telenet.be Sat Aug 25 18:05:31 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sat Aug 25 17:57:12 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: References: <46D01785.7070503@btinternet.com> <46D07A36.8010508@btinternet.com> <46D084F8.6020207@btinternet.com> <002101c7e74f$ed50da00$c7f28e00$@be> Message-ID: <002801c7e764$0d80f710$2882e530$@be> > What intriged me mostly was how it can display infinite data structures > lazily. I think it's certainly a great tool for teaching some aspects of > functional programming: helping newbies to understand and define data > Structures, say. Definitely! It's really cool stuff. But something like that for real Haskell (e.g. GHC) would be even better :) I could be an offline downloadable application. It would be a very nice tool: create postscript (or PDF, or LaTex, whatever rich text format) documents with Haskell "boxes" inside. Real literate programming... Oh well ;) From cmb21 at kent.ac.uk Sat Aug 25 18:12:25 2007 From: cmb21 at kent.ac.uk (C.M.Brown) Date: Sat Aug 25 18:04:03 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <002801c7e764$0d80f710$2882e530$@be> References: <46D01785.7070503@btinternet.com> <46D07A36.8010508@btinternet.com> <46D084F8.6020207@btinternet.com> <002101c7e74f$ed50da00$c7f28e00$@be> <002801c7e764$0d80f710$2882e530$@be> Message-ID: > Definitely! It's really cool stuff. But something like that for real Haskell > (e.g. GHC) would be even better :) I could be an offline downloadable > application. It would be a very nice tool: create postscript (or PDF, or > LaTex, whatever rich text format) documents with Haskell "boxes" inside. > Real literate programming... Oh well ;) I would personally say Haskell 98 is "real" Haskell (well, until Haskell Prime comes out). It becomes difficult for tool developers to cater for non-standard languages; Haskell is quite complicated enough without having to cater for all the little nuances and idiomatic extensions that are constantly added with each release of a compiler. I believe it does work as an offline downloadable tool... http://www.cs.kent.ac.uk/projects/vital/install/index.html Chris. From bf3 at telenet.be Sat Aug 25 18:14:23 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sat Aug 25 18:05:17 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) Message-ID: <002901c7e765$4b076f00$e1164d00$@be> Game developers are really struggling to get performance out of the Playstation 3 console. This console has a single PowerPC CPU with 6 Cell SPU coprocessors, all running at 3.3GHz. These SPUs have 256KB very high speed local RAM, and data from the 512MB main memory can stream in and out via DMA into these SPUs. The problem is that with imperative approaches this is a nightmare to manage.. It would be a very cool project to show that Haskell could run on such a platform, making it easier to take advance of its awesome power J Oh well, I'm just brainstorming here. Cheers, Peter BTW: This Cell platform also seemed to be offered for scientific computing in standard workstation PCs, so it would not just be for the Playstation 3. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070826/ff342166/attachment-0001.htm From radoslawg at gmail.com Sat Aug 25 18:19:25 2007 From: radoslawg at gmail.com (=?UTF-8?Q?Rados=C5=82aw_Grzanka?=) Date: Sat Aug 25 18:10:27 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <002901c7e765$4b076f00$e1164d00$@be> References: <002901c7e765$4b076f00$e1164d00$@be> Message-ID: <9d55dbaf0708251519n24fcb6b9kf89a350f75ea1ac4@mail.gmail.com> > It would be a very cool project to show that Haskell could run on such a > platform, making it easier to take advance of its awesome power J It's funny. But 5 minutes ago I was thinking: did anyone compiled haskell application for Palm (m68k and/or Arm) that runs on Palm OS? I can literally quote you: "It would be a very cool project to show that Haskell could run on such a platform". Ofcourse this is completly other way around in terms of power and memory. :) But anyway, did anyone do it? Cheers, Radek. -- Codeside: http://codeside.org/ Przedszkole Miejskie nr 86 w Lodzi: http://www.pm86.pl/ From marcotmarcot at gmail.com Sat Aug 25 18:31:00 2007 From: marcotmarcot at gmail.com (=?ISO-8859-1?Q?Marco_T=FAlio_Gontijo_e_Silva?=) Date: Sat Aug 25 18:22:00 2007 Subject: [Haskell-cafe] Text.Xhtml.Strict Message-ID: Hello there. I don't know if it's off topic, but I don't know where else to ask. I've been using Text.Xhtml.Strict, and I'm wondering why the functions are mostly Html -> Html and not HTML a => a -> Html, or something similar. If they were like this, << and toHtml would be not needed, what would make it simpler to call the functions with arguments that are not Html. The question is specific to this library, but I think it's a very general one: isn't it better to have more generic functions with type changing inside? It seems to me that it would make things better from the users point of view. What do you think? -- Marco T?lio Gontijo e Silva Blog: http://marcotmarcot.blogspot.com/ P?gina: http://marcotmarcot.googlepages.com/ Correio, Jabber, GTalk, MSN: marcotmarcot@gmail.com IRC: marcotmarcot@irc.freenode.net IRC: marcotmarcot@irc.indymedia.org Skype: marcotmarcot Telefone: 33346720 Celular: 98116720 Endere?o: Rua Paula C?ndido, 257/201 Gutierrez 30430-260 Belo Horizonte/MG Brasil From dbast0s at yahoo.com.br Sat Aug 25 19:33:56 2007 From: dbast0s at yahoo.com.br (Daniel C. Bastos) Date: Sat Aug 25 19:31:05 2007 Subject: [Haskell-cafe] :, infix operator, infix constructor, et cetera Message-ID: There is something called infix constructors and something else called infix operators. I'm guessing that an infix operator is really a function, and an infix constructor I don't know what it is. How would you guys describe them? (*) More questions. I learned how to define (++), and then I wanted to see how (:) would be defined. The Haskell 98 Report mentions that -- The (:) operator is built-in syntax, and cannot legally be given -- a fixity declaration; but its fixity is given by: -- infixr 5 : What does ``built-in syntax'' mean? Paul Hudak, in ``The Haskell School of Expression'' mentions that he defines (:) legally, in Appendix A. After writing data [a] = [] | a : [a] -- more pseudo-code infixr 5 : and making a couple of observations about it, he writes: ``The way (:) is defined here is actually legal syntax. Infix constructors are permitted in *data* declarations, and are distinguished from infix operators (for pattern-matching purposes) by the fact that they must begin with a colon (a property trivially satisfied by ":").'' So I'm not sure what ``legal syntax'' and ``pseudo-code'' exactly mean. The program > module Main where > data [a] = [] | a : [a] > infixr 5 : > main = putStrLn "hello world" gives %runhugs.exe Colon.lhs runhugs: Error occurred ERROR "Colon.lhs":3 - Syntax error in data declaration (unexpected `[') (*) The 5. What does that 5 do in ``infixr 5 :''? From jeremy.shaw at linspireinc.com Sat Aug 25 20:07:30 2007 From: jeremy.shaw at linspireinc.com (Jeremy Shaw) Date: Sat Aug 25 19:58:38 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <9d55dbaf0708251519n24fcb6b9kf89a350f75ea1ac4@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <9d55dbaf0708251519n24fcb6b9kf89a350f75ea1ac4@mail.gmail.com> Message-ID: <6433dupp.wl%jeremy.shaw@linspireinc.com> At Sun, 26 Aug 2007 00:19:25 +0200, =?UTF-8?Q?Rados=C5=82aw_Grzanka?= wrote: > It's funny. But 5 minutes ago I was thinking: did anyone compiled > haskell application for Palm (m68k and/or Arm) that runs on Palm OS? I have looked into doing this in the past. Historically speaking, the first obstacle is all the Haskell compilers I looked at required libgmp -- which I could not get to compile for PalmOS. libgmp was used primarily (entirely?) for supporting the Integer data type. I believe there is now one (or more?) pure Haskell implementations of Integer -- so, it should be easier to remove the libgmp dependency. I also heard wild rumors that a future version of GHC might have backend that generates pure ANSI C. In theory, that should make it much easier to target PalmOS. I have never written anything for PalmOS, aside from some scheme programs using LispMe, but I think it might be a pretty unusual platform. For example, it seems like applications can not access for than 4k of ram without some hackery. Another option would be to port the yhi bytecode interpreter to run on PalmOS. I tried this, but I ran into three problems: 1. libgmp dependency 2. build system requires Python (scons). 3. I 'upgraded' to a Nokia 770, and suddenly did not care about PalmOS There is also an old project to port nhc98 to PalmOS -- not sure if it is still active, or how far they got. AFAIK, nothing was ever released. If PalmOS is really un-POSIX compatible, it may be easier to write a custom compiler that compiles YHC or GHC Core to PalmOS. Well, the first time you try to write a compiler from Core -> ??? is difficult, but the second time around is a lot easier ;) j. From ndmitchell at gmail.com Sat Aug 25 20:11:49 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Sat Aug 25 20:02:50 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <6433dupp.wl%jeremy.shaw@linspireinc.com> References: <002901c7e765$4b076f00$e1164d00$@be> <9d55dbaf0708251519n24fcb6b9kf89a350f75ea1ac4@mail.gmail.com> <6433dupp.wl%jeremy.shaw@linspireinc.com> Message-ID: <404396ef0708251711p5a0f6b43i8cdcb1e3f52390ac@mail.gmail.com> Hi > Another option would be to port the yhi bytecode interpreter to run on > PalmOS. I tried this, but I ran into three problems: > > 1. libgmp dependency This is no longer an issue, we now have a flag to not require libgmp, which makes type Integer = Int > 2. build system requires Python (scons). Still alas, but we'd like to fix it. > If PalmOS is really un-POSIX compatible, it may be easier to write a > custom compiler that compiles YHC or GHC Core to PalmOS. Well, the > first time you try to write a compiler from Core -> ??? is > difficult, but the second time around is a lot easier ;) We have compilers from Yhc Core to everything nowadays. One to Lisp shouldn't be too tricky, if someone wanted to take that direction. Thanks Neil From derek.a.elkins at gmail.com Sat Aug 25 20:24:45 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Sat Aug 25 20:15:52 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> Message-ID: <1188087885.13256.0.camel@derek-laptop> On Sat, 2007-08-25 at 22:51 +0100, Philippa Cowderoy wrote: > On Sat, 25 Aug 2007, Andrew Coppin wrote: > > > Would be nice if I could build something in Haskell that overcomes these. > > OTOH, does Haskell have any way to talk to the audio hardware? > > > > It would definitely be nice if someone wrote a binding to the VST SDK or a > wrapper for it. Unfortunately I suspect it's too windows-specific for most > of those on the list, and there isn't a sufficiently good portable and > widely-used/available alternative. > I recently wrote a binding to LADSPA. I just need to finish packaging it and upload it to Hackage. From derek.a.elkins at gmail.com Sat Aug 25 20:28:12 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Sat Aug 25 20:19:21 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> <46D08AD5.80102@btinternet.com> <2518b95d0708251314h6f65ee3fl3e45b585ceea2b58@mail.gmail.com> Message-ID: <1188088092.13256.4.camel@derek-laptop> On Sat, 2007-08-25 at 23:36 +0200, jerzy.karczmarczuk@info.unicaen.fr wrote: > Evan Laforge writes: > > >> Indeed, you can write certain DSP algorithms beautifully in Haskell. > >> Now, if only it could talk to the audio hardware... (Or just use common > >> file formats even.) > > > > Oh, that's easy. I wrote an FFI interface to portaudio a while back > > to write a delay-looping type utility in haskell. It was pretty > > trivial. You could do the same for libsndfile or whatever. > > > > The only thing I'm uncertain about is whether it would have good > > enough time and space performance. All the real work is writing yet > > another set of basic envelope, oscillator, and fft primitives. You > > *should* be able to go all the way down to the samples in pure haskell > > though, which would be more elegant than those other languages :) > > == > > Well, if you want to see what you can do with a lazy functional language, > not necessarily Haskell, but Clean (sorry for advertizing a competitor > on this list...), perhaps have a look on my PADL paper > > http://users.info.unicaen.fr/~karczma/arpap/cleasyn.pdf > > I generated .wav files as output, from lazy streams, so the sound was > off-line. > My ambition was to code in a very, very compact way some musical > instruments, with looping replaced by co-recursion. It cannot be extremely > efficient, but it seems quite elegant and powerful. Last week I did exactly that. Using lazy streams and a quickly hacked up .wav file output, I played with some of the extended Karplus-Strong plucked string/drum synthesis algorithms. From bayer at cpw.math.columbia.edu Sun Aug 26 00:33:25 2007 From: bayer at cpw.math.columbia.edu (Dave Bayer) Date: Sun Aug 26 00:25:11 2007 Subject: [Haskell-cafe] "GHC from source" makes a great hardware test Message-ID: <60C7B0FB-AE2F-4E88-92D7-BD2EF181E22E@math.columbia.edu> I recently did the classic "push a shopping cart down the aisle at Fry's" to build a Core 2 Quad computer, with Linux swap and a soft raid array spread across three 750 GB sata hard disks. I had some potential "first build" issues, notably a mishap with the lawn of copper grass that passes for a 775 cpu socket, followed by an hour of brain-surgery with a magnifying glass and a tiny screwdriver. I was very curious to test the stability of this system when it booted up after all; the best hardware test I could think of was multiple processes building GHC from source, with each iteration using the previous GHC binary as the compiler for the new build. Four iterating GHC builds in parallel is enough to peg all four cores at 100% indefinitely, with considerable disk activity to the soft raid array. The most I had going at once was 30 GHC builds; the system remained responsive enough for me to gracefully change my mind in the morning. Building multiple copies of GHC generates a lot of heat; going full tilt, the computer was drawing 220 watts at the wall. I don't use air conditioning for my summer office, so I ended up taping a small bathroom exhaust fan and dimmer switch into the back of a cardboard box, to collect the hot air from the back of the computer and send it out the window through a dryer hose. This kept the cores at 40 C (the enclosure itself has all possible fans) and my office cooler. A previous passive dryer hose arrangement kept the computer at 50 C, which is cooler than my MacBook cpu at full tilt, but I like to build things. Cardboard is an awesome quick prototyping material. Someone else in the same boat might save some time by modifying my Bash script. I ran hundreds of GHC builds without a mishap, and concluded that my system is stable. > #!/bin/bash > > # ghc-test.sh > > # Bash script to iteratively build ghc from source > # http://www.haskell.org/ghc > > # usage: > # ghc-test iters [ghc] > > # Bash scripting reference: Advanced Bash-Scripting Guide > # http://tldp.org/LDP/abs/html/index.html > > # Customize these parameters to local installation: > > sourcedir="/home/me/ghc-6.6.1" > src1="${sourcedir}/ghc-6.6.1-src.tar.bz2" > src2="${sourcedir}/ghc-6.6.1-src-extralibs.tar.bz2" > > testdir="/media/raid/ghc-test" > log="${testdir}/log.txt" > ghcdir="ghc-6.6.1" > binarypath="driver/ghc/ghc" > > > # determine build directory > time=$(date +'%Y%m%d-%H%M%S') > builddir="${testdir}/${time}" > > > # determine number of iterations > if [[ -z "$1" ]] > then > iters=2 > else > iters=$1 > fi > > > # choose ghc binary to use > if [[ -n "$2" && -f $2 && -x $2 ]] > then > ghc=$2 > else > ghc=$(which ghc) > fi > > > # check ghc binary for pulse > fib=`${ghc} -e 'let x = 0 : 1 : zipWith (+) x (tail x) in x !! 99'` > if [[ ${fib} != "218922995834555169026" ]] > then > echo "** bad ** ${ghc} ${iters} ${time}" >> ${log} > ghc=$(which ghc) > else > echo "ok ${ghc} ${iters} ${time}" >> ${log} > fi > > > # do an iteration if $iters > 0 > let iters=iters-1 > if [[ ${iters} -gt 0 ]] > then > > # build new copy of ghc from source > mkdir -p ${builddir} > cd ${builddir} > tar -jxf ${src1} > tar -jxf ${src2} > cd ${ghcdir} > ./configure --with-ghc=${ghc} > make > > # delete previous build directory, now that we're done with $ghc > if [[ -n "$3" && -d "$3" ]] > then > rm -rf $3 > fi > > # iterate > newghc="${builddir}/${ghcdir}/${binarypath}" > ${sourcedir}/ghc-test.sh ${iters} ${newghc} ${builddir} > > else > > # delete previous build directory > if [[ -n "$3" && -d "$3" ]] > then > rm -rf $3 > fi > > fi From stefanor at cox.net Sun Aug 26 01:27:21 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sun Aug 26 01:18:24 2007 Subject: [Haskell-cafe] "GHC from source" makes a great hardware test In-Reply-To: <60C7B0FB-AE2F-4E88-92D7-BD2EF181E22E@math.columbia.edu> References: <60C7B0FB-AE2F-4E88-92D7-BD2EF181E22E@math.columbia.edu> Message-ID: <20070826052721.GA6240@localhost.localdomain> On Sat, Aug 25, 2007 at 09:33:25PM -0700, Dave Bayer wrote: > I recently did the classic "push a shopping cart down the aisle at > Fry's" to build a Core 2 Quad computer, with Linux swap and a soft > raid array spread across three 750 GB sata hard disks. I had some > potential "first build" issues, notably a mishap with the lawn of > copper grass that passes for a 775 cpu socket, followed by an hour of > brain-surgery with a magnifying glass and a tiny screwdriver. I was > very curious to test the stability of this system when it booted up > after all; the best hardware test I could think of was multiple > processes building GHC from source, with each iteration using the > previous GHC binary as the compiler for the new build. You might also try running the Jhc library build; on my system, that gets the processor about 5C hotter than a GHC build. Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070825/dc1f534e/attachment.bin From andrewcoppin at btinternet.com Sun Aug 26 04:12:03 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sun Aug 26 04:02:02 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <2518b95d0708251314h6f65ee3fl3e45b585ceea2b58@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> <46D08AD5.80102@btinternet.com> <2518b95d0708251314h6f65ee3fl3e45b585ceea2b58@mail.gmail.com> Message-ID: <46D135D3.3020401@btinternet.com> Evan Laforge wrote: >> Indeed, you can write certain DSP algorithms beautifully in Haskell. >> Now, if only it could talk to the audio hardware... (Or just use common >> file formats even.) >> > > Oh, that's easy. I wrote an FFI interface to portaudio a while back > to write a delay-looping type utility in haskell. It was pretty > trivial. You could do the same for libsndfile or whatever. > Well, since I can't do C... (What I typically end up doing in these situations is to write a small server program in some language that *does* have the feature I want, and then talk to it over TCP from the language that *doesn't* have the feature. But it's typically quite a lot of typing... and the only language I know of that supports sound (other than C) is Java. And it's *very* complicated...) > The only thing I'm uncertain about is whether it would have good > enough time and space performance. All the real work is writing yet > another set of basic envelope, oscillator, and fft primitives. You > *should* be able to go all the way down to the samples in pure haskell > though, which would be more elegant than those other languages :) > Heh. FFT is tricky. But I got it to work one time... ;-) >> Reaktor has abstraction. You can build a gizmo that does something >> useful, call it a macro, and then use it whereever you want. >> > > Well, except that if you then change your macro you have re-copy it > into every instrument or ensemble or other macro that uses it. So I > consider the macros basically a copy and paste mechanism. > True, true... From andrewcoppin at btinternet.com Sun Aug 26 04:14:05 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sun Aug 26 04:04:05 2007 Subject: [Haskell-cafe] Re: Parsec is being weird at me In-Reply-To: References: <46D077CB.5010106@btinternet.com> <46D07F3F.50604@list.mightyreason.com> <46D08085.6050205@btinternet.com> <20070825193759.GA5402@localhost.localdomain> <46D08B67.7050108@btinternet.com> Message-ID: <46D1364D.3030702@btinternet.com> Chris Casinghino wrote: > On 8/25/07, Andrew Coppin wrote: > >> >> I thought the whole *purpose* of the endBy combinator was to keep >> applying one parser until the other one succeeds? >> > > > I don't think this is a lookahead problem, but rather just a > misreading of the spec of endBy. Here it is: > > (endBy p sep) parses zero or more occurrences of p, seperated and > ended by sep. Returns a list of values returned by p. > > The key text is "seperated and ended by sep". Not just ended by. > ...so then what does sepEndBy do? From andrewcoppin at btinternet.com Sun Aug 26 04:14:33 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sun Aug 26 04:04:33 2007 Subject: [Haskell-cafe] Re: Parsec is being weird at me In-Reply-To: References: <46D077CB.5010106@btinternet.com> <46D07F3F.50604@list.mightyreason.com> <46D08085.6050205@btinternet.com> <20070825193759.GA5402@localhost.localdomain> <46D08B67.7050108@btinternet.com> Message-ID: <46D13669.4020501@btinternet.com> Chris Casinghino wrote: > On 8/25/07, Chris Casinghino wrote: > >> I'm not sure there is a built in combinator for what you want, >> >> > > I guess I should have looked harder. What you want is manyTill: > > "manyTill :: GenParser tok st a -> GenParser tok st end -> GenParser tok st [a] > > (manyTill p end) applies parser p zero or more times until parser end > succeeds. Returns the list of values returned by p." > Yeah, OK, that looks good... From andrewcoppin at btinternet.com Sun Aug 26 04:21:03 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sun Aug 26 04:11:06 2007 Subject: [Haskell-cafe] "GHC from source" makes a great hardware test In-Reply-To: <60C7B0FB-AE2F-4E88-92D7-BD2EF181E22E@math.columbia.edu> References: <60C7B0FB-AE2F-4E88-92D7-BD2EF181E22E@math.columbia.edu> Message-ID: <46D137EF.3030502@btinternet.com> Dave Bayer wrote: > I recently did the classic "push a shopping cart down the aisle at > Fry's" to build a Core 2 Quad computer, with Linux swap and a soft > raid array spread across three 750 GB sata hard disks. I've seen a 2 GHz Quad Xeon server going for about ?600. But get this... IT HAS A SECOND CPU SOCKET! 0_0 The idea of having two quad-core CPUs at my command has me just drooling... and there's currently a special offer on where the 2nd CPU comes for free. Seriously tempted! If *I* were to test such a machine, I'd probably use the new multi-threaded POV-Ray beta... but that's just me. ;-) (Almost all the stuff I do with my PC is compute-bound, not I/O-bound.) From alex at alexjacobson.com Sun Aug 26 04:20:52 2007 From: alex at alexjacobson.com (Alex Jacobson) Date: Sun Aug 26 04:12:00 2007 Subject: [Haskell-cafe] is there a way to run tests at compile time using TH Message-ID: <46D137E4.2000507@alexjacobson.com> I'd like to have code not compile if it doesn't pass the tests. Is there a way to use TH to generate compiler errors if the tests don't pass? -Alex- From andrewcoppin at btinternet.com Sun Aug 26 04:34:23 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sun Aug 26 04:24:24 2007 Subject: [Haskell-cafe] :, infix operator, infix constructor, et cetera In-Reply-To: References: Message-ID: <46D13B0F.4090809@btinternet.com> Daniel C. Bastos wrote: > There is something called infix constructors and something else called > infix operators. I'm guessing that an infix operator is really a > function, and an infix constructor I don't know what it is. How would > you guys describe them? > An "infix operator" is literally a normal function with a funny name, for example (++). If a function name consists only of symbols, not letters, it works infix instead of prefix. On the other hand, you can take a normal function name and make it infix using backticks: filter odd [1,2,3] odd `filter` [1,2,3] An "infix constructor" is a constructor rather than a function. Normally, functions start with a lowercase letter, and constructors start with an uppercase letter. But when the names are symbols, everything becomes infix, and an infix constructor starts with a ":", and an infix function starts with any other symbol. data Tree x = Leaf x | Branch (Tree x) (Tree x) data Tree x = Leaf x | (Tree x) :## (Tree x) > I learned how to define (++), and then I wanted to see how (:) would be > defined. It's a constructor. Like Leaf and Branch in the example above. If the list type wasn't already defined, you could define it as data List x = Node x (List x) | End and then write lists as Node 1 (Node 2 (Node 3 End)) However, that's a lot of typing, so the actual definition looks more like data [x] = x : [x] | [] But that won't compile, because it doesn't obey the syntax rules of Haskell. You could, however, write data List x = x : (List x) | End and it would work. 1 : (2 : (3 : End)) > What does ``built-in syntax'' mean? > The way lists are written (most especially the "[1,2,3]" syntax) is hard-wired into the compiler and cannot be changed. (Similarly for strings, actually.) > The program > > > >> data [a] = [] | a : [a] >> infixr 5 : >> > gives > > %runhugs.exe Colon.lhs > runhugs: Error occurred > ERROR "Colon.lhs":3 - Syntax error in data declaration (unexpected `[') > It doesn't like you calling the type "[x]". If you call it "List x" like I showed above, it should work. > What does that 5 do in ``infixr 5 :''? > 5 is the precedence. You know how "2 + 3 * 4" is treated as "2 + (3 * 4)"? That's because (*) has a higher precedence than (+). From bf3 at telenet.be Sun Aug 26 04:38:48 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Sun Aug 26 04:29:44 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: References: <46D01785.7070503@btinternet.com> <46D07A36.8010508@btinternet.com> <46D084F8.6020207@btinternet.com> <002101c7e74f$ed50da00$c7f28e00$@be> <002801c7e764$0d80f710$2882e530$@be> Message-ID: <003d01c7e7bc$870b96a0$9522c3e0$@be> Chris wrote: > I would personally say Haskell 98 is "real" Haskell (well, until Haskell... > I believe it does work as an offline downloadable tool... > http://www.cs.kent.ac.uk/projects/vital/install/index.html With "real Haskell" I ment strong type checking and indentation for determining scope; without the former, it becomes a different experience IMO. Avoiding runtime errors because types don't match is one the main advantages of Haskell; without this, I'm afraid it is difficult to get a good feeling of the Haskell programming language, be it Haskell98 Peter From ulrivo at gmx.de Sun Aug 26 05:17:42 2007 From: ulrivo at gmx.de (Ulrich Vollert) Date: Sun Aug 26 05:08:42 2007 Subject: [Haskell-cafe] Hugs on Zaurus Message-ID: <46D14536.7030606@gmx.de> > Haskell could run on such a platform". Ofcourse this is completly > other way around in terms of power and memory. :) > > But anyway, did anyone do it? I compiled Hugs for my Sharp Zaurus SL-C3200 (http://www.trisoft.de) which is a PDA with an ARM processor. (System: Lineo uLinux , CPU: Intel? XScale? (PXA270, 416 MHz)) Hugs was compiled by gcc 2.95.3 and can be used in the console, additionally under a special X/Qt-Environment called pdaXqtrom (http://www.users.on.net/~hluc/myZaurus/). So, it is possible to use graphics on the Zaurus, too. I didnt dare to port ghc or Yhc - which would be great to use on the Zaurus, too. Regards, Ulrich From flippa at flippac.org Sun Aug 26 05:59:24 2007 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun Aug 26 05:50:31 2007 Subject: [Haskell-cafe] Hugs on Zaurus In-Reply-To: <46D14536.7030606@gmx.de> References: <46D14536.7030606@gmx.de> Message-ID: On Sun, 26 Aug 2007, Ulrich Vollert wrote: > I compiled Hugs for my Sharp Zaurus SL-C3200 (http://www.trisoft.de) > which is a PDA with an ARM processor. > Any chance of a package or a HOWTO? > So, it is possible to use graphics on the Zaurus, too. I didnt dare to > port ghc or Yhc - which would be great to use on the Zaurus, too. > I've got GHC running under a Debian chroot using the existing ARM binaries - it's painfully slow though, took 7 minutes to compile and link a 300 line interpreter. Needs swap if you're compiling anything of size, too. -- flippa@flippac.org "The reason for this is simple yet profound. Equations of the form x = x are completely useless. All interesting equations are of the form x = y." -- John C. Baez From claudiusmaximus at goto10.org Sun Aug 26 06:35:45 2007 From: claudiusmaximus at goto10.org (Claude Heiland-Allen) Date: Sun Aug 26 06:21:18 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <2518b95d0708251314h6f65ee3fl3e45b585ceea2b58@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> <46D08AD5.80102@btinternet.com> <2518b95d0708251314h6f65ee3fl3e45b585ceea2b58@mail.gmail.com> Message-ID: <46D15781.1090907@goto10.org> Evan Laforge wrote: > The only thing I'm uncertain about is whether it would have good > enough time and space performance. All the real work is writing yet > another set of basic envelope, oscillator, and fft primitives. You > *should* be able to go all the way down to the samples in pure haskell > though, which would be more elegant than those other languages :) I've been playing with using Arrows as stream processors for audio, and the dataflow syntax of arrows is quite nice for sample manipulation: -- low pass filter (1-zero) > lop i = proc (x, f) -> do > sr <- readState -< SampleRate > let c = clip (2 * pi * f / sr) 0 1 > rec y <- delay i -< o > let o = x * c + (1 - c) * y > returnA -< o > lop :: (ArrowCircuit a, ArrowReader b a, Floating b, Ord b) > => b -> a (b, b) b Unfortunately it's *very* slow - to render a 5s sine oscillator sweep from 20Hz to 20000Hz through a low pass filter at 44100Hz sampling rate takes around 17s. Admittedly 40% of the time is spent outputting the numbers to a text file, but it's still far far from realtime, and churns through 7GB of memory in the process (the total memory usage at any one time is constant and small, however). Claude -- http://claudiusmaximus.goto10.org From ulrivo at gmx.de Sun Aug 26 06:36:03 2007 From: ulrivo at gmx.de (Ulrich Vollert) Date: Sun Aug 26 06:27:03 2007 Subject: [Haskell-cafe] Files for Hugs on Zaurus Message-ID: <46D15793.2090107@gmx.de> Hi Phillipa, Hugs is fast enough for me to work on the Zaurus. I packed together all the files which belong to Hugs on my Zaurus and I hope that I didnt miss something. Unpack them to /, the files will stay in usr/local/bin, usr/local/lib and usr/local/share. If you want to use Hugs not only under the console, but with pdaxqtrom (which includes a X-Server, a gcc-Compiler and tons of other stuff), go to http://www.users.on.net/~hluc/myZaurus/custom.html Please tell me, whether Hugs is working for you. Regards, Ulrich From gale at sefer.org Sun Aug 26 07:13:49 2007 From: gale at sefer.org (Yitzchak Gale) Date: Sun Aug 26 07:04:49 2007 Subject: [Haskell-cafe] Style In-Reply-To: References: <46CE8640.8040508@xs4all.nl> Message-ID: <2608b8a80708260413y1f8f7dbfg162448b485cacf70@mail.gmail.com> Bjorn Bringert wrote: > Here's a much more inefficient version, but it has the merit of being > very easy to understand: > > tm_silly n = length $ takeWhile (=='0') $ reverse $ show $ product [1..n] Be careful with types - use Data.List.genericLength here instead of length. Otherwise, tm_silly n is wrong for n >= 13 (on my 32-bit machine) due to round-off error in the Int type. Here is another implementation: > base5 n > | n < 1 = [] > | otherwise = let (q, r) = n `divMod` 5 in r : base5 q > tm6 = sum . zipWith (*) [(5^k-1)`div`4 | k <- [0..]] . base5 Regards, Yitz From lemming at henning-thielemann.de Sun Aug 26 07:34:06 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sun Aug 26 07:24:51 2007 Subject: [Haskell-cafe] Text.Xhtml.Strict In-Reply-To: References: Message-ID: On Sat, 25 Aug 2007, Marco T?lio Gontijo e Silva wrote: > Hello there. > > I don't know if it's off topic, but I don't know where else to ask. > > I've been using Text.Xhtml.Strict, and I'm wondering why the functions > are mostly Html -> Html and not HTML a => a -> Html, or something > similar. If they were like this, << and toHtml would be not needed, > what would make it simpler to call the functions with arguments that > are not Html. > > The question is specific to this library, but I think it's a very > general one: isn't it better to have more generic functions with type > changing inside? It seems to me that it would make things better from > the users point of view. What do you think? The disadvantage of more generic types is that they reduce the possibilities of type inference by the compiler. In the case of HTML generation it might still work well, that is, you could live without type annotations. From sven.panne at aedion.de Sun Aug 26 07:34:41 2007 From: sven.panne at aedion.de (Sven Panne) Date: Sun Aug 26 07:25:42 2007 Subject: [Haskell-cafe] Converting CTime -> Int In-Reply-To: <20070516073544.GB6683@lambda> References: <20070515233552.78fbb8a6@TheRing.javasnob.homelinux.net> <20070516073544.GB6683@lambda> Message-ID: <200708261334.41668.sven.panne@aedion.de> [ Sorry for the *extremely* slow response, but I'm currently working through my backlog of >6000 mails... :-P ] On Wednesday 16 May 2007 09:35, Tomasz Zielonka wrote: > I wonder why CTime is not Integral - maybe there is no such guarantee > for time_t? If so, then you shouldn't rely on Enum. The safest bet seems > to be toRational - CTime is Real. The Single Unix Specification has the answer: http://www.opengroup.org/onlinepubs/000095399/basedefs/sys/types.h.html#tag_13_67 "time_t and clock_t shall be integer or real-floating types." CTime's Enum instance is as debatable as the ones for Float and Double, but for consistency reasons we included it in the FFI spec. Cheers, S. From lemming at henning-thielemann.de Sun Aug 26 07:56:00 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sun Aug 26 07:46:43 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D079B4.9040700@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> Message-ID: On Sat, 25 Aug 2007, Andrew Coppin wrote: > Would be nice if I could build something in Haskell that overcomes these. > OTOH, does Haskell have any way to talk to the audio hardware? Maybe a JACK interface? http://haskell.org/haskellwiki/Applications_and_libraries/Music_and_sound From isaacdupree at charter.net Sun Aug 26 07:53:51 2007 From: isaacdupree at charter.net (Isaac Dupree) Date: Sun Aug 26 07:47:28 2007 Subject: [Haskell-cafe] :, infix operator, infix constructor, et cetera In-Reply-To: <46D13B0F.4090809@btinternet.com> References: <46D13B0F.4090809@btinternet.com> Message-ID: <46D169CF.2020803@charter.net> Andrew Coppin wrote: > Daniel C. Bastos wrote: > But that won't compile, because it doesn't obey the syntax rules of > Haskell. You could, however, write > > data List x = x : (List x) | End > > and it would work. > > 1 : (2 : (3 : End)) Except that (for no particularly good reason) ":" is a reserved symbol that always refers to the Prelude list version. You could define a similar name like: data List x = x :- (List x) | End 1 :- (2 :- (3 :- End)) Isaac From lemming at henning-thielemann.de Sun Aug 26 08:05:38 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sun Aug 26 07:56:24 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> Message-ID: On Sat, 25 Aug 2007, Evan Laforge wrote: >> Reaktor has a few limitations though. >> >> 1. It's virtually impossible to debug the thing! (I.e., if your synth >> doesn't work... good luck working out why.) >> >> 2. It lacks looping capabilities. For example, you cannot build a >> variable-size convolution block - only a fixed-size one. (If you want to >> draw *a lot* of wires!) If you look through the standard library, you'll >> find no end of instruments that use a "hack" of using voice polyphony to >> crudely simulate looping... but it's not too hot. >> >> Would be nice if I could build something in Haskell that overcomes >> these. OTOH, does Haskell have any way to talk to the audio hardware? > > ... > > To get this back to haskell, at the time I wondered if a more natural > implementation might be possible in haskell, seeing as it was more > naturally lazy. Not sure how to implement the behaviours though > (which were simply macros around a let of *dynamic-something*). I'm > sure people have done plenty of signal processing, and there's always > haskore... but what about a sound generation language like csound or > clm or nyquist? It could fit in nicely below haskore. I'm playing around with Haskore controlling signal synthesis implemented in pure Haskell for some time now: http://darcs.haskell.org/synthesizer/src/Haskore/Interface/Signal/ It works, but it's still slow and hard to install. This discussion is certainly also of interest for the haskell-art mailing list. http://lists.lurk.org/mailman/listinfo/haskell-art From lemming at henning-thielemann.de Sun Aug 26 08:09:21 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sun Aug 26 08:00:49 2007 Subject: [Haskell-cafe] Audio output (Was: Re: Ideas) In-Reply-To: <46D08AD5.80102@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> <46D08AD5.80102@btinternet.com> Message-ID: On Sat, 25 Aug 2007, Andrew Coppin wrote: > Evan Laforge wrote: >> To get this back to haskell, at the time I wondered if a more natural >> implementation might be possible in haskell, seeing as it was more >> naturally lazy. Not sure how to implement the behaviours though >> (which were simply macros around a let of *dynamic-something*). I'm >> sure people have done plenty of signal processing, and there's always >> haskore... but what about a sound generation language like csound or >> clm or nyquist? It could fit in nicely below haskore. > > Indeed, you can write certain DSP algorithms beautifully in Haskell. Now, if > only it could talk to the audio hardware... (Or just use common file formats > even.) I invoke a variety of sound converters/players (sox, alsaplayer, ecasound) in order to fix this problem. Writing and playing this way is easy. Reading files is problematic because the converters cannot output header information. 'http://darcs.haskell.org/synthesizer/src/Sox/File.hs' 'http://darcs.haskell.org/synthesizer/src/Sox/Play.hs' 'http://darcs.haskell.org/dafx/src/Presentation.hs' From lemming at henning-thielemann.de Sun Aug 26 08:17:34 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sun Aug 26 08:08:18 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D01785.7070503@btinternet.com> References: <46D01785.7070503@btinternet.com> Message-ID: On Sat, 25 Aug 2007, Andrew Coppin wrote: > How easy would it be to make / would anybody care / has somebody already made > ... in Haskell? > > - An interactive function plotter. (GNUplot is nice, but it can't plot recursive functions...) I'm be interested to use such a library. > - A "graphical programming tool". (You add boxes and put in lines, it constructs a "program" that you can run.) Would be nice for editing signal processing that is coded in Haskell. From lemming at henning-thielemann.de Sun Aug 26 08:18:51 2007 From: lemming at henning-thielemann.de (Henning Thielemann) Date: Sun Aug 26 08:09:34 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D135D3.3020401@btinternet.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538m38a05c6cmf8e16e1c5c6ba0bb@mail.gmail.com> <46D079B4.9040700@btinternet.com> <2518b95d0708251254k50e7e524o64911366bc3fb183@mail.gmail.com> <46D08AD5.80102@btinternet.com> <2518b95d0708251314h6f65ee3fl3e45b585ceea2b58@mail.gmail.com> <46D135D3.3020401@btinternet.com> Message-ID: On Sun, 26 Aug 2007, Andrew Coppin wrote: >> The only thing I'm uncertain about is whether it would have good >> enough time and space performance. All the real work is writing yet >> another set of basic envelope, oscillator, and fft primitives. You >> *should* be able to go all the way down to the samples in pure haskell >> though, which would be more elegant than those other languages :) > > Heh. FFT is tricky. But I got it to work one time... ;-) There's already an extensive FFT implementation in Haskell by Matt Donadio: http://haskelldsp.sourceforge.net/ (I'm working on some clean up at http://darcs.haskell.org/dsp/Numeric/Transform/Fourier/ ) From chaddai.fouche at gmail.com Sun Aug 26 08:22:10 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Sun Aug 26 08:13:11 2007 Subject: [Haskell-cafe] Style In-Reply-To: <2608b8a80708260413y1f8f7dbfg162448b485cacf70@mail.gmail.com> References: <46CE8640.8040508@xs4all.nl> <2608b8a80708260413y1f8f7dbfg162448b485cacf70@mail.gmail.com> Message-ID: 2007/8/26, Yitzchak Gale : > Bjorn Bringert wrote: > > Here's a much more inefficient version, but it has the merit of being > > very easy to understand: > > > > tm_silly n = length $ takeWhile (=='0') $ reverse $ show $ product [1..n] > > Be careful with types - use Data.List.genericLength > here instead of length. Otherwise, tm_silly n is wrong for > n >= 13 (on my 32-bit machine) due to round-off error > in the Int type. Are you sure you really tested tm_silly ? length is perfectly enough to count the 0 in n! since the number of zeros don't go over the Int limit before n = 8_589_934_615 (though this solution will stack overflow due to the product much sooned than that). -- Jeda? From andrewcoppin at btinternet.com Sun Aug 26 08:35:33 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sun Aug 26 08:25:30 2007 Subject: [Haskell-cafe] :, infix operator, infix constructor, et cetera In-Reply-To: <46D169CF.2020803@charter.net> References: <46D13B0F.4090809@btinternet.com> <46D169CF.2020803@charter.net> Message-ID: <46D17395.5080702@btinternet.com> Isaac Dupree wrote: > Andrew Coppin wrote: >> Daniel C. Bastos wrote: >> But that won't compile, because it doesn't obey the syntax rules of >> Haskell. You could, however, write >> >> data List x = x : (List x) | End >> >> and it would work. >> >> 1 : (2 : (3 : End)) > > Except that (for no particularly good reason) ":" is a reserved symbol > that always refers to the Prelude list version. You could define a > similar name like: Really? That's interesting... AFAIK, according to the Report, it shouldn't be. I just tested. GHC won't let me, WinHugs will. Hmm... From emmanuel.delaborde at citycampus.com Sun Aug 26 08:50:00 2007 From: emmanuel.delaborde at citycampus.com (manu) Date: Sun Aug 26 08:38:37 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell Message-ID: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> Hello, After reading Peter Norvig's take on writing a Sudoku solver (http:// norvig.com/sudoku.html) I decided that I would port his program to Haskell, without changing the algorithm, that'll make a nice exercise I thought and should be fairly easy... Boy, was I wrong ! Anyway, I eventually managed to tiptoe around for loops, mutable state, etc... However, when I run my program against the test data provided (http:// norvig.com/top95.txt), I find it takes around 1m20 s to complete (compiled with -fvia-C and - O2, on a MacBook Pro 2.33GHz Intel Core 2 Duo). That's roughly 8 times longer than Norvig's Python script. That's not what I expected ! My program is also longer than the Python version. Being a beginner, I am convinced my implementation is super naive and non idiomatic. A seasonned Haskeller would do much shorter and much faster. I don't know how to improve it though ! Should I introduce more strictness ? replace lists with more efficient data structures (ByteStrings, Arrays) ? Here is my program, and part of the profiling (memory allocation looks huge !) I hope this post wasn't too long. Thanks for any advice ! Emmanuel. {- This is an attempt to implement in Haskell, Peter Norvig's sudoku solver : "Solving Every Sudoku Puzzle" (http://norvig.com/sudoku.html) In Norvig's program, methods which change a grid return either a new grid, either False (failure). Here I use Maybe, and return Just grid or Nothing in case of failure -} module Main where import Prelude hiding (lookup) import Data.List hiding (lookup) import qualified Data.Map as M import Control.Monad import Maybe import System.IO -------------------------------------------------- -- Types type Digit = Char type Square = String type Unit = [Square] -- We represent our grid as a Map type Grid = M.Map Square [Digit] -------------------------------------------------- -- Setting Up the Problem rows = "ABCDEFGHI" cols = "123456789" digits = "123456789" cross :: String -> String -> [String] cross rows cols = [ r:c:[] | r <- rows, c <- cols ] squares :: [Square] squares = cross rows cols -- ["A1","A2","A3",...] unitlist :: [Unit] unitlist = [ cross rows [c] | c <- cols ] ++ [ cross [r] cols | r <- rows ] ++ [ cross rs cs | rs <- ["ABC","DEF","GHI"], cs <- ["123","456","789"]] units :: M.Map Square [Unit] units = M.fromList [ (s, [ u | u <- unitlist, elem s u ]) | s <- squares ] peers :: M.Map Square [Square] peers = M.fromList [ (s, set [[ p | p <- e, p /= s ] | e <- lookup s units ]) | s <- squares ] where set = nub . concat -------------------------------------------------- -- Wrapper around M.lookup used in list comprehensions lookup :: (Ord a, Show a) => a -> M.Map a b -> b lookup k v = case M.lookup k v of Just x -> x Nothing -> error $ "Error : key " ++ show k ++ " not in map !" -- lookup k m = fromJust . M.lookup k m -------------------------------------------------- -- Parsing a grid into a Map parsegrid :: String -> Maybe Grid parsegrid g = do regularGrid g foldM assign allPossibilities (zip squares g) where allPossibilities :: Grid allPossibilities = M.fromList [ (s,digits) | s <- squares ] regularGrid :: String -> Maybe String regularGrid g = if all (\c -> (elem c "0.-123456789")) g then (Just g) else Nothing -------------------------------------------------- -- Propagating Constraints assign :: Grid -> (Square, Digit) -> Maybe Grid assign g (s,d) = if (elem d digits) then do -- check that we are assigning a digit and not a '.' let toDump = delete d (lookup s g) res <- foldM eliminate g (zip (repeat s) toDump) return res else return g eliminate :: Grid -> (Square, Digit) -> Maybe Grid eliminate g (s,d) = let cell = lookup s g in if not (elem d cell) then return g -- already eliminated -- else d is deleted from s' values else do let newCell = delete d cell newV = M.insert s newCell g -- newV2 <- case length newCell of -- contradiction : Nothing terminates the computation 0 -> Nothing -- if there is only one value (d2) left in square, remove it from peers 1 -> do let peersOfS = [ s' | s' <- lookup s peers ] res <- foldM eliminate newV (zip peersOfS (cycle newCell)) return res -- else : return the new grid _ -> return newV -- Now check the places where d appears in the units of s let dPlaces = [ s' | u <- lookup s units, s' <- u, elem d (lookup s' newV2) ] case length dPlaces of 0 -> Nothing -- d can only be in one place in unit; assign it there 1 -> assign newV2 (head dPlaces, d) _ -> return newV2 -------------------------------------------------- -- Search search :: Maybe Grid -> Maybe Grid search Nothing = Nothing search (Just g) = if all (\xs -> length xs == 1) [ lookup s g | s <- squares ] then (Just g) -- solved else do let (_,s) = minimum [ (length (lookup s g),s) | s <- squares, length (lookup s g) > 1 ] g' = g -- copie of g foldl' some Nothing [ search (assign g' (s,d)) | d <- lookup s g ] where some Nothing Nothing = Nothing some Nothing (Just g) = (Just g) some (Just g) _ = (Just g) -------------------------------------------------- -- Display solved grid printGrid :: Grid -> IO () printGrid = putStrLn . gridToString gridToString :: Grid -> String gridToString g = let l0= map snd (M.toList g) -- [("1537"),("4"),...] l1 = (map (\s -> " " ++ s ++ " ")) l0 -- [" 1 "," 2 ",...] l2 = (map concat . sublist 3) l1 -- [" 1 2 3 "," 4 5 6 ",...] l3 = (sublist 3) l2 -- [[" 1 2 3 "," 4 5 6 "," 7 8 9 "],...] l4 = (map (concat . intersperse "|")) l3 -- [" 1 2 3 | 4 5 6 | 7 8 9 ",...] l5 = (concat . intersperse [line] . sublist 3) l4 in unlines l5 where sublist n [] = [] sublist n xs = take n xs : sublist n (drop n xs) line = hyphens ++ "+" ++ hyphens ++ "+" ++ hyphens hyphens = take 9 (repeat '-') -------------------------------------------------- main :: IO () main = do h <- openFile "top95.txt" ReadMode grids <- hGetContents h let solved = mapMaybe (search . parsegrid) (lines grids) mapM_ printGrid solved hClose h ************************************************************************ *** Sun Aug 26 13:44 2007 Time and Allocation Profiling Report (Final) sudoku_norvig +RTS -p -hc -RTS total time = 49.40 secs (988 ticks @ 50 ms) total alloc = 6,935,777,308 bytes (excludes profiling overheads) COST CENTRE MODULE %time %alloc lookup Main 65.7 22.6 eliminate Main 32.4 70.3 search Main 1.8 6.3 individual inherited COST CENTRE MODULE no. entries % time %alloc %time %alloc MAIN MAIN 1 0 0.0 0.0 100.0 100.0 main Main 190 1 0.0 0.0 100.0 100.0 printGrid Main 214 95 0.0 0.0 0.0 0.1 gridToString Main 215 665 0.0 0.1 0.0 0.1 search Main 208 427143 1.8 6.3 99.4 99.2 assign Main 210 468866 0.1 0.6 90.4 90.3 eliminate Main 212 30626903 32.2 69.8 89.9 89.6 lookup Main 213 172203504 57.7 19.9 57.7 19.9 lookup Main 211 468866 0.4 0.1 0.4 0.1 lookup Main 209 22447632 7.2 2.6 7.2 2.6 parsegrid Main 192 95 0.0 0.0 0.6 0.7 assign Main 198 7695 0.0 0.0 0.6 0.7 eliminate Main 201 51054 0.2 0.5 0.6 0.7 lookup Main 202 1239860 0.4 0.1 0.4 0.1 lookup Main 200 1953 0.0 0.0 0.0 0.0 ... (more innocuous stuff) From chris at cmears.id.au Sun Aug 26 09:13:27 2007 From: chris at cmears.id.au (Chris Mears) Date: Sun Aug 26 09:04:31 2007 Subject: [Haskell-cafe] is there a way to run tests at compile time using TH In-Reply-To: <46D137E4.2000507@alexjacobson.com> (Alex Jacobson's message of "Sun\, 26 Aug 2007 01\:20\:52 -0700") References: <46D137E4.2000507@alexjacobson.com> Message-ID: <873ay6sako.fsf@loki.cmears.id.au> Alex Jacobson writes: > I'd like to have code not compile if it doesn't pass the tests. > > Is there a way to use TH to generate compiler errors if the tests > don't pass? What about something like this? import Language.Haskell.TH import Tests -- this should export "testsPass :: Bool" -- don't bother trying to call this function. check = $( if testsPass then [| () |] else error "test failed" ) main = print "hi" If testsPass returns False, the compiler will throw an exception during compilation, like this: Exception when trying to run compile-time code: test failed [...] From igloo at earth.li Sun Aug 26 09:13:54 2007 From: igloo at earth.li (Ian Lynagh) Date: Sun Aug 26 09:04:53 2007 Subject: [Haskell-cafe] :, infix operator, infix constructor, et cetera In-Reply-To: <46D17395.5080702@btinternet.com> References: <46D13B0F.4090809@btinternet.com> <46D169CF.2020803@charter.net> <46D17395.5080702@btinternet.com> Message-ID: <20070826131354.GA406@matrix.chaos.earth.li> On Sun, Aug 26, 2007 at 01:35:33PM +0100, Andrew Coppin wrote: > Isaac Dupree wrote: > > > >Except that (for no particularly good reason) ":" is a reserved symbol > > Really? That's interesting... AFAIK, according to the Report, it > shouldn't be. It is; from http://haskell.org/onlinereport/syntax-iso.html consym -> (: {symbol | :}) reservedop -> .. | : | :: | = | \ | | | <- | -> | @ | ~ | => > I just tested. GHC won't let me, WinHugs will. Hmm... Sounds like a WinHugs bug if you haven't enabled extensions. Thanks Ian From igloo at earth.li Sun Aug 26 09:16:25 2007 From: igloo at earth.li (Ian Lynagh) Date: Sun Aug 26 09:07:27 2007 Subject: [Haskell-cafe] is there a way to run tests at compile time using TH In-Reply-To: <46D137E4.2000507@alexjacobson.com> References: <46D137E4.2000507@alexjacobson.com> Message-ID: <20070826131625.GB406@matrix.chaos.earth.li> On Sun, Aug 26, 2007 at 01:20:52AM -0700, Alex Jacobson wrote: > I'd like to have code not compile if it doesn't pass the tests. > > Is there a way to use TH to generate compiler errors if the tests don't > pass? This should do it, in a different module to that which defines runtests: $( case runtests of Success -> return [] Failure -> error "Tests failed" ) Thanks Ian From sven.panne at aedion.de Sun Aug 26 09:50:23 2007 From: sven.panne at aedion.de (Sven Panne) Date: Sun Aug 26 09:41:23 2007 Subject: [Haskell-cafe] renderString problems In-Reply-To: References: Message-ID: <200708261550.23798.sven.panne@aedion.de> On Wednesday 01 August 2007 18:30, Dave Tapley wrote: > I'm having a lot of trouble using renderString from Graphics.UI.GLUT.Fonts. > All my attempts to render a StrokeFont have so far failed. > Using a BitmapFont I can get strings to appear but they demonstrate > the odd behaviour of translating themselves a distance equal to their > length every time my displayCallback function is evaluated. This is actually not a bug, but a feature. :-) From the Haddock docs for renderString: ------------------------------------------------------------------------ Render the string in the named font, without using any display lists. Rendering a nonexistent character has no effect. If the font is a bitmap font, renderString automatically sets the OpenGL unpack pixel storage modes it needs appropriately and saves and restores the previous modes before returning. The generated call to bitmap will adjust the current raster position based on the width of the string. If the font is a stroke font, translate is used to translate the current model view matrix to advance the width of the string. ------------------------------------------------------------------------ The rational behind this is that you set a position once, and subsequent multiple renderString calls will render the individual strings one after the other, just like printf appends strings on the output. If this is not clear from the documentation, any suggestions how to improve the docs? And another hint: On usual consumer graphic cards, stroke fonts are normally faster than bitmapped fonts. The fastest, most flexible (scaling, filtering, ...) and visually nicest option would be textured quads, but this is not supported by GLUT. > My requests are: > * Does anyone know how to keep the position fixed? For bitmapped fonts, explicitly set the currentRasterPosition. For stroke fonts, you can use the normal modelview machinery (loadIdentity/preservingMatrix/...). > * Are there any good examples of (working) GLUT code available on > the web, I'm finding it very hard to make any progress at the moment. > Certainly not at Haskell speed :( Depending on the distribution you use, you probably have the example already somewhere on your disk or you can directly have a look at the repository: http://darcs.haskell.org/packages/GLUT/examples/ Cheers, S. From martindemello at gmail.com Sun Aug 26 10:32:46 2007 From: martindemello at gmail.com (Martin DeMello) Date: Sun Aug 26 10:23:45 2007 Subject: [Haskell-cafe] renderString problems In-Reply-To: <200708261550.23798.sven.panne@aedion.de> References: <200708261550.23798.sven.panne@aedion.de> Message-ID: On 8/26/07, Sven Panne wrote: > > This is actually not a bug, but a feature. :-) From the Haddock docs for > renderString: > > ------------------------------------------------------------------------ > Render the string in the named font, without using any display lists. > Rendering a nonexistent character has no effect. > > If the font is a bitmap font, renderString automatically sets the OpenGL > unpack pixel storage modes it needs appropriately and saves and restores the > previous modes before returning. The generated call to bitmap will adjust the > current raster position based on the width of the string. If the font is a > stroke font, translate is used to translate the current model view matrix to > advance the width of the string. > ------------------------------------------------------------------------ > > The rational behind this is that you set a position once, and subsequent > multiple renderString calls will render the individual strings one after the > other, just like printf appends strings on the output. If this is not clear > from the documentation, any suggestions how to improve the docs? Why not add the rationale to the docs too? Invoking printf should make the thing jump into focus for anyone who hasn't got it. martin From chris.casinghino at gmail.com Sun Aug 26 11:00:33 2007 From: chris.casinghino at gmail.com (Chris Casinghino) Date: Sun Aug 26 10:51:38 2007 Subject: [Haskell-cafe] Re: Parsec is being weird at me In-Reply-To: <46D1364D.3030702@btinternet.com> References: <46D077CB.5010106@btinternet.com> <46D07F3F.50604@list.mightyreason.com> <46D08085.6050205@btinternet.com> <20070825193759.GA5402@localhost.localdomain> <46D08B67.7050108@btinternet.com> <46D1364D.3030702@btinternet.com> Message-ID: On 8/26/07, Andrew Coppin wrote: > > ...so then what does sepEndBy do? > With endBy, the sequence must end with the separator, with sepEndBy, the final occurrence of the separator is optional. The documentation here is very good: http://legacy.cs.uu.nl/daan/parsec.html --Chris From gale at sefer.org Sun Aug 26 12:53:12 2007 From: gale at sefer.org (Yitzchak Gale) Date: Sun Aug 26 12:44:12 2007 Subject: [Haskell-cafe] Style In-Reply-To: References: <46CE8640.8040508@xs4all.nl> <2608b8a80708260413y1f8f7dbfg162448b485cacf70@mail.gmail.com> Message-ID: <2608b8a80708260953m13a7924vd83b360779016f2a@mail.gmail.com> I wrote: >> Be careful with types - use Data.List.genericLength >> here instead of length. Otherwise, tm_silly n is wrong for >> n >= 13 (on my 32-bit machine) due to round-off error >> in the Int type. > Are you sure you really tested tm_silly ? > length is perfectly enough > to count the 0 in n! since the number > of zeros don't go over the Int limit True, that is not the problem. Using length forces the result to be Int, which is different than all of the other tm's so far. So for example, try this: [n | n <- [0..25], tm_silly n /= tm n] -Yitz From girodt at gmail.com Sun Aug 26 13:24:32 2007 From: girodt at gmail.com (Thomas Girod) Date: Sun Aug 26 13:15:31 2007 Subject: [Haskell-cafe] nested datatypes Message-ID: Hi there. recently I was trying to represent complex data by defining several datatypes and nesting them, such as data Foo = Foo { foo :: Bar } deriving (Eq,Show) data Bar = Bar { bar :: Int } deriving (Eq,Show) To change only a part of the data, syntactic sugar is quite convenient. But it seems to be quite painful with nested datatypes. b = Bar 10 f = Foo b foobar :: Int -> Foo -> Foo foobar i f = let nb = (foo f){bar = i} in f{foo = nb} So, my question is : is there a nifty way to modify data within a nested datatype, similar to the f{foo = bar} style ? If not, anyone is using some kind of workaround for this ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070826/9fef271d/attachment.htm From derek.a.elkins at gmail.com Sun Aug 26 13:26:39 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Sun Aug 26 13:17:47 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> Message-ID: <1188149199.13256.8.camel@derek-laptop> On Sun, 2007-08-26 at 14:50 +0200, manu wrote: > Hello, > > After reading Peter Norvig's take on writing a Sudoku solver (http:// > norvig.com/sudoku.html) > I decided that I would port his program to Haskell, without changing > the algorithm, that'll make a nice exercise I thought > and should be fairly easy... Boy, was I wrong ! > > Anyway, I eventually managed to tiptoe around for loops, mutable > state, etc... > However, when I run my program against the test data provided (http:// > norvig.com/top95.txt), > I find it takes around 1m20 s to complete (compiled with -fvia-C and - > O2, on a MacBook Pro 2.33GHz Intel Core 2 Duo). > That's roughly 8 times longer than Norvig's Python script. That's not > what I expected ! > My program is also longer than the Python version. > > Being a beginner, I am convinced my implementation is super naive and > non idiomatic. A seasonned Haskeller would do much shorter and much > faster. I don't know how to improve it though ! > > Should I introduce more strictness ? replace lists with more > efficient data structures (ByteStrings, Arrays) ? Yes. Treating lists like arrays is always a recipe for heartbreak. If you did want to try to match the python code exactly there are mutable arrays and such. http://www.haskell.org/haskellwiki/Sudoku has a bunch of different implementations going for different things. From malte at gmx-topmail.de Sun Aug 26 13:30:43 2007 From: malte at gmx-topmail.de (Malte Milatz) Date: Sun Aug 26 13:21:49 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> Message-ID: <20070826193043.14b6632d@aligatoro.ret> manu : > After reading Peter Norvig's take on writing a Sudoku solver (http:// > norvig.com/sudoku.html) > I decided that I would port his program to Haskell Your program was wrapped by your mail client, so you may want to hpaste your program for easier digestion. > Being a beginner, I am convinced my implementation is super naive and > non idiomatic. A seasonned Haskeller would do much shorter and much > faster. I don't know how to improve it though ! Disclaimer: I'm not an experienced Haskeller either, and I haven't had a real look at your code at all. The following is only what stroke me by a quick look. Gurus may eventually reduce your code into a thirty-line version that also runs quickly. > -- Types > type Digit = Char > type Square = String > type Unit = [Square] > > -- We represent our grid as a Map > type Grid = M.Map Square [Digit] Your profiling output suggests that much time is consumed by the lookup function. Since you're using (fromJust . lookup) everywhere anyway, a data structure not envolving the Maybe type is probably a more succint choice. And why bother with characters and strings? So I propose type Square = (Int,Int) type Grid = Array Square Int -- or [Int], if the algorithm requires that Where the array's bound are (0,0), (8,8) or (1,1), (9,9), according to your taste. > newV2 <- case length newCell of > 0 -> Nothing > 1 -> do let peersOfS = [ s' | s' <- lookup s peers ] > res <- foldM eliminate newV (zip peersOfS (cycle newCell)) > return res > _ -> return newV The use of ?length? here is not an actual performance problem, but unnecessary. Simply write: case newCell of [] -> ... [_] -> ... _ -> ... The same is valid for your other use of length. Malte From jgm at berkeley.edu Sun Aug 26 13:45:39 2007 From: jgm at berkeley.edu (John MacFarlane) Date: Sun Aug 26 13:36:47 2007 Subject: [Haskell-cafe] Re: Ideas In-Reply-To: <46D01785.7070503@btinternet.com> References: <46D01785.7070503@btinternet.com> Message-ID: <20070826174538.GA24444@berkeley.edu> +++ Andrew Coppin [Aug 25 07 12:50 ]: > How easy would it be to make / would anybody care / has somebody already > made ... in Haskell? > > - A wiki program. (Ditto.) I wrote a simple wiki using HAppS and pandoc. See demonstration #15 on the pandoc web page: http://sophos.berkeley.edu/macfarlane/pandoc/examples.html It's by no means a finished product, but might serve as a good base if you decide to work on a wiki. John From radoslawg at gmail.com Sun Aug 26 14:14:59 2007 From: radoslawg at gmail.com (=?UTF-8?Q?Rados=C5=82aw_Grzanka?=) Date: Sun Aug 26 14:05:58 2007 Subject: [Haskell-cafe] Re: Hugs on Zaurus In-Reply-To: <46D14536.7030606@gmx.de> References: <46D14536.7030606@gmx.de> Message-ID: <9d55dbaf0708261114y5ddd73ebqc4bab7e23c3cc63a@mail.gmail.com> 2007/8/26, Ulrich Vollert : > > Haskell could run on such a platform". Ofcourse this is completly > > other way around in terms of power and memory. :) > > > > But anyway, did anyone do it? > > I compiled Hugs for my Sharp Zaurus SL-C3200 (http://www.trisoft.de) > which is a PDA with an ARM processor. > > (System: Lineo uLinux , CPU: Intel(r) XScale? (PXA270, 416 MHz)) > > Hugs was compiled by gcc 2.95.3 and can be used in the console, > additionally under a special X/Qt-Environment called pdaXqtrom > (http://www.users.on.net/~hluc/myZaurus/). > > So, it is possible to use graphics on the Zaurus, too. I didnt dare to > port ghc or Yhc - which would be great to use on the Zaurus, too. This is so cool. Unfortunatly I own Treo 650 and running Linux here is a lot of hackery. It would be awsomely cool to use Hugs on it. Cheers, Radek. From luc.taesch at gmail.com Sun Aug 26 14:32:02 2007 From: luc.taesch at gmail.com (luc.taesch) Date: Sun Aug 26 14:23:01 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <20070826174538.GA24444@berkeley.edu> References: <46D01785.7070503@btinternet.com> <20070826174538.GA24444@berkeley.edu> Message-ID: <12337130.post@talk.nabble.com> John MacFarlane wrote: > > +++ Andrew Coppin [Aug 25 07 12:50 ]: > > > I wrote a simple wiki using HAppS and pandoc. See demonstration #15 > on the pandoc web page: > > http://sophos.berkeley.edu/macfarlane/pandoc/examples.html > > o Hey ! that s exactly whatI had in mind.. cool indeed, I am toying with the idea to - produce book, nicely (automatically) typeset with Latex or docbook - out of a wiki as interface ( as wikibook for instance) - with either free and informal text , - or formally ( automatically produced) sets or reference or docs ( a bit like literate programming embed code into the text), but these table would be more and more refined set of requirement.. This last point was with a software ingeniering backgroud in mind, ie to produce the requirement, and specification of software, , imagine a lot of reference and cross reference to manage, and to establish tracability..( if you heard about Cleanroom, just to examplify ) may i ask you what did you had in mind as an application when you started that ? -- View this message in context: http://www.nabble.com/Ideas-tf4327747.html#a12337130 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From apfelmus at quantentunnel.de Sun Aug 26 14:52:08 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Sun Aug 26 14:43:16 2007 Subject: [Haskell-cafe] Re: nested datatypes In-Reply-To: References: Message-ID: (Note that the term "nested data type" also/already carries the meaning "non-regular data type", an example being data PerfectBinaryTree a = One a | Succ (PerfectBinaryTree (a,a)) ) Thomas Girod wrote: > recently I was trying to represent complex data by defining several > datatypes and nesting them, such as > > data Foo = Foo { foo :: Bar } > deriving (Eq,Show) > data Bar = Bar { bar :: Int } > deriving (Eq,Show) > > To change only a part of the data, syntactic sugar is quite convenient. But > it seems to be quite painful with nested datatypes. > > b = Bar 10 > f = Foo b > > foobar :: Int -> Foo -> Foo > foobar i f = > let nb = (foo f){bar = i} > in f{foo = nb} > > So, my question is : is there a nifty way to modify data within a nested > datatype, similar to the f{foo = bar} style ? If not, anyone is using some > kind of workaround for this ? There is a nifty way, called "functional references". They're a pair of get and set functions data Ref s a = Ref { get :: s -> a, set :: a -> s -> s } The nice thing about them is that we can compose them like functions o :: Ref b c -> Ref a b -> Ref a c f `o` g = Ref (get f . get g) (\c a -> set (set c f $ get g a) g a) The example becomes data Foo = Foo Bar data Bar = Bar Int foo :: Ref Foo Bar foo = Ref (\(Foo x) -> x) (\x (Foo _) -> Foo y) bar :: Ref Bar Int bar = Ref (\(Bar x) -> x) (\x (Bar _) -> Bar x) foobar :: Ref Foo Int foobar = bar `o` foo See also http://luqui.org/blog/archives/2007/08/05/ haskell-state-accessors-second-attempt-composability/ and Sander Evers, Peter Achten, and Jan Kuper. "A Functional Programming Technique for Forms in Graphical User Interfaces". http://www.st.cs.ru.nl/papers/2005/eves2005-FFormsIFL04.pdf Writing getter and setter functions by hand can be tedious but somebody already automated this with Template Haskell or other other preprocessing tools. Regards, apfelmus From jgm at berkeley.edu Sun Aug 26 15:12:53 2007 From: jgm at berkeley.edu (John MacFarlane) Date: Sun Aug 26 15:04:02 2007 Subject: [Haskell-cafe] Re: Ideas In-Reply-To: <12337130.post@talk.nabble.com> References: <46D01785.7070503@btinternet.com> <20070826174538.GA24444@berkeley.edu> <12337130.post@talk.nabble.com> Message-ID: <20070826191253.GA28742@berkeley.edu> > may i ask you what did you had in mind as an application when you started > that ? This was just recreational programming: I wanted to see what writing a web application in Haskell would be like. I think it would be great to have a fully featured wiki program in Haskell, but I don't have time to do it myself. Your idea sounds very interesting. Feel free to extend pandocwiki if that works for you; it's GPL. John From andrewcoppin at btinternet.com Sun Aug 26 15:17:21 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Sun Aug 26 15:07:21 2007 Subject: [Haskell-cafe] Re: Parsec is being weird at me In-Reply-To: References: <46D077CB.5010106@btinternet.com> <46D07F3F.50604@list.mightyreason.com> <46D08085.6050205@btinternet.com> <20070825193759.GA5402@localhost.localdomain> <46D08B67.7050108@btinternet.com> <46D1364D.3030702@btinternet.com> Message-ID: <46D1D1C1.6010906@btinternet.com> Chris Casinghino wrote: > On 8/26/07, Andrew Coppin wrote: > >> ...so then what does sepEndBy do? >> >> > > With endBy, the sequence must end with the separator, with sepEndBy, > the final occurrence of the separator is optional. > Oh. I see... *sigh* Another wetware error. :-/ From gale at sefer.org Sun Aug 26 15:23:59 2007 From: gale at sefer.org (Yitzchak Gale) Date: Sun Aug 26 15:14:58 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> Message-ID: <2608b8a80708261223s3058f5acy1efdf1ddbab2ea16@mail.gmail.com> Hi Manu, You wrote: > After reading Peter Norvig's take on writing a Sudoku solver > (http://> norvig.com/sudoku.html) > I decided that I would port his program to Haskell, without changing > the algorithm, that'll make a nice exercise I thought > and should be fairly easy... Boy, was I wrong ! Welcome to the Haskell Sudoku club! http://haskell.org/haskellwiki/Sudoku Please add your solver there. I enjoyed reading your solver, and comparing it to the Python version. It was a nice idea to port the imperitive parts of this algorithm using the Maybe monad. The algorithm of your solver is essentially identical to the solver I posted on the wiki page; even the data structures are more or less the same. But mine is written in a more native Haskell style (happens to be based on a State monad). > When I run my program against the test data > provided (http://norvig.com/top95.txt), > I find it takes around 1m20 s to complete I just ran mine against that file, also on a MacBook like yours, but only 2Ghz. It took about 28s, only about double Norvig's claim. There are other solvers on the wiki page that claim to be considerably faster. > (compiled with -fvia-C The GHC gurus can correct me, but I understand that there isn't likely to be any advantage to -fvia-C nowadays. > My program is also longer than the Python version. Yes, but for porting foreign code I think you did great. The use of strings, copied from the Python, looks a bit arcane in Haskell, but it shouldn't hurt anything. Perhaps you would gain something if you used Data.Map.! instead of your "lookup". Other than that, I'm not sure why your code runs slower than mine. Regards, Yitz From gale at sefer.org Sun Aug 26 16:17:14 2007 From: gale at sefer.org (Yitzchak Gale) Date: Sun Aug 26 16:08:13 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <1188149199.13256.8.camel@derek-laptop> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <1188149199.13256.8.camel@derek-laptop> Message-ID: <2608b8a80708261317l55d37bcx15a5d2cd5c7e6070@mail.gmail.com> Manu wrote: >> Should I introduce more strictness ? replace lists with more >> efficient data structures (ByteStrings, Arrays) ? Derek wrote: > Yes. Treating lists like arrays is always a recipe > for heartbreak. Here it costs very little - the lists are all short, mostly of length exactly 9. > If you did want to try to match the python code exactly > there are mutable arrays and such. I think Manu's code is about as exact as you can get for a direct translation into pure Haskell. You could emulate Python using imperitive-style Haskell, but that would be a different sort of port. If speed is really important for you, there are many ways to optimize a Haskell program - the techniques Derek mentioned, and many more, all the way down to low-level bit fiddling on the bare metal. There are some great people on this list who are very, very good at that. But I personally find that for my own purposes, pure, simple, clear Haskell is almost always more than fast enough. And it saves truckloads of debugging time. Regards, Yitz From emmanuel.delaborde at citycampus.com Sun Aug 26 17:17:38 2007 From: emmanuel.delaborde at citycampus.com (manu) Date: Sun Aug 26 17:06:12 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <20070826190733.660DB32465E@www.haskell.org> References: <20070826190733.660DB32465E@www.haskell.org> Message-ID: <6B01129E-C4B9-4F21-A644-9A6CB17375DF@citycampus.com> > From: Malte Milatz > Subject: Re: [Haskell-cafe] Norvig's Sudoku Solver in Haskell > > Your program was wrapped by your mail client, so you may want to > hpaste > your program for easier digestion. > here it is : http://hpaste.org/2452 > > Your profiling output suggests that much time is consumed by the > lookup > function. Since you're using (fromJust . lookup) everywhere anyway, a > data structure not envolving the Maybe type is probably a more succint > choice. And why bother with characters and strings? > no rationale except that's what the original Python script did use >> newV2 <- case length newCell of >> 0 -> Nothing >> 1 -> do let peersOfS = [ s' | s' <- lookup s peers ] >> res <- foldM eliminate newV (zip peersOfS >> (cycle newCell)) >> return res >> _ -> return newV > > The use of ?length? here is not an actual performance problem, but > unnecessary. Simply write: case newCell of [] -> ... > [_] -> ... > _ -> ... > > The same is valid for your other use of length. > > Malte I see, thanks ! E.D From luc.taesch at googlemail.com Sun Aug 26 17:16:17 2007 From: luc.taesch at googlemail.com (Luc TAESCH) Date: Sun Aug 26 17:07:16 2007 Subject: [Haskell-cafe] arrows-.02 fails when rebuilding ghc 6.6.1 Message-ID: <1be091cf0708261416r3e977d87x4b36056777976b81@mail.gmail.com> I try download and build 6.6.1 ( as ubntu has just 6.6 on package) and most went ok ( compiler and most libs) but arrows i tried and download arrow 0.2 from hackage but no more success any ideas ? ( knowing 6.6 is also on the machine if that matters) luc@haserv:~/src/arrows-0.2$ runghc Setup.hs build Preprocessing library arrows-0.2... Building arrows-0.2... [ 1 of 13] Compiling Data.Stream ( Data/Stream.hs, dist/build/Data/Stream.o ) [ 2 of 13] Compiling Control.Arrow.Transformer ( Control/Arrow/Transformer.hs, dist/build/Control/Arrow/Transformer.o ) [ 3 of 13] Compiling Control.Arrow.Operations ( Control/Arrow/Operations.hs, dist/build/Control/Arrow/Operations.o ) [ 4 of 13] Compiling Control.Arrow.Transformer.CoState ( Control/Arrow/Transformer/CoState.hs, dist/build/Control/Arrow/Transformer/CoState.o ) [ 5 of 13] Compiling Control.Arrow.Internals ( Control/Arrow/Internals.hs, dist/build/Control/Arrow/Internals.o ) [ 6 of 13] Compiling Control.Arrow.Transformer.Automaton ( Control/Arrow/Transformer/Automaton.hs, dist/build/Control/Arrow/Transformer/Automaton.o ) Control/Arrow/Transformer/Automaton.hs:98:0: Illegal instance declaration for `ArrowWriter w (Automaton a)' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowWriter w (Automaton a)' Control/Arrow/Transformer/Automaton.hs:104:0: Illegal instance declaration for `ArrowError r (Automaton a)' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowError r (Automaton a)' Control/Arrow/Transformer/Automaton.hs:115:0: Illegal instance declaration for `ArrowReader r (Automaton a)' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowReader r (Automaton a)' Control/Arrow/Transformer/Automaton.hs:120:0: Illegal instance declaration for `ArrowState s (Automaton a)' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowState s (Automaton a)' Control/Arrow/Transformer/Automaton.hs:126:0: Illegal instance declaration for `ArrowAddWriter w (Automaton a) (Automaton a')' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowAddWriter w (Automaton a) (Automaton a')' I discovered recently that my ubuntu package were providing only 6.6 and the latest cabal needs 6.6.1. when rebuilding this one from the tar ( not the head on darcs) most went ok but the arrows lib. I also tried to get it from hackage, but idem: ( I also have 6.6 on the machaine dos it matters ?) here is the build from hacakge with runghc : luc@haserv:~/src/arrows-0.2$ runghc Setup.hs build Preprocessing library arrows-0.2... Building arrows-0.2... [ 1 of 13] Compiling Data.Stream ( Data/Stream.hs, dist/build/Data/Stream.o ) [ 2 of 13] Compiling Control.Arrow.Transformer ( Control/Arrow/Transformer.hs, dist/build/Control/Arrow/Transformer.o ) [ 3 of 13] Compiling Control.Arrow.Operations ( Control/Arrow/Operations.hs, dist/build/Control/Arrow/Operations.o ) [ 4 of 13] Compiling Control.Arrow.Transformer.CoState ( Control/Arrow/Transformer/CoState.hs, dist/build/Control/Arrow/Transformer/CoState.o ) [ 5 of 13] Compiling Control.Arrow.Internals ( Control/Arrow/Internals.hs, dist/build/Control/Arrow/Internals.o ) [ 6 of 13] Compiling Control.Arrow.Transformer.Automaton ( Control/Arrow/Transformer/Automaton.hs, dist/build/Control/Arrow/Transformer/Automaton.o ) Control/Arrow/Transformer/Automaton.hs:98:0: Illegal instance declaration for `ArrowWriter w (Automaton a)' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowWriter w (Automaton a)' Control/Arrow/Transformer/Automaton.hs:104:0: Illegal instance declaration for `ArrowError r (Automaton a)' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowError r (Automaton a)' Control/Arrow/Transformer/Automaton.hs:115:0: Illegal instance declaration for `ArrowReader r (Automaton a)' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowReader r (Automaton a)' Control/Arrow/Transformer/Automaton.hs:120:0: Illegal instance declaration for `ArrowState s (Automaton a)' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowState s (Automaton a)' Control/Arrow/Transformer/Automaton.hs:126:0: Illegal instance declaration for `ArrowAddWriter w (Automaton a) (Automaton a')' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowAddWriter w (Automaton a) (Automaton a')' Control/Arrow/Transformer/Automaton.hs:135:0: Illegal instance declaration for `ArrowAddReader r (Automaton a) (Automaton a')' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowAddReader r (Automaton a) (Automaton a')' Control/Arrow/Transformer/Automaton.hs:144:0: Illegal instance declaration for `ArrowAddState r (Automaton a) (Automaton a')' (the Coverage Condition fails for one of the functional dependencies; Use -fallow-undecidable-instances to permit this) In the instance declaration for `ArrowAddState r (Automaton a) (Automaton a')' luc@haserv:~/src/arrows-0.2$ ------------------------------------------------------- here is a make from the build in the libraries tree under ghc 6.6.1 luc@haserv:~/Desktop/ghc-6.6.1-src/ghc-6.6.1/libraries/arrows$ make gcc -E -undef -traditional -P \ -DIMPORT_DIR='"/home/luc/Desktop/ghc-6.6.1-src/ghc-6.6.1/libraries/arrows"' \ -DLIB_DIR='"/home/luc/Desktop/ghc-6.6.1-src/ghc-6.6.1/libraries/arrows"' \ -DINCLUDE_DIR='"/home/luc/Desktop/ghc-6.6.1-src/ghc-6.6.1/libraries/arrows/include"' \ -DDATA_DIR='"/home/luc/Desktop/ghc-6.6.1-src/ghc-6.6.1/libraries/arrows"' \ -DHTML_DIR='"/home/luc/Desktop/ghc-6.6.1-src/ghc-6.6.1/libraries/arrows/html"' \ -DHADDOCK_IFACE='"/home/luc/Desktop/ghc-6.6.1-src/ghc-6.6.1/libraries/arrows/html/arrows.haddock"' \ -DFPTOOLS_TOP_ABS='"/home/luc/Desktop/ghc-6.6.1-src/ghc-6.6.1"' \ -x c -I../../includes -Iinclude -DPACKAGE=arrows -DVERSION=0.2.1 -DPKG_LIBDIR='"/usr/local/lib/ghc-6.6.1"' -DPKG_DATADIR='"/usr/local/share/ghc-6.6.1"' package.conf.in | \ grep -v '^#pragma GCC' | \ sed -e 's/""//g' -e 's/:[ ]*,/: /g' >package.conf.inplace gcc -E -undef -traditional -P -DINSTALLING \ -DIMPORT_DIR='"/usr/local/lib/ghc-6.6.1/imports"' \ -DLIB_DIR='"/usr/local/lib/ghc-6.6.1"' \ -DINCLUDE_DIR='"/usr/local/lib/ghc-6.6.1/include"' \ -DDATA_DIR='"/usr/local/share/ghc-6.6.1"' \ -DHTML_DIR='"/usr/local/share/ghc-6.6.1/html/libraries/arrows"' \ -DHADDOCK_IFACE='"/usr/local/share/ghc-6.6.1/html/libraries/arrows/arrows.haddock"' \ -x c -I../../includes -Iinclude -DPACKAGE=arrows -DVERSION=0.2.1 -DPKG_LIBDIR='"/usr/local/lib/ghc-6.6.1"' -DPKG_DATADIR='"/usr/local/share/ghc-6.6.1"' package.conf.in | \ grep -v '^#pragma GCC' | \ sed -e 's/""//g' -e 's/:[ ]*,/: /g' >package.conf.installed ../../utils/ghc-pkg/ghc-pkg-inplace update - --force-files > make: *** [Control/Arrow/Internals.o] Error 1 luc@haserv:~/Desktop/ghc-6.6.1-src/ghc-6.6.1/libraries/arrows$ From ross at soi.city.ac.uk Sun Aug 26 17:23:46 2007 From: ross at soi.city.ac.uk (Ross Paterson) Date: Sun Aug 26 17:14:53 2007 Subject: [Haskell-cafe] arrows-.02 fails when rebuilding ghc 6.6.1 In-Reply-To: <1be091cf0708261416r3e977d87x4b36056777976b81@mail.gmail.com> References: <1be091cf0708261416r3e977d87x4b36056777976b81@mail.gmail.com> Message-ID: <20070826212346.GA5748@soi.city.ac.uk> On Sun, Aug 26, 2007 at 11:16:17PM +0200, Luc TAESCH wrote: > I try download and build 6.6.1 ( as ubntu has just 6.6 on package) and > most went ok ( compiler and most libs) but arrows > > i tried and download arrow 0.2 from hackage but no more success You need to change the Extensions line in arrows.cabal to Extensions: MultiParamTypeClasses, UndecidableInstances From luc.taesch at googlemail.com Sun Aug 26 17:45:10 2007 From: luc.taesch at googlemail.com (Luc TAESCH) Date: Sun Aug 26 17:36:08 2007 Subject: [Haskell-cafe] Re: Ideas In-Reply-To: <20070826191253.GA28742@berkeley.edu> References: <46D01785.7070503@btinternet.com> <20070826174538.GA24444@berkeley.edu> <12337130.post@talk.nabble.com> <20070826191253.GA28742@berkeley.edu> Message-ID: <1be091cf0708261445o225e7b1aveb0521348131b41a@mail.gmail.com> thanks John for replying... when building , i cannot find the lcs mentionned in the cabal file not on hasckage nor on goggle. could you help? ( your papers on philosophy looks quite serious .. impressive you are in haskell too .. math backgroud ? logics ?) 2007/8/26, John MacFarlane : > > may i ask you what did you had in mind as an application when you started > > that ? > > This was just recreational programming: I wanted to see what writing a > web application in Haskell would be like. I think it would be great to > have a fully featured wiki program in Haskell, but I don't have time to > do it myself. Your idea sounds very interesting. Feel free to extend > pandocwiki if that works for you; it's GPL. > > John > > From gale at sefer.org Sun Aug 26 18:44:58 2007 From: gale at sefer.org (Yitzchak Gale) Date: Sun Aug 26 18:35:56 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <85F62D4F-C1E6-4118-A289-2D9CC793A047@citycampus.com> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <2608b8a80708261223s3058f5acy1efdf1ddbab2ea16@mail.gmail.com> <85F62D4F-C1E6-4118-A289-2D9CC793A047@citycampus.com> Message-ID: <2608b8a80708261544o6156ee36va79f3b4d6a024974@mail.gmail.com> I wrote: >> Perhaps you would gain something if you used Data.Map.! >> instead of your "lookup". Manu wrote: > I'm not sure I understand, do you mean I should have use a strict Map > constructor ? > like : Map !key !value ? No, there is an operator in Data.Map called "!". > how can it replace the lookup function ? Use > import qualified Data.Map as M > import Data.Map (!) Then, instead of "lookup k m" use "m ! k". >> Other than that, I'm not >> sure why your code runs slower than mine. Malte Milatz wrote: MM> The use of "length" here is not an actual MM> performance problem... Maybe not there, but I think Malte's suggestion might actually improve performance if you do the same thing a few lines further down, where you wrote: > case length dPlaces of By using Malte's idea there instead of length, you might allow some calculations inside dPlaces to be lazily skipped. Regards, Yitz From jgm at berkeley.edu Sun Aug 26 18:57:27 2007 From: jgm at berkeley.edu (John MacFarlane) Date: Sun Aug 26 18:48:36 2007 Subject: [Haskell-cafe] Re: Ideas In-Reply-To: <1be091cf0708261445o225e7b1aveb0521348131b41a@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <20070826174538.GA24444@berkeley.edu> <12337130.post@talk.nabble.com> <20070826191253.GA28742@berkeley.edu> <1be091cf0708261445o225e7b1aveb0521348131b41a@mail.gmail.com> Message-ID: <20070826225727.GA5152@berkeley.edu> lcs can be found at http://urchin.earth.li/darcs/igloo/lcs/ +++ Luc TAESCH [Aug 26 07 23:45 ]: > when building , i cannot find the lcs mentionned in the cabal file not > on hasckage nor on goggle. > could you help? From chaddai.fouche at gmail.com Sun Aug 26 19:34:52 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Sun Aug 26 19:25:50 2007 Subject: [Haskell-cafe] Style In-Reply-To: <2608b8a80708260953m13a7924vd83b360779016f2a@mail.gmail.com> References: <46CE8640.8040508@xs4all.nl> <2608b8a80708260413y1f8f7dbfg162448b485cacf70@mail.gmail.com> <2608b8a80708260953m13a7924vd83b360779016f2a@mail.gmail.com> Message-ID: 2007/8/26, Yitzchak Gale : > True, that is not the problem. > > Using length forces the result to > be Int, which is different than all of > the other tm's so far. So for example, > try this: > > [n | n <- [0..25], tm_silly n /= tm n] > You mean to say that tm_silly returns Int, which means we can't use it directly in a comparison but have to use toInteger or fromInteger ? Ok, in this case, but it's still a nice test for our more optimized functions (and using genericLength is much slower than toInteger . length, though of course the results differ for really long list) $> [n | n <- [1..1000], toInteger (tm_silly n) /= tm n] [] -- Jeda? From levi.stephen at optusnet.com.au Sun Aug 26 20:34:26 2007 From: levi.stephen at optusnet.com.au (Levi Stephen) Date: Sun Aug 26 20:25:48 2007 Subject: [Haskell-cafe] Help understanding a partial application Message-ID: <46D21C12.40209@optusnet.com.au> Hi, I was browsing through the source code for Data.Foldable and having trouble comprehending it (which was kind of the point of browsing the code, so I could learn something ;) ) I'm looking at foldl foldl :: (c -> d -> c) -> c -> t d -> c foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z But, I haven't got very far. I'm still trying to follow: Endo . flip f f is of type c->d->c, so this makes flip f of type d->c->c. I think the Endo constructor is of type (a->a)->Endo a I think a is binding to a function type here, but can not work out what. (From memory) ghci reports > :t Endo . flip (+) Num a => a -> Endo a So, this looks like a partial application of the constructor? But, this still isn't helping me understand. Any thoughts or pointers that might help me comprehend what's happening? Thanks, Levi lstephen.wordpress.com From tmorris at tmorris.net Sun Aug 26 21:04:58 2007 From: tmorris at tmorris.net (Tony Morris) Date: Sun Aug 26 20:56:01 2007 Subject: [Haskell-cafe] Geometry Message-ID: <46D2233A.1070207@tmorris.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I went camping on the weekend and a friend of mine who is a builder asked me many questions on geometry as they apply to his every day work - - most of which I could answer. However, there was one that I couldn't and I am having trouble googling a solution (for lack of keywords?). I'm hoping a fellow Haskeller could help me out (in Haskell of course). The problem is finding the unknown x from the two knowns a and b in the given image below (excuse my Microsoft Paintbrush skills). I may have misunderstood his problem (we were drawing in dirt) and actually, it is the straight line between the two points on the circumference that are known and not the specified 'b', but I figure I could derive one solution from another if I have misunderstood him. Here is my image: http://tinyurl.com/2kgsjy Thanks for any tips or keywords with which to google! - -- Tony Morris http://tmorris.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFG0iM6mnpgrYe6r60RAqfDAJ4gFAdr7zP1ehLl8H2MaCzCNfAvhQCgmL8D 4nrxrK13O9EBNv/ojPIMJXI= =eaxX -----END PGP SIGNATURE----- From joelkoerwer at gmail.com Sun Aug 26 21:23:09 2007 From: joelkoerwer at gmail.com (Joel Koerwer) Date: Sun Aug 26 21:14:07 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: <46D2233A.1070207@tmorris.net> References: <46D2233A.1070207@tmorris.net> Message-ID: <34e5cfb80708261823w684d2ffdt407140df64d8675c@mail.gmail.com> Hi Tony, x is called the sagitta. At least when making a telescope mirror it is[1]. By bisecting your angle with another radius, you'll see that you have a right triangle with hypotenuse a, and legs of length (b/2) and (a-x). Then sagitta a b = a - sqrt (a*a - b*b/4) Considered as a function of half the angle subtended by the points on the circumference, this is called the versine. http://en.wikipedia.org/wiki/Versine [1] http://www.stellafane.com/atm/atm_grind/atm_measure_sag.htm From chaddai.fouche at gmail.com Sun Aug 26 21:24:14 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Sun Aug 26 21:15:12 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: <46D2233A.1070207@tmorris.net> References: <46D2233A.1070207@tmorris.net> Message-ID: You've got a which is the radius of the circle, and b which is the length of the arc, thus you've got the angle between the two red radiuses : u = b / a So with basic trigonometry, we can deduce a - x = a * cos(u/2) x = a *( cos(u/2) - 1) -- Jeda? From stefanor at cox.net Sun Aug 26 21:24:19 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Sun Aug 26 21:15:29 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: <46D2233A.1070207@tmorris.net> References: <46D2233A.1070207@tmorris.net> Message-ID: <20070827012419.GA3954@localhost.localdomain> On Mon, Aug 27, 2007 at 11:04:58AM +1000, Tony Morris wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I went camping on the weekend and a friend of mine who is a builder > asked me many questions on geometry as they apply to his every day work > - - most of which I could answer. > > However, there was one that I couldn't and I am having trouble googling > a solution (for lack of keywords?). I'm hoping a fellow Haskeller could > help me out (in Haskell of course). > > The problem is finding the unknown x from the two knowns a and b in the > given image below (excuse my Microsoft Paintbrush skills). I may have > misunderstood his problem (we were drawing in dirt) and actually, it is > the straight line between the two points on the circumference that are > known and not the specified 'b', but I figure I could derive one > solution from another if I have misunderstood him. > > Here is my image: > http://tinyurl.com/2kgsjy This is a fairly simple exercise in trigonometry. Call the angle subtended by b, ?. Then: b = a sin(?/2) a - x = a cos(?/2) by the relation between circles and trig functions. From this we can (algebraicly) derive: sin(?/2) = b / a x = a - a cos(?/2) x = a - a (1 - b? / a?)^? (nb, I'm assuming ? is less than 180? here) And as you request: problem a b = a - a * sqrt (1 - b*b / a*a) Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070826/da84ba78/attachment.bin From chaddai.fouche at gmail.com Sun Aug 26 21:27:45 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Sun Aug 26 21:18:42 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: References: <46D2233A.1070207@tmorris.net> Message-ID: 2007/8/27, Chadda? Fouch? : > You've got a which is the radius of the circle, and b which is the > length of the arc, thus you've got the angle between the two red > radiuses : u = b / a > So with basic trigonometry, we can deduce a - x = a * cos(u/2) > x = a *( cos(u/2) - 1) > > -- > Jeda? > Actually that would be x = a * (1 - cos (b/(2a))) Ooops o_O -- Jeda? From steve at fenestra.com Sun Aug 26 21:30:30 2007 From: steve at fenestra.com (Steve Schafer) Date: Sun Aug 26 21:21:32 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: <46D2233A.1070207@tmorris.net> References: <46D2233A.1070207@tmorris.net> Message-ID: On Mon, 27 Aug 2007 11:04:58 +1000, you wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > >I went camping on the weekend and a friend of mine who is a builder >asked me many questions on geometry as they apply to his every day work >- - most of which I could answer. > >However, there was one that I couldn't and I am having trouble googling >a solution (for lack of keywords?). I'm hoping a fellow Haskeller could >help me out (in Haskell of course). > >The problem is finding the unknown x from the two knowns a and b in the >given image below (excuse my Microsoft Paintbrush skills). I may have >misunderstood his problem (we were drawing in dirt) and actually, it is >the straight line between the two points on the circumference that are >known and not the specified 'b', but I figure I could derive one >solution from another if I have misunderstood him. > >Here is my image: >http://tinyurl.com/2kgsjy > >Thanks for any tips or keywords with which to google! So a is the radius of the circle, and b is half the length of the chord. From basic trigonometry: b = a * sin @ where @ is half of the angle between the two radii as drawn in the picture. Then: x = a * (1 - cos @) Using the trigonometric identity sin^2 @ + cos^2 @ = 1 and rearranging, we get: x = a - sqrt(a^2 - b^2) I don't know offhand if there's a straightforward way to arrive at this result without using trigonometry. By the way, I found http://www.1728.com/circsect.htm by Googling height chord. Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ From steve at fenestra.com Sun Aug 26 21:32:13 2007 From: steve at fenestra.com (Steve Schafer) Date: Sun Aug 26 21:23:14 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: References: <46D2233A.1070207@tmorris.net> Message-ID: On Sun, 26 Aug 2007 21:30:30 -0400, you wrote: >I don't know offhand if there's a straightforward way to arrive at this >result without using trigonometry. Duh. Of course there is.... Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ From ryani.spam at gmail.com Mon Aug 27 00:54:21 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Mon Aug 27 00:45:17 2007 Subject: [Haskell-cafe] Help understanding a partial application In-Reply-To: <46D21C12.40209@optusnet.com.au> References: <46D21C12.40209@optusnet.com.au> Message-ID: <2f9b2d30708262154g1fd1700fobc80592cd0445236@mail.gmail.com> Just expand out the function composition: Dual . Endo . flip f = (\x -> Dual (Endo (flip f x))) which has the type d -> Dual (Endo c). -- ryan On 8/26/07, Levi Stephen wrote: > > Hi, > > I was browsing through the source code for Data.Foldable and having > trouble > comprehending it (which was kind of the point of browsing the code, so I > could > learn something ;) ) > > I'm looking at foldl > > foldl :: (c -> d -> c) -> c -> t d -> c > foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z > > But, I haven't got very far. I'm still trying to follow: > > Endo . flip f > > f is of type c->d->c, so this makes flip f of type d->c->c. > > I think the Endo constructor is of type (a->a)->Endo a > > I think a is binding to a function type here, but can not work out what. > > (From memory) ghci reports > > > :t Endo . flip (+) > Num a => a -> Endo a > > So, this looks like a partial application of the constructor? > > But, this still isn't helping me understand. > > Any thoughts or pointers that might help me comprehend what's happening? > > Thanks, > Levi > lstephen.wordpress.com > _______________________________________________ > 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/haskell-cafe/attachments/20070826/cb03b9ba/attachment-0001.htm From levi.stephen at optusnet.com.au Mon Aug 27 01:22:26 2007 From: levi.stephen at optusnet.com.au (Levi Stephen) Date: Mon Aug 27 01:13:29 2007 Subject: [Haskell-cafe] Help understanding a partial application In-Reply-To: <2f9b2d30708262154g1fd1700fobc80592cd0445236@mail.gmail.com> References: <46D21C12.40209@optusnet.com.au> <2f9b2d30708262154g1fd1700fobc80592cd0445236@mail.gmail.com> Message-ID: <46D25F92.4080809@optusnet.com.au> Ryan Ingram wrote: > Just expand out the function composition: > Dual . Endo . flip f = (\x -> Dual (Endo (flip f x))) > which has the type d -> Dual (Endo c). > > -- ryan > Aha. I didn't get this straight away, but once I looked at the type signature for function composition, it became clear. Thanks, Levi From emmanuel.delaborde at citycampus.com Mon Aug 27 04:09:17 2007 From: emmanuel.delaborde at citycampus.com (manu) Date: Mon Aug 27 03:57:54 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <200708262256.26873.daniel.is.fischer@web.de> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <200708262256.26873.daniel.is.fischer@web.de> Message-ID: Daniel Fischer's modifications to my original program lead to a 400 % speed boost !!! (It now runs in 22 seconds on my machine) He avoided unecessary calls to 'length', uses Array instead of Map, refactored 'search' function (details below) I've put up his version on hpaste : http://hpaste.org/2452#a1 Manu On Aug 26, 2007, at 10:56 PM, Daniel Fischer wrote: > Without much thinking I can spped it up by a factor of 4 (from 280s > to 60s). > The most important things are: > - don't use length unless you need it > instead of > newV2 <- case length newCell of > 0 -> Nothing > ... > and > case length dPlaces of > 0 -> ... > use > case newCell of > [] -> Nothing > [d'] -> ... > and > case dPlaces of > [] -> Nothing > [s'] -> ... > > - let dPlaces = [ s' | u <- lookup s units, s' <- u, elem d (lookup > s' newV2)] > is bad > let dPlaces = [s' | s' <- lookup s peers, elem d (lookup s' newV2)] > scans each peer only once > > - search is really bad, you lookup all squares several times, > potentially > compute all lengths multiple times... > much better is > > search :: Grid -> Maybe Grid > search g = case [(l,a) | a@(_,xs) <- M.assocs g, let l = length xs, > l /= 1] of > [] -> return g > ls -> do let (_,(s,ds)) = minimum ls > msum [assign g (s,d) >>= search | d <- ds] > > (I also changed the type, and instead of foldl' you should use > foldr, since > "some" is lazy in the second argument, further, since Maybe is a > MonadPlus, > it's "mplus" and 'foldr mplus Nothing' is msum) > > - Maps aren't good here, too slow lookup and you know the keys, so > use arrays > From luc.taesch at gmail.com Mon Aug 27 05:34:45 2007 From: luc.taesch at gmail.com (luc.taesch) Date: Mon Aug 27 05:25:42 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <20070826225727.GA5152@berkeley.edu> References: <46D01785.7070503@btinternet.com> <20070826174538.GA24444@berkeley.edu> <12337130.post@talk.nabble.com> <20070826191253.GA28742@berkeley.edu> <1be091cf0708261445o225e7b1aveb0521348131b41a@mail.gmail.com> <20070826225727.GA5152@berkeley.edu> Message-ID: <12344039.post@talk.nabble.com> All went finally fine. wiki is live. thanks for your help. great example. this helped me progressing my understanding of happs. This should conveniently go on the happs tutorial wiki., or at least be referred to . (I have seen alex is doing some tutorial on a wiki in the latest head release, so definitively this is the topic of the day !!) fyi, the cabal run (runghc) could not find the Diff file ( in the same directory anyway) o_o but ghc --make PanDocwiki.hs had it ok.) John MacFarlane wrote: > > lcs can be found at http://urchin.earth.li/darcs/igloo/lcs/ > > +++ Luc TAESCH [Aug 26 07 23:45 ]: >> when building , i cannot find the lcs mentionned in the cabal file not >> on hasckage nor on goggle. >> could you help? > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > -- View this message in context: http://www.nabble.com/Ideas-tf4327747.html#a12344039 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From jon at ffconsultancy.com Mon Aug 27 05:24:47 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon Aug 27 05:26:41 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <200708262256.26873.daniel.is.fischer@web.de> Message-ID: <200708271024.47735.jon@ffconsultancy.com> On Monday 27 August 2007 09:09:17 manu wrote: > Daniel Fischer's modifications to my original program lead to a 400 % > speed boost !!! > (It now runs in 22 seconds on my machine) > He avoided unecessary calls to 'length', uses Array instead of Map, > refactored 'search' function (details below) > > I've put up his version on hpaste : http://hpaste.org/2452#a1 You shouldn't have any problem writing a purely functional solver that is faster and much shorter than Norvig's Python without having to use arrays. The following purely functional OCaml solver is faster than Norvig's, for example, and uses lists, tuples and maps: open List let invalid (i, j) (i', j') = i=i' || j=j' || i/3=i'/3 && j/3=j'/3 let select p n p' ns = if invalid p p' then filter ((<>) n) ns else ns let cmp (_, l1) (_, l2) = compare (length l1) (length l2) let add p n sols = sort cmp (map (fun (p', ns) -> p', select p n p' ns) sols) module Map = Map.Make(struct type t = int * int let compare = compare end) let rec search f sol = function | [] -> f sol | (p, ns)::sols -> iter (fun n -> search f (Map.add p n sol) (add p n sols)) ns -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/?e From hughperkins at gmail.com Mon Aug 27 05:42:18 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Mon Aug 27 05:33:15 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <20070825190804.GA5305@localhost.localdomain> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> <46D07852.4080808@btinternet.com> <20070825190804.GA5305@localhost.localdomain> Message-ID: <837db430708270242r356c9c8cqe723563772d3574c@mail.gmail.com> On 8/26/07, Stefan O'Rear wrote: > Actually, we aren't. You might not have been able to tell, but a core > goal of our community is to stay small and avoid success at all costs; > our language is not practical, not designed to be practical, and if it > ever becomes practical, it will have done so only by a terrible streak > of bad luck. Remember, success breeds inertia, and inertia would ruin > our fundamental goal of being an agile research language. Yes! We agree :-) Can someone please do something about the horrible paragraph at the end of this page here: http://www.haskell.org/complex/why_does_haskell_matter.html , which is what inspired my rather passive/agressive attitude to the Haskell community ;-) "Another reaso for the lack of Haskell, and other functional languages, in mainstream use is that programming languages are rarely thought of as tools (even though they are). To most people their favorite programming language is much more like religion - it just seems unlikely that any other language exists that can get the job done better and faster. There is a paper by Paul Graham called Beating the Averages describing his experience using Lisp, another functional language, for an upstart company. In it he uses an analogy which he calls "The Blub Paradox". It goes a little something like this: If a programmer's favorite language is Blub, which is positioned somewhere in the middle of the "power spectrum", he can most often only identify languages that are lower down in the spectrum. He can look at COBOL and say "How can anyone get anything done in that language, it doesn't have feature x", x being a feature in Blub. However, this Blub programmer has a harder time looking the other way in the spectrum. If he examines languages that are higher up in the power spectrum, they will just seem "weird" because the Blub programmer is "thinking in Blub" and can not possibly see the uses for various features of more powerful languages. It goes without saying that this inductively leads to the conclusion that to be able to compare all languages you'll need to position yourself at the top of the power spectrum. It is my belief that functional languages, almost by definition, are closer to the top of the power spectrum than imperative ones. So languages can actually limit a programmers frame of thought. If all you've ever programmed is Blub, you may not see the limitations of Blub - you may only do that by switching to another level which is more powerful." The author of this paragraph fails to realize that the Blub Paradox cut both ways ;-) Anyway, there I've said it, so that's out of the way perhaps :-D From hughperkins at gmail.com Mon Aug 27 05:45:23 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Mon Aug 27 05:36:20 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <837db430708270242r356c9c8cqe723563772d3574c@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> <46D07852.4080808@btinternet.com> <20070825190804.GA5305@localhost.localdomain> <837db430708270242r356c9c8cqe723563772d3574c@mail.gmail.com> Message-ID: <837db430708270245t6d971312qb013bc0d5a027989@mail.gmail.com> Oooo... just noticed that the page is not anonymous.... errrmmmm :-D From hughperkins at gmail.com Mon Aug 27 05:47:34 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Mon Aug 27 05:38:31 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <837db430708270245t6d971312qb013bc0d5a027989@mail.gmail.com> References: <46D01785.7070503@btinternet.com> <404396ef0708250511r34aaf29fu48dc0f9026ed63b9@mail.gmail.com> <46D02190.8030106@btinternet.com> <404396ef0708250538r6aff00fdr120d317255d1bd32@mail.gmail.com> <46D07852.4080808@btinternet.com> <20070825190804.GA5305@localhost.localdomain> <837db430708270242r356c9c8cqe723563772d3574c@mail.gmail.com> <837db430708270245t6d971312qb013bc0d5a027989@mail.gmail.com> Message-ID: <837db430708270247s1b47f84en2cd84ca7c51ae1d0@mail.gmail.com> On 8/27/07, Hugh Perkins wrote: > Oooo... just noticed that the page is not anonymous.... errrmmmm :-D > FWIW, the rest of the page is awesome. Good work. It was one of the pages that inspired me to look at Haskell. From daniel.is.fischer at web.de Mon Aug 27 06:54:20 2007 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Aug 27 06:44:33 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <200708271024.47735.jon@ffconsultancy.com> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <200708271024.47735.jon@ffconsultancy.com> Message-ID: <200708271254.20656.daniel.is.fischer@web.de> Am Montag, 27. August 2007 11:24 schrieb Jon Harrop: > On Monday 27 August 2007 09:09:17 manu wrote: > > Daniel Fischer's modifications to my original program lead to a 400 % > > speed boost !!! > > (It now runs in 22 seconds on my machine) > > He avoided unecessary calls to 'length', uses Array instead of Map, > > refactored 'search' function (details below) > > > > I've put up his version on hpaste : http://hpaste.org/2452#a1 > > You shouldn't have any problem writing a purely functional solver that is > faster and much shorter than Norvig's Python without having to use arrays. Probably not, but what's wrong with using arrays (here and in general)? Here I find arrays very natural, after all a grid has a fixed set of indices. And as they have a much faster lookup than maps (not to mention lists), what do you gain by avoiding them? > > The following purely functional OCaml solver is faster than Norvig's, for > example, and uses lists, tuples and maps: Since I don't speak OCaml, could you translate it to haskell? Cheers, Daniel From jon at ffconsultancy.com Mon Aug 27 08:40:17 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon Aug 27 08:42:10 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <200708271254.20656.daniel.is.fischer@web.de> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <200708271024.47735.jon@ffconsultancy.com> <200708271254.20656.daniel.is.fischer@web.de> Message-ID: <200708271340.18285.jon@ffconsultancy.com> On Monday 27 August 2007 11:54:20 you wrote: > Am Montag, 27. August 2007 11:24 schrieb Jon Harrop: > > You shouldn't have any problem writing a purely functional solver that is > > faster and much shorter than Norvig's Python without having to use > > arrays. > > Probably not, but what's wrong with using arrays (here and in general)? > Here I find arrays very natural, after all a grid has a fixed set of > indices. And as they have a much faster lookup than maps (not to mention > lists), what do you gain by avoiding them? Elegance, brevity and (for short implementations) performance. Although this algorithm certainly involves getting and setting puzzle entries from a square array, there is little benefit in constraining your solver to reflect that explicitly in its concrete data structures. Compilers like GHC will be extremely good at performing low-level optimizations on list-intensive algorithms. So the performance overhead of using lists rather than arrays in a functional language will be small. Externally, using lists makes it easier to pluck out one choice and the remaining choices when searching. That is, after all, the core of this algorithm. > > The following purely functional OCaml solver is faster than Norvig's, for > > example, and uses lists, tuples and maps: > > > Since I don't speak OCaml, could you translate it to haskell? I don't speak Haskell yet but I can translate it into English: A puzzle is represented by an association list that maps each coordinate onto its possible solutions. Initially, coordinates set in the puzzle map onto singleton lists (e.g. ((3, 4), [7]) means position 3,4 in the solution must contain 7) and unset coordinates map onto [1..9]. To search for a solution, you accumulate the solution in another association list (e.g. ((3, 4), 7) means that 3,4 contains 7 in the solution). You take the coordinate with the shortest list of possibilities first and the list of remaining coordinates. You try each of the possibilities listed in turn, pushing that choice onto the current solution and filtering out all invalidated solutions from the remaining list before recursing. That's it. Choosing the shortest list first corresponds to constraint propagation. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/?e From daniel.is.fischer at web.de Mon Aug 27 10:27:54 2007 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Aug 27 10:18:23 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <200708271340.18285.jon@ffconsultancy.com> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <200708271254.20656.daniel.is.fischer@web.de> <200708271340.18285.jon@ffconsultancy.com> Message-ID: <200708271627.55061.daniel.is.fischer@web.de> Am Montag, 27. August 2007 14:40 schrieb Jon Harrop: > > Probably not, but what's wrong with using arrays (here and in general)? > > Here I find arrays very natural, after all a grid has a fixed set of > > indices. And as they have a much faster lookup than maps (not to mention > > lists), what do you gain by avoiding them? > > Elegance, brevity and (for short implementations) performance. Although > this algorithm certainly involves getting and setting puzzle entries from a > square array, there is little benefit in constraining your solver to > reflect that explicitly in its concrete data structures. I'm not convinced (yet). Elegance: well, yes in general; if you don't know the size of the problem in advance certainly. But here? Brevity: okay, "Map.fromList" is shorter than "array ((0,0),(8,8))", but not awfully much so, and you write "grid!s" regardless of whether grid is a Map or an array. So without further elaboration I remain unconvinced of that point. Performance: in my experience arrays are usually much faster (if the algorithm is suited to using them, if not, it's a different story, of course). > > Compilers like GHC will be extremely good at performing low-level > optimizations on list-intensive algorithms. So the performance overhead of > using lists rather than arrays in a functional language will be small. That VERY MUCH depends. I usually use lists for the Project Euler problems first (1. I love lists, 2. list code is often far more natural - and hence more elegant) and sometimes afterwards re-code it using arrays (boxed arrays or ST(U)Arrays). More often than not that reduces run time by orders of magnitude(factors between 10 and 100 are common, larger or smaller factors occur). I doubt it's just that my array code is better suited for GHC's optimiser than my list code. Maps I found to perform in between and they are rather memory-hungry. > > Externally, using lists makes it easier to pluck out one choice and the > remaining choices when searching. That is, after all, the core of this > algorithm. Just to make it clear, you are here talking about the list of possibilities for some square? Or are you talking about using a list of (square, list of possibilites) pairs? If the former: I represent the grid as an Array (Char,Char) [Char], replacing the original representation as a Map String [Char], so I keep that. Although, in my own solver I keep the set of possibilities for each square as an EnumSet (now Data.Set.Enum in the collections package, maybe I should update my code), that gains a factor of 2 over lists for the good old 9x9 grids, more than 10 for 16x16 grids, I fear trying 25x25 grids. However, I use deduction strategies that involve forming unions and differences of several sets of possibilities, operations which are weak spots of lists. > > > > The following purely functional OCaml solver is faster than Norvig's, > > > for example, and uses lists, tuples and maps: > > > > > > Since I don't speak OCaml, could you translate it to haskell? > > I don't speak Haskell yet but I can translate it into English: > > A puzzle is represented by an association list that maps each coordinate > onto its possible solutions. Initially, coordinates set in the puzzle map > onto singleton lists (e.g. ((3, 4), [7]) means position 3,4 in the solution > must contain 7) and unset coordinates map onto [1..9]. > > To search for a solution, you accumulate the solution in another > association list (e.g. ((3, 4), 7) means that 3,4 contains 7 in the > solution). You take the coordinate with the shortest list of possibilities > first and the list of remaining coordinates. You try each of the > possibilities listed in turn, pushing that choice onto the current solution > and filtering out all invalidated solutions from the remaining list before > recursing. > > That's it. Choosing the shortest list first corresponds to constraint > propagation. Thought it was something like that. Must check whether that beats Norvig's constraint propagation. Cheers, Daniel From bf3 at telenet.be Mon Aug 27 10:29:38 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Mon Aug 27 10:20:35 2007 Subject: [Haskell-cafe] Newbie terminology for partial application Message-ID: <46D2DFD2.9000203@telenet.be> A while ago I confused "currying" with "partial application", which was pointed out by members of this community, and the wiki pages got adapted so that newbies like me don't make the same mistake twice ;) That's great. Anyway, at the risk of making mistakes again, I'm looking for good terminilogy when talking about "partial application". For example: -- uncurried form *f (x,y)* = -- whatever -- curried form *g x y *= f (x,y) -- partial application *h x *= g x But when writing text documents, I guess it is common to say "/g is curried/", but is it also common to say /"g is partially applied"? /The latter sounds silly to a non-native speaker like myself... Or shouldn't it be? / /And what is "application"? I guess it means that (g x y) is internally translated to ((g $ x) $ y) which is translated into (apply (apply g x) y) where apply is a primitive function? Thanks, Peter PS: sorry for the poor English! / / From bf3 at telenet.be Mon Aug 27 11:04:17 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Mon Aug 27 10:55:10 2007 Subject: [Haskell-cafe] "quoting" in Haskell Message-ID: <46D2E7F1.9080905@telenet.be> In Scheme, on can "quote" code, so that it becomes data. Microsoft's F# and C# 3.0 also have something similar that turns code into "expression trees". The latter is used extensively in LINQ which translates plain C# code into SQL code or any other code at runtime (this idea came from FP I heared) I can't find something similar for Haskell? Maybe I am looking at the wrong places? In Haskell, I know one can use a data constructor as a function (as in (map Just [1..3])), but a function cannot be turned into a data constructor (= "quoting"), can it? Now this is all really fuzzy for a newbie like me, because aren't all functions initially just data constructors waiting to be evaluated in a lazy language? I'm actually looking for something like (loose terminilogy follows) "context-based-semi-quoting". The idea is to only quote a set of functions, while evaluating all the others. For example, in the code 1 `add` 2 `mul` 3 where add = (+) mul = (*) I want to write something like selectiveQuote [add] (1 `add` 2 `mul` 3) which would result in an expression tree like add / \ 1 6 So the `mul` is not quoted because it is not part of the "context" = [add] Maybe this is just impossible, I did not dig deep into this. Thanks, Peter From chaddai.fouche at gmail.com Mon Aug 27 11:13:16 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Mon Aug 27 11:04:12 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: <200708271627.55061.daniel.is.fischer@web.de> References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <200708271254.20656.daniel.is.fischer@web.de> <200708271340.18285.jon@ffconsultancy.com> <200708271627.55061.daniel.is.fischer@web.de> Message-ID: For the translation of the above OCaml code, there is not much to do, in fact it is mostly functional, and so easily translated in Haskell code, note that I add a code to handle input of the form "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......", to resolve it and print a solution : import Data.Ix import Data.List import Data.Char import qualified Data.Map as M invalid :: (Int, Int) -> (Int, Int) -> Bool invalid (i, j) (i', j') = i==i' || j==j' || (i `div` 3 == i' `div` 3 && j `div` 3 == j' `div` 3) select p n p' ns = if invalid p p' then filter (/= n) ns else ns cmp (_, l1) (_, l2) = (length l1) `compare` (length l2) add p n sols = sortBy cmp $ map (\(p', ns) -> (p', select p n p' ns)) sols search f sol [] = f sol search f sol ((p, ns):sols) = concatMap (\n -> search f (M.insert p n sol) (add p n sols)) ns My additions : base :: [((Int, Int),[Int])] base = [((i,j), [1..9]) | i <- [0..8], j <- [0..8]] createBoard input = foldr constraint (M.empty, purge base input) input where constraint (p, [n]) (sol,sols) = (M.insert p n sol,add p n sols) purge b i = filter (maybe True (const False) . flip lookup i . fst) b inputBoard :: String -> [((Int, Int), [Int])] inputBoard = filter (not . null . snd) . zip (range ((0,0),(8,8))) . map (\c -> if isDigit c then [read [c]] else []) showSol = unlines . concat . intersperse ([replicate 15 '-']) . split 3 . map (unwords . intersperse "|" . split 3) . split 9 . map (chr . (+ ord '0')) . M.elems where split n = takeWhile (not . null) . unfoldr (Just . splitAt n) solve = head . uncurry (search ((:[]).showSol)) . createBoard . inputBoard main = interact $ solve -- Jeda? From v.dijk.bas at gmail.com Mon Aug 27 11:13:16 2007 From: v.dijk.bas at gmail.com (Bas van Dijk) Date: Mon Aug 27 11:04:23 2007 Subject: [Haskell-cafe] "quoting" in Haskell In-Reply-To: <46D2E7F1.9080905@telenet.be> References: <46D2E7F1.9080905@telenet.be> Message-ID: On 8/27/07, Peter Verswyvelen wrote: > In Scheme, on can "quote" code, so that it becomes data. Microsoft's F# > and C# 3.0 also have something similar that turns code into "expression > trees". The latter is used extensively in LINQ which translates plain C# > code into SQL code or any other code at runtime (this idea came from FP > I heared) > > I can't find something similar for Haskell? Maybe I am looking at the > wrong places? > > In Haskell, I know one can use a data constructor as a function (as in > (map Just [1..3])), but a function cannot be turned into a data > constructor (= "quoting"), can it? > > Now this is all really fuzzy for a newbie like me, because aren't all > functions initially just data constructors waiting to be evaluated in a > lazy language? > > I'm actually looking for something like (loose terminilogy follows) > "context-based-semi-quoting". The idea is to only quote a set of > functions, while evaluating all the others. > > For example, in the code > > 1 `add` 2 `mul` 3 > where > add = (+) > mul = (*) > > I want to write something like > > selectiveQuote [add] (1 `add` 2 `mul` 3) > > which would result in an expression tree like > > add > / \ > 1 6 > > So the `mul` is not quoted because it is not part of the "context" = [add] > > Maybe this is just impossible, I did not dig deep into this. > > Thanks, > Peter > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > Look at Template Haskell. quote from http://haskell.org/th : "Intuitively Template Haskell provides new language features that allow us to convert back and forth between concrete syntax, i.e. what you would type when you write normal Haskell code, and abstract syntax trees. These abstract syntax trees are represented using Haskell datatypes and, at compile time, they can be manipulated by Haskell code. This allows you to reify (convert from concrete syntax to an abstract syntax tree) some code, transform it and splice it back in (convert back again), or even to produce completely new code and splice that in, while the compiler is compiling your module." However I don't know if your 'selectiveQuote' is possible using TH. regards, Bas van Dijk From bf3 at telenet.be Mon Aug 27 11:56:43 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Mon Aug 27 11:47:38 2007 Subject: [Haskell-cafe] "quoting" in Haskell In-Reply-To: References: <46D2E7F1.9080905@telenet.be> Message-ID: <46D2F43B.6070208@telenet.be> > Look at Template Haskell. > "Intuitively Template Haskell provides new language features that > allow us to convert back and forth between concrete syntax, i.e. what Gee coming from C++ that was the last thing I expected "templates" to do. It seems a bit more powerful in Haskell though! I'll look into that! Thanks, Peter From gleb.alexeev at gmail.com Mon Aug 27 12:04:52 2007 From: gleb.alexeev at gmail.com (Gleb Alexeyev) Date: Mon Aug 27 11:56:06 2007 Subject: [Haskell-cafe] Re: [ANN] An efficient lazy suffix tree library In-Reply-To: <46CBAD5A.8020408@serpentine.com> References: <46CBAD5A.8020408@serpentine.com> Message-ID: Bryan O'Sullivan wrote: > I just posted a library named suffixtree to Hackage. > > http://www.serpentine.com/software/suffixtree/ > > It implements Giegerich and Kurtz's lazy construction algorithm, with a > few tweaks for better performance and resource usage. > > API docs: > > http://darcs.serpentine.com/suffixtree/dist/doc/html/Data-SuffixTree.html > > I've tested it on multi-megabyte input strings. > I think I found a bug: import qualified Data.SuffixTree as T > T.countRepeats "ab" (T.construct "abab") 1 From jon.fairbairn at cl.cam.ac.uk Mon Aug 27 12:38:38 2007 From: jon.fairbairn at cl.cam.ac.uk (Jon Fairbairn) Date: Mon Aug 27 12:29:43 2007 Subject: [Haskell-cafe] Re: Newbie terminology for partial application References: <46D2DFD2.9000203@telenet.be> Message-ID: Peter Verswyvelen writes: > A while ago I confused "currying" with "partial > application", which was pointed out by members of this > community, and the wiki pages got adapted so that newbies > like me don't make the same mistake twice ;) That's great. > > Anyway, at the risk of making mistakes again, I'm looking > for good terminilogy when talking about "partial > application". > > For example: > > -- uncurried form > *f (x,y)* = -- whatever > > -- curried form > *g x y *= f (x,y) > -- partial application > *h x *= g x It's only a partial application because g takes more than one argument; bear that in mind. > But when writing text documents, I guess it is common to say > "/g is curried/", Actually, I don't think most haskell programmers would say anything at all. Haskellers generally write functions in curried (because partial application is useful), and use the function uncurry :: (a -> b -> c) -> (a, b) -> c when an uncurried version is needed. > but is it also common to say /"g is partially applied"? > /The latter sounds silly to a non-native speaker like > myself... Or shouldn't it be? Sounds OK to me, though again, I'm not sure I would say it often. A partial application is just an application that returns a function, and this is functional programming, so it goes without saying! > /And what is "application"? I guess it means that (g x y) is > internally translated to ((g $ x) $ y) which is translated > into (apply (apply g x) y) where apply is a primitive > function? Application is itself the primitive, and the notation for application is juxtaposition (f x). It might help to have a look at lambda-calculus (if you have a strong stomach for abstraction; if you don't it'd just scare you off). In lambda-calculus there are only four bits of syntax (I'll use Haskell syntax): lambda terms: abstraction: \ a -> T -- where T is a lambda term application: M N -- where M and N are lambda terms variable reference: v -- where v is just a name grouping: (M) -- where M is a lambda term It's possible to think of Haskell as being based on lambda calculus. Application in Haskell is the same as application in lambda calculus, abstraction in Haskell has patterns that lambda calculus does not. The other two are the same. -- J?n Fairbairn Jon.Fairbairn@cl.cam.ac.uk From derek.a.elkins at gmail.com Mon Aug 27 12:39:59 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Mon Aug 27 12:31:01 2007 Subject: [Haskell-cafe] Newbie terminology for partial application In-Reply-To: <46D2DFD2.9000203@telenet.be> References: <46D2DFD2.9000203@telenet.be> Message-ID: <1188232800.5429.7.camel@derek-laptop> On Mon, 2007-08-27 at 16:29 +0200, Peter Verswyvelen wrote: > A while ago I confused "currying" with "partial application", which was > pointed out by members of this community, and the wiki pages got adapted > so that newbies like me don't make the same mistake twice ;) That's great. > > Anyway, at the risk of making mistakes again, I'm looking for good > terminilogy when talking about "partial application". > > For example: > > -- uncurried form > *f (x,y)* = -- whatever > > -- curried form > *g x y *= f (x,y) > > -- partial application > *h x *= g x > > But when writing text documents, I guess it is common to say "/g is > curried/", but is it also common to say /"g is partially applied"? /The > latter sounds silly to a non-native speaker like myself... Or shouldn't > it be? g -is- curried, just period, i.e. that is a property of g itself. g is partially applied to x in h or (g x) is a partial application, i.e. this is a property of a particular application. g is applied to x would also be fine since there is rarely much value in making a distinction between application and partial application at the level of programming (in Haskell at least). You do seem to have a good grasp on the terminology. > /And what is "application"? I guess it means that (g x y) is internally > translated to ((g $ x) $ y) which is translated into (apply (apply g x) > y) where apply is a primitive function? Yes, application is what you do when you "call" a function with arguments. The side step through ($) is unnecessary, ($) is nothing special. From derek.a.elkins at gmail.com Mon Aug 27 12:43:25 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Mon Aug 27 12:34:33 2007 Subject: [Haskell-cafe] "quoting" in Haskell In-Reply-To: <46D2F43B.6070208@telenet.be> References: <46D2E7F1.9080905@telenet.be> <46D2F43B.6070208@telenet.be> Message-ID: <1188233005.5429.11.camel@derek-laptop> On Mon, 2007-08-27 at 17:56 +0200, Peter Verswyvelen wrote: > > Look at Template Haskell. > > "Intuitively Template Haskell provides new language features that > > allow us to convert back and forth between concrete syntax, i.e. what > > Gee coming from C++ that was the last thing I expected "templates" to do. It seems a bit more powerful in Haskell though! > > I'll look into that! They aren't related to "templates" in C++ at all. It follows from the general meaning of the word "template" (as does C++'s usage). Really, it's not all that appropriate a name anyway. You may also find Liskell interesting http://liskell.org/ From bradypus at xs4all.nl Mon Aug 27 13:05:06 2007 From: bradypus at xs4all.nl (Arie Groeneveld) Date: Mon Aug 27 12:53:15 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: References: <46D2233A.1070207@tmorris.net> Message-ID: <46D30442.4020300@xs4all.nl> Steve Schafer wrote: > > x = a - sqrt(a^2 - b^2) > > I don't know offhand if there's a straightforward way to arrive at this > result without using trigonometry. Here you go, though with a slightly different result (same as Joel Koerwer): a^2=(b^2)/4+(a-x)^2 (Pythagoras) solving x: --> x(1,2) = a +/- sqrt (a^2 - b^2/4) (I) Did anyone compare the answers? (I) aai a b = (x1,x2) where x1 = a + sqrt disc x2 = a - sqrt disc disc = a^2-b^2/4 Others: schafer a b = a - sqrt(a^2 - b^2) jeda? a b = a * (1 - cos (b/(2*a))) stefan a b = a - a * sqrt (1 - b*b / a*a) joel a b = a - sqrt (a*a - b*b/4) Assume a and b are given: a=10; b=8 Results: *Main> aai 10 8 (19.165151389911678,0.8348486100883203) the answer is the smaller value the other value = the diameter of the circumference minus x (0.00 secs, 523308 bytes) *Main> schafer 10 8 4.0 (0.01 secs, 524924 bytes) *Main> jeda? 10 8 0.789390059971149 (0.01 secs, 524896 bytes) *Main> stefan 10 8 NaN (0.00 secs, 524896 bytes) *Main> stefan 10 8 4.0 (0.01 secs, 524896 bytes) *Main> joel 10 8 0.8348486100883203 (0.01 secs, 524896 bytes) Where do I go wrong (I)? Thanks @@i From emmanuel.delaborde at citycampus.com Mon Aug 27 13:12:52 2007 From: emmanuel.delaborde at citycampus.com (manu) Date: Mon Aug 27 13:01:21 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell Message-ID: From: Daniel Fischer > Thought it was something like that. > Must check whether that beats Norvig's constraint propagation. it does ! on my machine : Jon Harrop's : 12.5 sec and Norvig's : 15 sec Manu From v.dijk.bas at gmail.com Mon Aug 27 13:15:47 2007 From: v.dijk.bas at gmail.com (Bas van Dijk) Date: Mon Aug 27 13:06:43 2007 Subject: [Haskell-cafe] "quoting" in Haskell In-Reply-To: <1188233005.5429.11.camel@derek-laptop> References: <46D2E7F1.9080905@telenet.be> <46D2F43B.6070208@telenet.be> <1188233005.5429.11.camel@derek-laptop> Message-ID: On 8/27/07, Derek Elkins wrote: > ...Really, it's not all that appropriate a name anyway... Indeed, Meta Haskell would be better I think. Bas From bradypus at xs4all.nl Mon Aug 27 13:20:42 2007 From: bradypus at xs4all.nl (Arie Groeneveld) Date: Mon Aug 27 13:08:50 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: <46D30442.4020300@xs4all.nl> References: <46D2233A.1070207@tmorris.net> <46D30442.4020300@xs4all.nl> Message-ID: <46D307EA.1060309@xs4all.nl> Correction > > > stefan a b = a - a * sqrt (1 - b*b / a*a) > should be: stefan a b = a - a * sqrt (1 - b*b / (a*a)) > > *Main> stefan 10 8 > 4.0 > (0.01 secs, 524896 bytes) > Thanks @@i From dpiponi at gmail.com Mon Aug 27 13:41:30 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Mon Aug 27 13:32:27 2007 Subject: [Haskell-cafe] "quoting" in Haskell In-Reply-To: <46D2F43B.6070208@telenet.be> References: <46D2E7F1.9080905@telenet.be> <46D2F43B.6070208@telenet.be> Message-ID: <625b74080708271041p207088d0v3f68c2b940544e9b@mail.gmail.com> On 8/27/07, Peter Verswyvelen wrote: > > Look at Template Haskell. > Gee coming from C++ that was the last thing I expected "templates" to do. It seems a bit more powerful in Haskell though! There's much in common between C++ template metaprogramming and template Haskell - they both allow compile-time computation. On the question of which is more 'powerful', check out the side by side comparison here: http://www.cs.rice.edu/~taha/publications/journal/dspg04b.pdf -- Dan From haskell at list.mightyreason.com Mon Aug 27 13:57:19 2007 From: haskell at list.mightyreason.com (ChrisK) Date: Mon Aug 27 13:48:26 2007 Subject: [Haskell-cafe] Re: [ANN] An efficient lazy suffix tree library In-Reply-To: References: <46CBAD5A.8020408@serpentine.com> Message-ID: <46D3107F.8030900@list.mightyreason.com> Gleb Alexeyev wrote: > Bryan O'Sullivan wrote: >> I just posted a library named suffixtree to Hackage. >> >> http://www.serpentine.com/software/suffixtree/ >> >> It implements Giegerich and Kurtz's lazy construction algorithm, with >> a few tweaks for better performance and resource usage. >> >> API docs: >> >> http://darcs.serpentine.com/suffixtree/dist/doc/html/Data-SuffixTree.html >> >> I've tested it on multi-megabyte input strings. >> > I think I found a bug: > import qualified Data.SuffixTree as T > >> T.countRepeats "ab" (T.construct "abab") > 1 That is almost certainly because the algorithm expects the source string to have a unique character at its end. The library should either make that clear or add such a character on its own. Otherwise the "ab" suffix is a prefix of the "abab" suffix and the shorter one gets lost. If you end in "$" then "ab$" cannot merge with "abab$" and there are no distinct suffixes a and b for which (isPrefixOf a b) is true. Example: > *Data.SuffixTree> countRepeats "ab" (construct "abab") > 1 > *Data.SuffixTree> countRepeats "ab" (construct "abab$") > 2 -- Chris From steve at fenestra.com Mon Aug 27 14:06:09 2007 From: steve at fenestra.com (Steve Schafer) Date: Mon Aug 27 13:57:08 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: <46D30442.4020300@xs4all.nl> References: <46D2233A.1070207@tmorris.net> <46D30442.4020300@xs4all.nl> Message-ID: <8k46d3lefj10uss6evjvsrq4v090ivgfe1@4ax.com> On Mon, 27 Aug 2007 19:05:06 +0200, you wrote: >Where do I go wrong (I)? b is defined to be _half_ of the chord (the "semichord," I suppose). You're assuming it to be the entire chord. Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ From bos at serpentine.com Mon Aug 27 14:37:11 2007 From: bos at serpentine.com (Bryan O'Sullivan) Date: Mon Aug 27 14:28:46 2007 Subject: [Haskell-cafe] [ANN] pcap 0.3.1, for user-level network packet capture Message-ID: <46D319D7.40704@serpentine.com> I've taken over maintenance of the pcap library (an interface to libpcap, for user-level network packet capture), and released a new version. Home page: http://www.serpentine.com/software/pcap/ API docs: http://darcs.serpentine.com/pcap/dist/doc/html/pcap/ Download: http://hackage.haskell.org/packages/archive/pcap/ darcs repo: darcs get http://darcs.serpentine.com/pcap/ Thanks are due to Gregory Wright for originally writing the package, and Dominic Steinitz and Nick Burlett for their respective maintenance efforts. References: <46CBAD5A.8020408@serpentine.com> <46D3107F.8030900@list.mightyreason.com> Message-ID: <46D31A29.5000207@serpentine.com> ChrisK wrote: > That is almost certainly because the algorithm expects the source string to have > a unique character at its end. Chris is correct. I'll ensure that the docs make this clear. References: <46D2233A.1070207@tmorris.net> <46D30442.4020300@xs4all.nl> <8k46d3lefj10uss6evjvsrq4v090ivgfe1@4ax.com> Message-ID: 2007/8/27, Steve Schafer : > > b is defined to be _half_ of the chord (the "semichord," I suppose). > You're assuming it to be the entire chord. > Based on the drawing I thought it was the length of the arc (in blue) ? -- Jeda? From Rene_de_Visser at hotmail.com Mon Aug 27 15:05:01 2007 From: Rene_de_Visser at hotmail.com (Rene de Visser) Date: Mon Aug 27 14:56:28 2007 Subject: [Haskell-cafe] Re: "quoting" in Haskell References: <46D2E7F1.9080905@telenet.be> Message-ID: "Peter Verswyvelen" schrieb im Newsbeitrag news:46D2E7F1.9080905@telenet.be... > In Scheme, on can "quote" code, so that it becomes data. Microsoft's F# > and C# 3.0 also have something similar that turns code into "expression > trees". The latter is used extensively in LINQ which translates plain C# > code into SQL code or any other code at runtime (this idea came from FP I > heared) The normal way of doing such things in Haskell is to have 1) functions that generate the component data structures (these functions are often called smart constructors) 2) other functions to put the functions/data structures together (these other functions are often call combinators). The resulting data structure that represents the sql query for example is then processed to produce the real (textual) sql query which this then sent to the database. > > I can't find something similar for Haskell? Maybe I am looking at the > wrong places? HaskellDB for example does this for database queries. Parsec does this parsers. HSXML (if I got the name right) does this for XML. > > In Haskell, I know one can use a data constructor as a function (as in > (map Just [1..3])), but a function cannot be turned into a data > constructor (= "quoting"), can it? A data constructor is a special case of a function, or perhaps better said, a particular way a function is defined. Either a function is a data constructor or it isn't. For example you can also do just = Just Just is a data constuctor. It was defined with a data statement (and as a result starts with a capital letter). data Maybe a = Nothing | Just a just is not a data constructor. Why? It wasn't defined with a data statement. However just and Just behave almost identically. (you can't pattern match on just, only on Just) Rene. From daniel.is.fischer at web.de Mon Aug 27 15:52:09 2007 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Aug 27 15:42:21 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <200708262256.26873.daniel.is.fischer@web.de> Message-ID: <200708272152.09175.daniel.is.fischer@web.de> Am Montag, 27. August 2007 10:09 schrieb manu: > Daniel Fischer's modifications to my original program lead to a 400 % > speed boost !!! > (It now runs in 22 seconds on my machine) > He avoided unecessary calls to 'length', uses Array instead of Map, > refactored 'search' function (details below) > Ouch! I should've looked at the code more closely. That had a bug which resulted in LOTS of futile work. Fixed that and the Array version now runs in 3 seconds on my computer (previous version took 60), the corresponding Map version runs in 7. What was the saying, 'The best optimisation is a better algorithm'? Code below. Cheers, Daniel {- This is an attempt to implement in Haskell, Peter Norvig's sudoku solver : "Solving Every Sudoku Puzzle" (http://norvig.com/sudoku.html) In Norvig's program, methods which change a grid return either a new grid, either False (failure). Here I use Maybe, and return Just grid or Nothing in case of failure -} module Main where import Data.List hiding (lookup) import Data.Array import Control.Monad import Data.Maybe -------------------------------------------------- -- Types type Digit = Char type Square = (Char,Char) type Unit = [Square] -- We represent our grid as an array type Grid = Array Square [Digit] -------------------------------------------------- -- Setting Up the Problem rows = "ABCDEFGHI" cols = "123456789" digits = "123456789" box = (('A','1'),('I','9')) cross :: String -> String -> [Square] cross rows cols = [ (r,c) | r <- rows, c <- cols ] squares :: [Square] squares = cross rows cols -- [('A','1'),('A','2'),('A','3'),...] peers :: Array Square [Square] peers = array box [(s, set (units!s)) | s <- squares ] where set = nub . concat unitlist :: [Unit] unitlist = [ cross rows [c] | c <- cols ] ++ [ cross [r] cols | r <- rows ] ++ [ cross rs cs | rs <- ["ABC","DEF","GHI"], cs <- ["123","456","789"]] -- this could still be done more efficiently, but what the heck... units :: Array Square [Unit] units = array box [(s, [filter (/= s) u | u <- unitlist, elem s u ]) | s <- squares] allPossibilities :: Grid allPossibilities = array box [ (s,digits) | s <- squares ] -------------------------------------------------- -- Parsing a grid into a Map parsegrid :: String -> Maybe Grid parsegrid g = do regularGrid g foldM assign allPossibilities (zip squares g) where regularGrid :: String -> Maybe String regularGrid g = if all (\c -> (elem c "0.-123456789")) g then (Just g) else Nothing -------------------------------------------------- -- Propagating Constraints assign :: Grid -> (Square, Digit) -> Maybe Grid assign g (s,d) = if (elem d digits) then do -- check that we are assigning a digit and not a '.' let ds = g!s toDump = delete d ds foldM eliminate g (zip (repeat s) toDump) else return g eliminate :: Grid -> (Square, Digit) -> Maybe Grid eliminate g (s,d) = let cell = g!s in if not (elem d cell) then return g -- already eliminated -- else d is deleted from s' values else do let newCell = delete d cell newV = g // [(s,newCell)] newV2 <- case newCell of -- contradiction : Nothing terminates the computation [] -> Nothing -- if there is only one value (d') left in square, remove it from peers [d'] -> do let peersOfS = peers!s foldM eliminate newV (zip peersOfS (repeat d')) -- else : return the new grid _ -> return newV -- Now check the places where d appears in the units of s foldM (locate d) newV2 (units ! s) locate :: Digit -> Grid -> Unit -> Maybe Grid locate d g u = case filter (elem d . (g !)) u of [] -> Nothing [s] -> assign g (s,d) _ -> return g -------------------------------------------------- -- Search search :: Grid -> Maybe Grid search g = case [(l,(s,xs)) | (s,xs) <- assocs g, let l = length xs, l /= 1] of [] -> return g ls -> do let (_,(s,ds)) = minimum ls msum [assign g (s,d) >>= search | d <- ds] solve :: String -> Maybe Grid solve str = do grd <- parsegrid str search grd -------------------------------------------------- -- Display solved grid printGrid :: Grid -> IO () printGrid = putStrLn . gridToString gridToString :: Grid -> String gridToString g = let l0 = elems g l1 = (map (\s -> " " ++ s ++ " ")) l0 -- ["1 "," 2 ",...] l2 = (map concat . sublist 3) l1 -- ["1 2 3 "," 4 5 6 ",...] l3 = (sublist 3) l2 -- [["1 2 3 "," 4 5 6 "," 7 8 9 "],...] l4 = (map (concat . intersperse "|")) l3 -- ["1 2 3 | 4 5 6 | 7 8 9 ",...] l5 = (concat . intersperse [line] . sublist 3) l4 in unlines l5 where sublist n [] = [] sublist n xs = take n xs : sublist n (drop n xs) line = hyphens ++ "+" ++ hyphens ++ "+" ++ hyphens hyphens = take 9 (repeat '-') -------------------------------------------------- main :: IO () main = do grids <- fmap lines $ readFile "top95.txt" mapM_ printGrid $ mapMaybe solve grids From jeremy.shaw at linspireinc.com Mon Aug 27 16:01:11 2007 From: jeremy.shaw at linspireinc.com (Jeremy Shaw) Date: Mon Aug 27 15:52:17 2007 Subject: [Haskell-cafe] "quoting" in Haskell In-Reply-To: <46D2E7F1.9080905@telenet.be> References: <46D2E7F1.9080905@telenet.be> Message-ID: <1wdod9x4.wl%jeremy.shaw@linspireinc.com> At Mon, 27 Aug 2007 17:04:17 +0200, Peter Verswyvelen wrote: > > In Scheme, on can "quote" code, so that it becomes data. Microsoft's F# > and C# 3.0 also have something similar that turns code into "expression > trees". The latter is used extensively in LINQ which translates plain C# > code into SQL code or any other code at runtime (this idea came from FP > I heared) Depending on what you are trying to do, you might also be able to use some of the DSL techniques that Lennart Augustsson has been exploring in his blog over the past couple months. This is probably a good starting point: http://augustss.blogspot.com/2007_06_01_archive.html j. From bf3 at telenet.be Mon Aug 27 16:08:32 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Mon Aug 27 15:59:25 2007 Subject: [Haskell-cafe] Geometry In-Reply-To: References: <46D2233A.1070207@tmorris.net> <46D30442.4020300@xs4all.nl> <8k46d3lefj10uss6evjvsrq4v090ivgfe1@4ax.com> Message-ID: <46D32F40.5050804@telenet.be> An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070827/d3d3628d/attachment.htm From bf3 at telenet.be Mon Aug 27 16:34:19 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Mon Aug 27 16:25:11 2007 Subject: [Haskell-cafe] No Enum nor Ix instance on Graphics.UI.GLUT.Key Message-ID: <46D3354B.3040701@telenet.be> I want to make an array using GLUT.Key as an index, but it is not an instance of Enum nor Ix Of course, I can make it an instance myself, but I guess it would be easier to do so in the library? Cheers, Peter From apfelmus at quantentunnel.de Tue Aug 28 02:43:03 2007 From: apfelmus at quantentunnel.de (apfelmus) Date: Tue Aug 28 02:34:14 2007 Subject: [Haskell-cafe] Re: "quoting" in Haskell In-Reply-To: <46D2E7F1.9080905@telenet.be> References: <46D2E7F1.9080905@telenet.be> Message-ID: Peter Verswyvelen wrote: > In Scheme, on can "quote" code, so that it becomes data. Microsoft's F# > and C# 3.0 also have something similar that turns code into "expression > trees". > > I can't find something similar for Haskell? Maybe I am looking at the > wrong places? Quoting/Inspecting code at runtime is not possible in Haskell since this would break referential transparency, i.e. one could tell that two extensionally equal values like 3 `add` 4 1 `add` (2 `mul` 3) are different by inspecting their internal structure. Of course, you can use constructors for add and mul and then inspect and transform the result data Expr = Val Int | Add Expr Expr | Mul Expr Expr add, mul :: Expr -> Expr -> Expr add = Add mul = Mul x :: Expr x = Val 1 `add` (Val 2 `mul` Val 3) By making Expr an instance of the class Num , you can use overloaded arithmetic operations instance Num Expr where (+) = Add (*) = Mul fromInteger = Val . fromInteger x :: Expr x = 1 + 2*3 > I want to write something like > > selectiveQuote [add] (1 `add` 2 `mul` 3) > > which would result in an expression tree like > > add > / \ > 1 6 > > So the `mul` is not quoted because it is not part of the "context" = [add] I'm not sure why you'd want to do that, but it's not well-defined. What would selectiveQuote [add] ((1 `add` 2) `mul` 3) be? How to expand `mul` here when `add` isn't expanded? Regards, apfelmus From gleb.alexeev at gmail.com Tue Aug 28 03:57:19 2007 From: gleb.alexeev at gmail.com (Gleb Alexeyev) Date: Tue Aug 28 03:48:31 2007 Subject: [Haskell-cafe] Re: [ANN] An efficient lazy suffix tree library In-Reply-To: <46D31A29.5000207@serpentine.com> References: <46CBAD5A.8020408@serpentine.com> <46D3107F.8030900@list.mightyreason.com> <46D31A29.5000207@serpentine.com> Message-ID: Bryan O'Sullivan wrote: > ChrisK wrote: > >> That is almost certainly because the algorithm expects the source >> string to have >> a unique character at its end. > > Chris is correct. I'll ensure that the docs make this clear. > Apologies, I should have thought of this myself. Thanks. From alexander.vodomerov at gmail.com Tue Aug 28 05:14:43 2007 From: alexander.vodomerov at gmail.com (Alexander Vodomerov) Date: Tue Aug 28 05:05:41 2007 Subject: [Haskell-cafe] GHC 6.6.1 and SELinux issues Message-ID: <20070828091443.GA21275@isil.ipib.msu.ru> Hello! Does anybody here uses GHC on Linux with SELinux turned on? I've just installed SELinux and run into GHC/SELinux incompatibility. It seems that the similar problem was reported some time ago and was fixed in 6.4.3. However, I use 6.6.1 and the problem is still here. $ ghc ghc-6.6.1: internal error: getMBlock: mmap: Permission denied (GHC version 6.6.1 for i386_unknown_linux) Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug Exactly the same bug is appearing on x86_64 architecture. Much more details is available at http://hackage.haskell.org/trac/ghc/ticket/738 Any ideas? With best regards, Alexander. PS. Is it possible to turn on global allow_execmem boolean in SELinux policy, thus enabling executable memory mapping. This solves the problem. However, this is major drawback for system security and should be avoided at any cost. From sjansen at buscaluz.org Tue Aug 28 10:05:02 2007 From: sjansen at buscaluz.org (Stuart Jansen) Date: Tue Aug 28 09:56:06 2007 Subject: [Haskell-cafe] GHC 6.6.1 and SELinux issues In-Reply-To: <20070828091443.GA21275@isil.ipib.msu.ru> References: <20070828091443.GA21275@isil.ipib.msu.ru> Message-ID: <1188309902.3165.7.camel@vision.buscaluz.org> On Tue, 2007-08-28 at 13:14 +0400, Alexander Vodomerov wrote: > Does anybody here uses GHC on Linux with SELinux turned on? I'm using it on Fedora 7 without any problems. $ /usr/sbin/getenforce Enforcing $ getsebool allow_execmem allow_execmem --> off $ cat /etc/redhat-release Fedora release 7 (Moonshine) $ ls -Z $(which ghc) lrwxrwxrwx root root system_u:object_r:bin_t /usr/bin/ghc -> ghc-6.6.1* $ ls -Z $(which ghci) lrwxrwxrwx root root system_u:object_r:bin_t /usr/bin/ghci -> ghci-6.6.1* $ ghc ghc-6.6.1: no input files Usage: For basic information, try the `--help' option. $ ghci ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.6.1, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base ... linking ... done. Prelude> :l Text.hs [1 of 1] Compiling Main ( Text.hs, interpreted ) Ok, modules loaded: Main. *Main> main Loading package mtl-1.0.1 ... linking ... done. Loading package glib-0.9.12 ... linking ... done. Loading package cairo-0.9.12 ... linking ... done. Loading package gtk-0.9.12 ... linking ... done. *Main> Leaving GHCi. $ ghc --make Text.hs [1 of 1] Compiling Main ( Text.hs, Text.o ) Linking Text ... -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070828/73afb4f3/attachment-0001.bin From feeder.of.the.bears at gmail.com Tue Aug 28 12:46:55 2007 From: feeder.of.the.bears at gmail.com (David Pollak) Date: Tue Aug 28 12:37:49 2007 Subject: [Haskell-cafe] [Off Topic Amusement] Lylle Lovett lyrics Message-ID: http://www.lyricsdepot.com/lyle-lovett/west-texas-highway.html -- lift, the fast, powerful, easy web framework http://liftweb.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070828/d7957993/attachment.htm From andrewcoppin at btinternet.com Tue Aug 28 13:26:32 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Tue Aug 28 13:16:20 2007 Subject: [Haskell-cafe] Wildly off-topic Message-ID: <46D45AC8.8050305@btinternet.com> http://importantshock.wordpress.com/2007/08/21/haskell-curry-yes-i-dated-his-daughter/ (Actually, you hardly need to click that. The URL says it all...) From alexander.vodomerov at gmail.com Tue Aug 28 16:59:46 2007 From: alexander.vodomerov at gmail.com (Alexander Vodomerov) Date: Tue Aug 28 16:52:36 2007 Subject: [Haskell-cafe] GHC 6.6.1 and SELinux issues In-Reply-To: <1188309902.3165.7.camel@vision.buscaluz.org> References: <20070828091443.GA21275@isil.ipib.msu.ru> <1188309902.3165.7.camel@vision.buscaluz.org> Message-ID: <20070828205944.GA6400@localhost.localdomain> On Tue, Aug 28, 2007 at 08:05:02AM -0600, Stuart Jansen wrote: > I'm using it on Fedora 7 without any problems. > > $ ls -Z $(which ghc) > lrwxrwxrwx root root system_u:object_r:bin_t /usr/bin/ghc -> > ghc-6.6.1* > $ ls -Z $(which ghci) > lrwxrwxrwx root root system_u:object_r:bin_t /usr/bin/ghci -> > ghci-6.6.1* In what domain do you run GHC? The commands about just show that /usr/bin/ghc has the bin_t type, however it is just a symlink or shell wrapper. Real GHC executable may have another permission. See for example (taken from my Debian box): $ ls -Z `which ghc` lrwxrwxrwx root root system_u:object_r:bin_t:s0 /usr/bin/ghc -> /etc/alternatives/ghc $ ls -Z /usr/lib/ghc-6.6.1/bin/ghc-6.6.1 -rwxr-xr-x root root system_u:object_r:bin_t:s0 /usr/lib/ghc-6.6.1/bin/ghc-6.6.1 $ file /usr/lib/ghc-6.6.1/bin/ghc-6.6.1 /usr/lib/ghc-6.6.1/bin/ghc-6.6.1: POSIX shell script text executable $ cat /usr/lib/ghc-6.6.1/bin/ghc-6.6.1 #!/bin/sh GHCBIN="/usr/lib/ghc-6.6.1/ghc-6.6.1"; TOPDIROPT="-B/usr/lib/ghc-6.6.1"; # Mini-driver for GHC exec $GHCBIN $TOPDIROPT ${1+"$@"} $ file /usr/lib/ghc-6.6.1/ghc-6.6.1 /usr/lib/ghc-6.6.1/ghc-6.6.1: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.1, dynamically linked (uses shared libs), stripped $ ls -Z /usr/lib/ghc-6.6.1/ghc-6.6.1 -rwxr-xr-x root root system_u:object_r:lib_t:s0 /usr/lib/ghc-6.6.1/ghc-6.6.1 In this case the real domain for ghc is lib_t, not bin_t. With best regards, Alexander. From jgbailey at gmail.com Tue Aug 28 17:08:39 2007 From: jgbailey at gmail.com (Justin Bailey) Date: Tue Aug 28 16:59:30 2007 Subject: [Haskell-cafe] Searching for a subsequence in Data.Sequence structure? Message-ID: Does anyone have code for finding a subsequence within a Data.Sequence.Seq value, or is there a way to do it with the already defined instances that I am missing? A quick search didn't turn up much. Thanks in advance! Justin From mail at joachim-breitner.de Tue Aug 28 17:33:28 2007 From: mail at joachim-breitner.de (Joachim Breitner) Date: Tue Aug 28 17:24:23 2007 Subject: [Haskell-cafe] Ideas In-Reply-To: <46D01785.7070503@btinternet.com> References: <46D01785.7070503@btinternet.com> Message-ID: <1188336808.4470.29.camel@otto.ehbuehl.net> Hi, Am Samstag, den 25.08.2007, 12:50 +0100 schrieb Andrew Coppin: > How easy would it be to make / would anybody care / has somebody already > made ... in Haskell? > > - A wiki program. (Ditto.) I wrote a wiki in haskell, but it focuses on full-sized LaTeX-Documents, so the ?regular? wiki party is rather limited. But of course it can be extended... (It?s based on subversion, and the small CGI-part is written in python). Wiki (self-hosting): http://latexki.nomeata.de/ Application: http://mitschriebwiki.nomeata.de/ Greetings, Joachim -- Joachim "nomeata" Breitner mail: mail@joachim-breitner.de | ICQ# 74513189 | GPG-Key: 4743206C JID: joachimbreitner@amessage.de | http://www.joachim-breitner.de/ Debian Developer: nomeata@debian.org From thomas.hartman at db.com Tue Aug 28 18:03:32 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Tue Aug 28 17:54:28 2007 Subject: [Haskell-cafe] runInteractiveCommand behaves differently on linux and windows Message-ID: Maybe this is by design, but I just thought I would point this behavior out and ask for comment. test1 merely shows that runInteractiveCommand reacts differently to perl warnings than perl errors. Okay, maybe the inconsistency in that case is due to perl and not haskell. test2 behaves the same on win and nix. This is "pipe like" in that the ouptut of a command (which could be the result of a shell call, but just as easily be the return of a haskell function) gets fed into a shell command. In this case, if the shell command is simply "tail" the behavior is consistent from win to nix. test3 shows that the behavior stops being consistent if ssh enters the picture. (piping to tail via ssh). again, maybe this is due to ssh and not haskell. however... note however that on windows ghc -e 'mapM_ ( putStrLn . show ) [1..1000] ' | ssh `whoami`@localhost 'tail -n2' works fine. so it's not *just* ssh, but ssh in conjuction with runInteractiveCommand which seems to cause problems FWIW, using 10 lines instead of 1000 still hangs on windows. Is there a way to code up shell pipelike behavior in a more portable way? curious what the cafe thinks... thomas. import Test.HUnit import Misc ( (>>=^) ) import System.Process import System.IO import System.Exit -- works on linux, error on windows test1 = do res1 <- test_shellrunStderrOk runTestTT $ TestCase ( assertEqual "test1" "made it" res1 ) where test_shellrunStderrOk = do runprocessStdErrAllowed' "" cmdPerlwarn return "made it" cmdPerldie = " perl -e 'die \"error\"' " cmdPerlwarn = " perl -e 'warn \"blee\"' " -- works on linux, windows test2 = pipeTo "tail -n2" -- works on linux, hangs on windows test3 = pipeTo "ssh `whoami`@localhost 'tail -n2'" pipeTo cmd = do res2 <- test_shellrunPipeinLike runTestTT $ TestCase ( assertEqual ( "pipe to, cmd: " ++ cmd) (show l) res2 ) where test_shellrunPipeinLike = do runprocessStdErrAllowed' (unlines $ map show [1..l]) ( cmd ) >>=^ filter (not . ( == '\n') ) l = 1000 runprocessStdErrAllowed' inp s = do (ih,oh,eh,pid) <- runInteractiveCommand s so <- hGetContents oh se <- hGetContents eh hPutStrLn ih inp hClose ih ex <- waitForProcess pid case ex of ExitFailure e -> fail $ "shell command " ++ s ++ "\nFailed with status: " ++ show e _ | otherwise -> return so --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070828/a737582a/attachment.htm From thomas.hartman at db.com Tue Aug 28 18:19:41 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Tue Aug 28 18:10:39 2007 Subject: [Haskell-cafe] cabal install of HDBC-odbc fails on ghc 6.7, -I flag causes problems In-Reply-To: <1187816007.1034.2.camel@localhost> Message-ID: Well, I built with -v3 as suggested, but the ouptut doesn't seem that helpful to me. ghc compile commands, at any rate, do not appear to be outputted $ echo ":main build" | /usr/local/bin/ghci-6.7.20070816 -v3 Setup.hs 1>build.out 2>build.err build.out: GHCi, version 6.7.20070816: http://www.haskell.org/ghc/ :? for help Loading package base ... linking ... done. Ok, modules loaded: Main. *Main> Loading package array-0.1 ... linking ... done. Loading package containers-0.1 ... linking ... done. Loading package old-locale-1.0 ... linking ... done. Loading package old-time-1.0 ... linking ... done. Loading package filepath-1.0 ... linking ... done. Loading package directory-1.0 ... linking ... done. Loading package unix-2.0 ... linking ... done. Loading package process-1.0 ... linking ... done. Loading package pretty-1.0 ... linking ... done. Loading package Cabal-1.1.7 ... linking ... done. Reading parameters from /home/hartthoma/installs/HDBC-odbc-1.0.1.0/HDBC-odbc.buildinfo Preprocessing library HDBC-odbc-1.0.1.0... *** Exception: exit: ExitFailure 1 *Main> Leaving GHCi. build.err: Glasgow Haskell Compiler, Version 6.7.20070816, for Haskell 98, stage 2 booted by GHC version 6.6.1 Using package config file: /usr/local/lib/ghc-6.7.20070816/package.conf hiding package regex-base-0.72 to avoid conflict with later version regex-base-0.91 hiding package HDBC-1.0.1 to avoid conflict with later version HDBC-1.1.2 wired-in package base mapped to base-2.1 wired-in package rts mapped to rts-1.0 wired-in package haskell98 mapped to haskell98-1.0 wired-in package template-haskell mapped to template-haskell-0.1 wired-in package ndp not found. Hsc static flags: -static *** Parser: *** Desugar: *** Simplify: *** CorePrep: *** ByteCodeGen: *** Parser: *** Desugar: *** Simplify: *** CorePrep: *** ByteCodeGen: *** Parser: *** Desugar: *** Simplify: *** CorePrep: *** ByteCodeGen: *** Chasing dependencies: Chasing modules from: Stable obj: [] Stable BCO: [] unload: retaining objs [] unload: retaining bcos [] Ready for upsweep [] Upsweep completely successful. *** Deleting temp files: Deleting: *** Chasing dependencies: Chasing modules from: Setup.hs Stable obj: [] Stable BCO: [] unload: retaining objs [] unload: retaining bcos [] Ready for upsweep [NONREC ModSummary { ms_hs_date = Mon Aug 20 09:49:47 EDT 2007 ms_mod = main:Main, ms_imps = [System.Exit, Distribution.PackageDescription, Distribution.Simple.Utils, Data.List, System.Info, Distribution.Simple] ms_srcimps = [] }] compile: input file Setup.hs *** Checking old interface for main:Main: [1 of 1] Compiling Main ( Setup.hs, interpreted ) *** Parser: *** Renamer/typechecker: *** Desugar: Result size = 435 *** Simplify: Result size = 464 Result size = 437 *** Tidy Core: Result size = 437 *** CorePrep: Result size = 491 *** ByteCodeGen: *** Deleting temp files: Deleting: Upsweep completely successful. *** Deleting temp files: Deleting: *** Parser: *** Desugar: *** Simplify: *** CorePrep: *** ByteCodeGen: ghc-6.6.1: unrecognised flags: -I Usage: For basic information, try the `--help' option. compiling dist/build/Database/HDBC/ODBC/Connection_hsc_make.c failed command was: ghc -c -I dist/build/Database/HDBC/ODBC/Connection_hsc_make.c -o dist/build/Database/HDBC/ODBC/Connection_hsc_make.o *** Deleting temp files: Deleting: *** Deleting temp dirs: Deleting: Duncan Coutts 08/22/2007 04:53 PM To Thomas Hartman/ext/dbcom@DBAmericas cc haskell-cafe@haskell.org Subject Re: [Haskell-cafe] cabal install of HDBC-odbc fails on ghc 6.7, -I flag causes problems On Mon, 2007-08-20 at 13:10 -0400, Thomas Hartman wrote: > > problemw with the -I flag to ghc are causing cabal install to fail for > hdbc-odbc (darcs head). > Any tips on debugging this cabal install would be appreciated. > $ runghc Setup.hs configure; runghc Setup.hs build Try with -v3 is: runghc Setup.hs build -v3 this will give extremely verbose output. We'd like to see the last bit to see what ghc command line exactly is failing. It'll show the command line arguments in Haskell show format eg ["-I", "/"] Duncan --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070828/47ada858/attachment-0001.htm From duncan.coutts at worc.ox.ac.uk Tue Aug 28 20:08:46 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Tue Aug 28 19:57:40 2007 Subject: [Haskell-cafe] cabal install of HDBC-odbc fails on ghc 6.7, -I flag causes problems In-Reply-To: References: Message-ID: <1188346126.10322.1.camel@localhost> On Tue, 2007-08-28 at 18:19 -0400, Thomas Hartman wrote: > > Well, I built with -v3 as suggested, but the ouptut doesn't seem that > helpful to me. ghc compile commands, at any rate, do not appear to be > outputted Sorry, I meant to pass -v3 to cabal, not to ghc compiling/running Setup.hs > $ echo ":main build" | /usr/local/bin/ghci-6.7.20070816 -v3 Setup.hs > 1>build.out 2>build.err like: runghc Setup.hs build -v3 Duncan From dons at cse.unsw.edu.au Tue Aug 28 21:49:43 2007 From: dons at cse.unsw.edu.au (Donald Bruce Stewart) Date: Tue Aug 28 21:40:36 2007 Subject: [Haskell-cafe] Norvig's Sudoku Solver in Haskell In-Reply-To: References: <30E7ACB7-5961-42AD-B5D6-880D7F08453C@citycampus.com> <200708271254.20656.daniel.is.fischer@web.de> <200708271340.18285.jon@ffconsultancy.com> <200708271627.55061.daniel.is.fischer@web.de> Message-ID: <20070829014943.GC24034@cse.unsw.EDU.AU> chaddai.fouche: > For the translation of the above OCaml code, there is not much to do, > in fact it is mostly functional, and so easily translated in Haskell > code, note that I add a code to handle input of the form > "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......", > to resolve it and print a solution : Spencer Janssen also wrote a rather elegant translation, which you can find on hpaste.org import Data.List import Data.Ord n = 3 :: Int invalid (i, j) (i', j') = i == i' || j == j' || i `div` n == i' `div` n && j `div` n == j' `div` n select p n p' ns | invalid p p' = filter (/= n) ns | otherwise = ns add p n sols = sortBy (comparing (length . snd)) $ map f sols where f (p', ns) = (p', select p n p' ns) search [] = [[]] search ((p, ns):sols) = [(p, n):ss | n <- ns, ss <- search $ add p n sols] You can see the development here, http://hpaste.org/2348 -- Don From ronguida at mindspring.com Tue Aug 28 22:19:37 2007 From: ronguida at mindspring.com (Ronald Guida) Date: Tue Aug 28 22:12:28 2007 Subject: [Haskell-cafe] Serial Communications in Haskell Message-ID: <46D4D7B8.1030808@mindspring.com> I'm on a Windows box and I'm looking for a way to talk to a serial port (for example, RS-232) from Haskell. I couldn't find a library to do this, so I am wondering how to create one. I have a fairly thorough understanding of how to open and use a serial port with the Windows API. In particular, to open a serial port, I have to use CreateFile, which is the same API call that opens files. In fact, if I call openFile from GHC, and pass "COM1:" as the filename, then I can get a writable serial port. > module Serial > where > import System.IO > > main = do > h <- openFile "COM1:" ReadWriteMode > hPutStrLn h "Hello World" I can't read from the port (I always get an immediate EOF), and I have no way of configuring things like the baud rate or the parity settings. Nevertheless, this demonstrates that openFile can at least open the serial port. What I would like to do is create some functions that would allow me to open and configure a serial port, and get a Handle back so that I can use the existing IO functions like hGetChar and hPutChar. I am assuming that hGetChar eventually calls win32::ReadFile and hPutChar eventually calls win32::WriteFile. These same two API calls would work for serial ports. In Windows, there are 23 API functions that apply specifically to serial ports. Out of these 23 functions, only a few of them are actually necessary if I just want to send and receive data. Of course, I don't know how to call Windows API functions from Haskell, and I have no idea how to hook things to the IO library so that I can use a Handle for a serial port. I'm looking for some advice on how to proceed. -- Ron From alexander.vodomerov at gmail.com Wed Aug 29 03:01:14 2007 From: alexander.vodomerov at gmail.com (Alexander Vodomerov) Date: Wed Aug 29 02:54:06 2007 Subject: [Haskell-cafe] GHC 6.6.1 and SELinux issues In-Reply-To: <1188355985.3156.11.camel@vision.buscaluz.org> References: <20070828091443.GA21275@isil.ipib.msu.ru> <1188309902.3165.7.camel@vision.buscaluz.org> <20070828205944.GA6400@localhost.localdomain> <1188355985.3156.11.camel@vision.buscaluz.org> Message-ID: <20070829070114.GA5706@localhost.localdomain> On Tue, Aug 28, 2007 at 08:53:05PM -0600, Stuart Jansen wrote: > On Wed, 2007-08-29 at 00:59 +0400, Alexander Vodomerov wrote: > > In what domain do you run GHC? > > Sorry about that, should've dug deeper. And here we have the difference: > > $ ls -Z /usr/lib/ghc-6.6.1/ghc-6.6.1 > -rwxr-xr-x root root > system_u:object_r:unconfined_execmem_exec_t /usr/lib/ghc-6.6.1/ghc-6.6.1 This explains that GHC works fine. unconfined_execmem_exec_t gives permission to map memory with PROT_EXEC and PROT_WRITE simultaneously. I've put GHC in unconfined_execmem_t and it started to work fine. But the problem is not in GHC -- it is in programs compiled by GHC. They also require exec/write memory. Only root can grant unconfined_execmem privileges, so simple user can not run binaries compiled by GHC. How do you solve this problem? Does Fedora GHC package has any additional patches? With best regards, Alexander. From mmitar at gmail.com Wed Aug 29 03:38:39 2007 From: mmitar at gmail.com (Mitar) Date: Wed Aug 29 03:29:30 2007 Subject: [Haskell-cafe] Serial Communications in Haskell In-Reply-To: <46D4D7B8.1030808@mindspring.com> References: <46D4D7B8.1030808@mindspring.com> Message-ID: Hi! > Of course, I don't know how to call Windows API functions from Haskell, > and I have no idea how to hook things to the IO library so that I can > use a Handle for a serial port. I'm looking for some advice on how to > proceed. You can check how I did this in my Lego Mindstorms NXT interface, pre-beta version: http://www.forzanka.si/files/NXT.tgz It is for UNIX (POSIX?) systems but I had similar problems so I had to use FFI (foreign function interface) to setup a link. You will probably just have to replace that with Windows API calls. I hope. Mitar From eivuokko at gmail.com Wed Aug 29 04:26:07 2007 From: eivuokko at gmail.com (Esa Ilari Vuokko) Date: Wed Aug 29 04:17:02 2007 Subject: [Haskell-cafe] Serial Communications in Haskell In-Reply-To: <46D4D7B8.1030808@mindspring.com> References: <46D4D7B8.1030808@mindspring.com> Message-ID: On 8/29/07, Ronald Guida wrote: > I'm on a Windows box and I'm looking for a way to talk to a serial > port (for example, RS-232) from Haskell. I couldn't find a library to > do this, so I am wondering how to create one. > > I have a fairly thorough understanding of how to open and use a serial > port with the Windows API. In particular, to open a serial port, I At the moment, I think it is easier to just use the same Windows API directly, rather than try to bend GHC's IO system to do it "right". > have to use CreateFile, which is the same API call that opens files. > In fact, if I call openFile from GHC, and pass "COM1:" as the > filename, then I can get a writable serial port. > > > module Serial > > where > > import System.IO > > > > main = do > > h <- openFile "COM1:" ReadWriteMode > > hPutStrLn h "Hello World" > > I can't read from the port (I always get an immediate EOF), and I have > no way of configuring things like the baud rate or the parity > settings. Nevertheless, this demonstrates that openFile can at least > open the serial port. > > What I would like to do is create some functions that would allow me > to open and configure a serial port, and get a Handle back so that I > can use the existing IO functions like hGetChar and hPutChar. I am > assuming that hGetChar eventually calls win32::ReadFile and hPutChar > eventually calls win32::WriteFile. These same two API calls would > work for serial ports. Unfortunately, it goes via extra hoops and uses c runtime instead of Windows API directly. This extra layer makes sure it's hard to predict exactly what gets done (and with what options) sometimes. And even if it did, it'd probably use overlapping io, does that work with COM ports? > In Windows, there are 23 API functions that apply specifically to > serial ports. Out of these 23 functions, only a few of them are > actually necessary if I just want to send and receive data. > > Of course, I don't know how to call Windows API functions from Haskell, > and I have no idea how to hook things to the IO library so that I can > use a Handle for a serial port. I'm looking for some advice on how to > proceed. I haven't done much work on COM ports, but the little I did, I used bindings in Win32 and probably some of my own, and didn't use System.IO/Handle at all. Maybe problems with GHC's IO system are easy to solve, but I have no idea and wasn't inclined to find out. Best regards, Esa From v.dijk.bas at gmail.com Wed Aug 29 08:28:41 2007 From: v.dijk.bas at gmail.com (Bas van Dijk) Date: Wed Aug 29 08:19:31 2007 Subject: [Haskell-cafe] Serial Communications in Haskell In-Reply-To: References: <46D4D7B8.1030808@mindspring.com> Message-ID: On 8/29/07, Esa Ilari Vuokko wrote: > On 8/29/07, Ronald Guida wrote: > > I'm on a Windows box and I'm looking for a way to talk to a serial > > port (for example, RS-232) from Haskell. I couldn't find a library to > > do this, so I am wondering how to create one. > > > > I have a fairly thorough understanding of how to open and use a serial > > port with the Windows API. In particular, to open a serial port, I > > At the moment, I think it is easier to just use the same Windows API directly, > rather than try to bend GHC's IO system to do it "right". > > > have to use CreateFile, which is the same API call that opens files. > > In fact, if I call openFile from GHC, and pass "COM1:" as the > > filename, then I can get a writable serial port. > > > > > module Serial > > > where > > > import System.IO > > > > > > main = do > > > h <- openFile "COM1:" ReadWriteMode > > > hPutStrLn h "Hello World" > > > > I can't read from the port (I always get an immediate EOF), and I have > > no way of configuring things like the baud rate or the parity > > settings. Nevertheless, this demonstrates that openFile can at least > > open the serial port. > > > > What I would like to do is create some functions that would allow me > > to open and configure a serial port, and get a Handle back so that I > > can use the existing IO functions like hGetChar and hPutChar. I am > > assuming that hGetChar eventually calls win32::ReadFile and hPutChar > > eventually calls win32::WriteFile. These same two API calls would > > work for serial ports. > > Unfortunately, it goes via extra hoops and uses c runtime instead of > Windows API directly. This extra layer makes sure it's hard to predict > exactly what gets done (and with what options) sometimes. > > And even if it did, it'd probably use overlapping io, does that work with > COM ports? > > > In Windows, there are 23 API functions that apply specifically to > > serial ports. Out of these 23 functions, only a few of them are > > actually necessary if I just want to send and receive data. > > > > Of course, I don't know how to call Windows API functions from Haskell, > > and I have no idea how to hook things to the IO library so that I can > > use a Handle for a serial port. I'm looking for some advice on how to > > proceed. > > I haven't done much work on COM ports, but the little I did, I used bindings > in Win32 and probably some of my own, and didn't use System.IO/Handle > at all. Maybe problems with GHC's IO system are easy to solve, but I have > no idea and wasn't inclined to find out. > > Best regards, > Esa > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > Ideally, we would have something like pyserial ( http://pyserial.sourceforge.net ) for Haskell. It provides a nice portable abstraction over serial communication. See for example the windows binding: http://pyserial.cvs.sourceforge.net/pyserial/pyserial/serial/serialwin32.py?view=markup regards, Bas van Dijk From thomas.hartman at db.com Wed Aug 29 10:05:03 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Wed Aug 29 09:55:56 2007 Subject: [Haskell-cafe] cabal install of HDBC-odbc fails on ghc 6.7, -I flag causes problems In-Reply-To: <1188346126.10322.1.camel@localhost> Message-ID: Ah ok, so I did echo ":main build -v3" | /usr/local/bin/ghci-6.7.20070816 Setup.hs 1>build.out 2>build.err and this does indeed seem more informative. advice? build.err: [1 of 1] Compiling Main ( Setup.hs, interpreted ) ghc-6.6.1: unrecognised flags: -I Usage: For basic information, try the `--help' option. compiling dist/build/Database/HDBC/ODBC/Connection_hsc_make.c failed command was: ghc -c -I dist/build/Database/HDBC/ODBC/Connection_hsc_make.c -o dist/build/Database/HDBC/ODBC/Connection_hsc_make.o build.out: GHCi, version 6.7.20070816: http://www.haskell.org/ghc/ :? for help Loading package base ... linking ... done. Ok, modules loaded: Main. *Main> Loading package array-0.1 ... linking ... done. Loading package containers-0.1 ... linking ... done. Loading package old-locale-1.0 ... linking ... done. Loading package old-time-1.0 ... linking ... done. Loading package filepath-1.0 ... linking ... done. Loading package directory-1.0 ... linking ... done. Loading package unix-2.0 ... linking ... done. Loading package process-1.0 ... linking ... done. Loading package pretty-1.0 ... linking ... done. Loading package Cabal-1.1.7 ... linking ... done. Reading parameters from /home/hartthoma/installs/HDBC-odbc-1.0.1.0/HDBC-odbc.buildinfo Creating dist/build (and its parents) Creating dist/build/autogen (and its parents) Preprocessing library HDBC-odbc-1.0.1.0... Creating dist/build/Database/HDBC/ODBC (and its parents) ("/usr/local/bin/hsc2hs",["-D__GLASGOW_HASKELL__=606","--cflag=-I","--lflag=-lodbc","-o","dist/build/Database/HDBC/ODBC/Connection.hs","Database/HDBC/ODBC/Connection.hsc"]) *** Exception: exit: ExitFailure 1 *Main> Leaving GHCi. Duncan Coutts 08/28/2007 08:08 PM To Thomas Hartman/ext/dbcom@DBAmericas cc haskell-cafe@haskell.org Subject Re: [Haskell-cafe] cabal install of HDBC-odbc fails on ghc 6.7, -I flag causes problems On Tue, 2007-08-28 at 18:19 -0400, Thomas Hartman wrote: > > Well, I built with -v3 as suggested, but the ouptut doesn't seem that > helpful to me. ghc compile commands, at any rate, do not appear to be > outputted Sorry, I meant to pass -v3 to cabal, not to ghc compiling/running Setup.hs > $ echo ":main build" | /usr/local/bin/ghci-6.7.20070816 -v3 Setup.hs > 1>build.out 2>build.err like: runghc Setup.hs build -v3 Duncan --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/fef1ed71/attachment-0001.htm From thomas.hartman at db.com Wed Aug 29 10:08:30 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Wed Aug 29 09:59:24 2007 Subject: [Haskell-cafe] runInteractiveCommand behaves differently on linux and windows In-Reply-To: Message-ID: I probably should have also mentioned that the "fail" on windows is for me ssh-ed to that box remotely, where the sshd program is cygwin. Thomas Hartman Sent by: haskell-cafe-bounces@haskell.org 08/28/2007 06:03 PM To haskell-cafe@haskell.org cc Subject [Haskell-cafe] runInteractiveCommand behaves differently on linux and windows Maybe this is by design, but I just thought I would point this behavior out and ask for comment. test1 merely shows that runInteractiveCommand reacts differently to perl warnings than perl errors. Okay, maybe the inconsistency in that case is due to perl and not haskell. test2 behaves the same on win and nix. This is "pipe like" in that the ouptut of a command (which could be the result of a shell call, but just as easily be the return of a haskell function) gets fed into a shell command. In this case, if the shell command is simply "tail" the behavior is consistent from win to nix. test3 shows that the behavior stops being consistent if ssh enters the picture. (piping to tail via ssh). again, maybe this is due to ssh and not haskell. however... note however that on windows ghc -e 'mapM_ ( putStrLn . show ) [1..1000] ' | ssh `whoami`@localhost 'tail -n2' works fine. so it's not *just* ssh, but ssh in conjuction with runInteractiveCommand which seems to cause problems FWIW, using 10 lines instead of 1000 still hangs on windows. Is there a way to code up shell pipelike behavior in a more portable way? curious what the cafe thinks... thomas. import Test.HUnit import Misc ( (>>=^) ) import System.Process import System.IO import System.Exit -- works on linux, error on windows test1 = do res1 <- test_shellrunStderrOk runTestTT $ TestCase ( assertEqual "test1" "made it" res1 ) where test_shellrunStderrOk = do runprocessStdErrAllowed' "" cmdPerlwarn return "made it" cmdPerldie = " perl -e 'die \"error\"' " cmdPerlwarn = " perl -e 'warn \"blee\"' " -- works on linux, windows test2 = pipeTo "tail -n2" -- works on linux, hangs on windows test3 = pipeTo "ssh `whoami`@localhost 'tail -n2'" pipeTo cmd = do res2 <- test_shellrunPipeinLike runTestTT $ TestCase ( assertEqual ( "pipe to, cmd: " ++ cmd) (show l) res2 ) where test_shellrunPipeinLike = do runprocessStdErrAllowed' (unlines $ map show [1..l]) ( cmd ) >>=^ filter (not . ( == '\n') ) l = 1000 runprocessStdErrAllowed' inp s = do (ih,oh,eh,pid) <- runInteractiveCommand s so <- hGetContents oh se <- hGetContents eh hPutStrLn ih inp hClose ih ex <- waitForProcess pid case ex of ExitFailure e -> fail $ "shell command " ++ s ++ "\nFailed with status: " ++ show e _ | otherwise -> return so --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/8f63028a/attachment.htm From bos at serpentine.com Wed Aug 29 11:41:12 2007 From: bos at serpentine.com (Bryan O'Sullivan) Date: Wed Aug 29 11:33:03 2007 Subject: [Haskell-cafe] GHC 6.6.1 and SELinux issues In-Reply-To: <20070829070114.GA5706@localhost.localdomain> References: <20070828091443.GA21275@isil.ipib.msu.ru> <1188309902.3165.7.camel@vision.buscaluz.org> <20070828205944.GA6400@localhost.localdomain> <1188355985.3156.11.camel@vision.buscaluz.org> <20070829070114.GA5706@localhost.localdomain> Message-ID: <46D59398.8030208@serpentine.com> Alexander Vodomerov wrote: > I've put GHC in unconfined_execmem_t and it started to work fine. But > the problem is not in GHC -- it is in programs compiled by GHC. They > also require exec/write memory. Only root can grant unconfined_execmem > privileges, so simple user can not run binaries compiled by GHC. How do > you solve this problem? Running "chcon -t unconfined_execmem_exec_t" as root will let you run the binaries, which you probably already knew. The underlying problem is harder to fix: the default SELinux policy doesn't allow PROT_EXEC pages to be mapped with PROT_WRITE, for obvious reasons. The solution is expensive in terms of address space and TLB entries: map the same pages twice, once only with PROT_EXEC, and once only with PROT_WRITE. There's already a Trac ticket filed against this problem, but Simon Marlow marked it as closed because he couldn't test the code he wrote to try to fix it, and nobody stepped in to help out at the time: http://hackage.haskell.org/trac/ghc/ticket/738 0.92) on ghc 6.7 Message-ID: Skipped content of type multipart/alternative-------------- next part -------------- { addfile ./include/regex/HsRegexPosixConfig.h hunk ./include/regex/HsRegexPosixConfig.h 1 +/* include/HsRegexPosixConfig.h. Generated by configure. */ +/* include/HsRegexPosixConfig.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have a POSIX regex library installed */ +#define HAVE_POSIX_REGEX 1 + +/* Define to 1 if you have the `regcomp' function. */ +#define HAVE_REGCOMP 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_REGEX_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "TextRegexLazy@personal.mightyreason.com" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "Haskell regex-posix package" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "Haskell regex-posix package 0.71" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "regex-posix" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "0.71" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 hunk ./regex-posix.cabal 16 -Build-Depends: regex-base >= 0.80, base >= 2.0 +Build-Depends: regex-base >= 0.80, base >= 2.0, array, containers, bytestring hunk ./regex-posix.cabal 43 -Include-Dirs: include +Include-Dirs: include/regex } -------------- next part -------------- A non-text attachment was scrubbed... Name: regex-posix-0.92-build Type: application/octet-stream Size: 6952 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/b4429a62/regex-posix-0-0002.obj -------------- next part -------------- A non-text attachment was scrubbed... Name: regex-posix-0.92-install Type: application/octet-stream Size: 634 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/b4429a62/regex-posix-0-0003.obj From alexander.vodomerov at gmail.com Wed Aug 29 14:40:41 2007 From: alexander.vodomerov at gmail.com (Alexander Vodomerov) Date: Wed Aug 29 14:33:33 2007 Subject: [Haskell-cafe] GHC 6.6.1 and SELinux issues In-Reply-To: <46D59398.8030208@serpentine.com> References: <20070828091443.GA21275@isil.ipib.msu.ru> <1188309902.3165.7.camel@vision.buscaluz.org> <20070828205944.GA6400@localhost.localdomain> <1188355985.3156.11.camel@vision.buscaluz.org> <20070829070114.GA5706@localhost.localdomain> <46D59398.8030208@serpentine.com> Message-ID: <20070829184041.GA9231@localhost.localdomain> On Wed, Aug 29, 2007 at 08:41:12AM -0700, Bryan O'Sullivan wrote: > The underlying problem is harder to fix: the default SELinux policy doesn't > allow PROT_EXEC pages to be mapped with PROT_WRITE, for obvious reasons. > The solution is expensive in terms of address space and TLB entries: map > the same pages twice, once only with PROT_EXEC, and once only with > PROT_WRITE. Just for experiment I've removed PROT_EXEC from my_mmap function in rts/MBlock.c and recompiled GHC. The resulting GHC was able to compile itself and my code. Binaries, produced by it worked fine with SELinux. However, another problem related to GHCi ocurred. More details are available at the 738 ticket you mentioned. So it is not clear if GHC does really need this PROT_EXEC. Can someone familiar with GHC internals answer why PROT_EXEC is used in getMBlocks? > There's already a Trac ticket filed against this problem, but Simon Marlow > marked it as closed because he couldn't test the code he wrote to try to > fix it, and nobody stepped in to help out at the time: > http://hackage.haskell.org/trac/ghc/ticket/738 Yes, I reopened the bug some days ago. I can also provide a shell access to Simon Marlow (or someone else willing to help) on a machine to experiment with. Both x86 and x86_64 boxes are available. With best regards, Alexander. From stefanor at cox.net Wed Aug 29 16:03:56 2007 From: stefanor at cox.net (Stefan O'Rear) Date: Wed Aug 29 15:54:47 2007 Subject: [Haskell-cafe] GHC 6.6.1 and SELinux issues In-Reply-To: <20070829184041.GA9231@localhost.localdomain> References: <20070828091443.GA21275@isil.ipib.msu.ru> <1188309902.3165.7.camel@vision.buscaluz.org> <20070828205944.GA6400@localhost.localdomain> <1188355985.3156.11.camel@vision.buscaluz.org> <20070829070114.GA5706@localhost.localdomain> <46D59398.8030208@serpentine.com> <20070829184041.GA9231@localhost.localdomain> Message-ID: <20070829200356.GA3688@localhost.localdomain> On Wed, Aug 29, 2007 at 10:40:41PM +0400, Alexander Vodomerov wrote: > On Wed, Aug 29, 2007 at 08:41:12AM -0700, Bryan O'Sullivan wrote: > > > The underlying problem is harder to fix: the default SELinux policy doesn't > > allow PROT_EXEC pages to be mapped with PROT_WRITE, for obvious reasons. > > The solution is expensive in terms of address space and TLB entries: map > > the same pages twice, once only with PROT_EXEC, and once only with > > PROT_WRITE. > Just for experiment I've removed PROT_EXEC from my_mmap function in > rts/MBlock.c and recompiled GHC. The resulting GHC was able to compile > itself and my code. Binaries, produced by it worked fine with SELinux. > However, another problem related to GHCi ocurred. More details are > available at the 738 ticket you mentioned. > > So it is not clear if GHC does really need this PROT_EXEC. Can someone > familiar with GHC internals answer why PROT_EXEC is used in getMBlocks? It's not possible to correctly implement 'foreign import ccall "wrapper"' without self-modifying code on any mainstream computer architecture. Does this program work on your no-PROT_EXEC ghc? : {-# OPTIONS_GHC -ffi #-} import Foreign foreign import ccall "wrapper" wrap :: IO () -> IO (FunPtr (IO ())) foreign import ccall "dynamic" call :: FunPtr (IO ()) -> IO () main = call =<< wrap (print "hi!") Stefan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/78d0dc2d/attachment.bin From alexteslin at yahoo.co.uk Wed Aug 29 16:55:30 2007 From: alexteslin at yahoo.co.uk (Alexteslin) Date: Wed Aug 29 16:46:18 2007 Subject: [Haskell-cafe] defining mapPairs function Message-ID: <12395628.post@talk.nabble.com> Hello, I just came across with this question on the exam and can not think of implementing it. mapPair :: (a -> a -> a) -> [a] -> [a] such that mapPairs f [x1, x2, x3, x4...] = [f x1 x2, f x3 x4,...] and if the list contains an odd number of elements, the last one is kept unchanged, for example mapPairs f [x1, x2, x3] = [f x1 x2, x3] Any ideas will be appreciated, thanks -- View this message in context: http://www.nabble.com/defining-mapPairs-function-tf4350356.html#a12395628 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From alexteslin at yahoo.co.uk Wed Aug 29 17:04:12 2007 From: alexteslin at yahoo.co.uk (Alexteslin) Date: Wed Aug 29 16:55:00 2007 Subject: [Haskell-cafe] defining mapPairs function In-Reply-To: <12395628.post@talk.nabble.com> References: <12395628.post@talk.nabble.com> Message-ID: <12395696.post@talk.nabble.com> Alexteslin wrote: > > Hello, > > I just came across with this question on the exam and can not think of > implementing it. > > mapPair :: (a -> a -> a) -> [a] -> [a] > > such that mapPairs f [x1, x2, x3, x4...] = [f x1 x2, f x3 x4,...] > > and if the list contains an odd number of elements, the last one is kept > unchanged, for example > > mapPairs f [x1, x2, x3] = [f x1 x2, x3] > > > Any ideas will be appreciated, thanks > Oh, I think i just defined it - seems to work. I spent some time on the exam and made silly mistakes: mapPairs :: (a -> a -> a) -> [a] -> [a] mapPairs f [x] = [x] mapPairs f [] = [] mapPairs f (x:xs) = f x (head xs) : mapPairs f (tail xs) I was concing f x to (head xs) as well and mapPairs f [x] = x - this is very silly mistake. Does anyone think this is the right answer? -- View this message in context: http://www.nabble.com/defining-mapPairs-function-tf4350356.html#a12395696 Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com. From ndmitchell at gmail.com Wed Aug 29 17:06:34 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Wed Aug 29 16:57:22 2007 Subject: [Haskell-cafe] defining mapPairs function In-Reply-To: <12395628.post@talk.nabble.com> References: <12395628.post@talk.nabble.com> Message-ID: <404396ef0708291406y3ce2b282y59ec002eda963627@mail.gmail.com> Hi Alexteslin, > I just came across with this question on the exam and can not think of > implementing it. > > mapPair :: (a -> a -> a) -> [a] -> [a] > > such that mapPairs f [x1, x2, x3, x4...] = [f x1 x2, f x3 x4,...] I would implement this using direct recursion. As a starting point, the standard definition of map is: map f [] = [] map f (x:xs) = f x : map f xs You should be able to start at this and modify it to give the behaviour you require. If you want further hints, you might want to try the Haskell IRC Channel, which is good for these kind of questions. http://www.haskell.org/haskellwiki/IRC_channel Thanks Neil From ndmitchell at gmail.com Wed Aug 29 17:10:02 2007 From: ndmitchell at gmail.com (Neil Mitchell) Date: Wed Aug 29 17:00:51 2007 Subject: [Haskell-cafe] defining mapPairs function In-Reply-To: <12395696.post@talk.nabble.com> References: <12395628.post@talk.nabble.com> <12395696.post@talk.nabble.com> Message-ID: <404396ef0708291410k3a598e9bu2cede05d238cc8dc@mail.gmail.com> Hi > mapPairs :: (a -> a -> a) -> [a] -> [a] > mapPairs f [x] = [x] > mapPairs f [] = [] > mapPairs f (x:xs) = f x (head xs) : mapPairs f (tail xs) It looks like it works, but you can get a better version by changing the last line: mapPairs f (x:y:zs) = ... - left as an exercise, but no need for head or tail. Thanks Neil From dpfrey at shaw.ca Wed Aug 29 17:12:22 2007 From: dpfrey at shaw.ca (David Frey) Date: Wed Aug 29 17:04:28 2007 Subject: [Haskell-cafe] Looking for suggestions to improve my algorithm Message-ID: Hello Haskellers, I have been trying to learn a bit about Haskell by solving Project Euler problems. For those of you who don't know what Project Euler is, see http://projecteuler.net After solving problem 21, which is related to amicable pairs, I decided to attempt problem 95 since it is an extension of the same topic. The full description of problem 95 is here: http://projecteuler.net/index.php?section=problems&id=95 This is the summary: "Find the smallest member of the longest amicable chain with no element exceeding one million." I have attempted to solve this problem, but my solution is too resource hungry to search the full set of 1000000 numbers. I am hoping someone reading this list can suggest : - How I can improve my algorithm - An alternative algorithm that will be more efficient - Ways to profile a Haskell program to help me understand why my implementation is performing poorly. In addition to the question above, I would also be interested in comments on the style of the code. If there is a more idiomatic way to write portions of the code, I would like to see what it is. My solution is at the bottom of this e-mail. The program will probably run obscenely slow or die from stack overflow unless you replace [1..999999] with [1..somethingSmaller] in main. Thanks, David Frey --- BEGIN Main.hs --- module Main where import ProjectEuler (takeUntil, divisors) import qualified Data.Map as M import qualified Data.IntSet as I main = let initialContext = Context (I.fromList []) 0 0 in print $ cycleStart $ foldl checkForChain initialContext [1..999999] {- Idea: * Put all the numbers that have been visited into a map regardless of whether they are a part of a chain or not. * Store the min element in the cycle and the number of elements in the cycle * As you process, from 1->n if the stopping conditions for a sumOfDivisors result are: * has already been seen before * number is less than the start of this chain attempt * >= 1,000,000 -} data Context = Context {seenNum::I.IntSet, cycleStart::Int, cycleLength::Int} hasBeenSeen :: Int -> Context -> Bool hasBeenSeen n context = I.member n (seenNum context) markSeen :: Int -> Context -> Context markSeen n context = context { seenNum = (I.insert n (seenNum context)) } deleteFromSeen :: Int -> Context -> Context deleteFromSeen n context = context { seenNum = (I.delete n (seenNum context)) } {- - Examines the context to see if the input has potential to be a chain or not - based on whether the input number has been visited before. If it could be a - chain, an attempt is made to build the chain. -} checkForChain :: Context -> Int -> Context checkForChain context n = if hasBeenSeen n context then deleteFromSeen n context else buildChain context (sum $ divisors n) n [n] {- - Builds a chain until ones of the 3 stopping conditions are met or a chain is - found. If a chain is found the context will be updated with the new chain if - it is the longest. - - Stopping Conditions: - * Number has already been seen before - * Number is less than the start of this chain attempt - * Number >= 1,000,000 -} buildChain :: Context -> Int -> Int -> [Int] -> Context buildChain context candidate first cycleList = if elem candidate cycleList then foundChain (takeUntil ((==) candidate) cycleList) context else if candidate < first || candidate >= 1000000 || hasBeenSeen candidate context then context else buildChain (markSeen candidate context) (sum $ divisors candidate) first (candidate : cycleList) {- - Updates the context with the new longest chain and the start value if the - chain input parameter is longer than the one currently in the context. -} foundChain :: [Int] -> Context -> Context foundChain ls context = let l = length ls m = minimum ls in if l > (cycleLength context) then context { cycleLength = l, cycleStart = m } else if l == (cycleLength context) then let m = minimum ls in if m < (cycleStart context) then context { cycleStart = m } else context else context --- END Main.hs --- I put a bunch of common functions in ProjectEuler.hs. Here are the relevant functions for this problem: {- - Gets all of the proper divisors of a number. That is all divisors starting - from 1, but not including itself. -} divisors :: (Integral a) => a -> [a] divisors n = let p1 = [x | x <- [1 .. floor $ sqrt $ fromIntegral n], n `mod` x == 0] p2 = map (div n) (tail p1) in p1 `concatNoDupe` (reverse p2) where {- - Concatenate two lists. If the last element in the first list and the - first element in the second list are ==, produce only the value from - the first list in the output. -} concatNoDupe :: (Eq a) => [a] -> [a] -> [a] concatNoDupe [] ys = ys concatNoDupe [x] (y:ys) = if x == y then (y : ys) else (x : y : ys) concatNoDupe (x:xs) ys = x : (concatNoDupe xs ys) {- - Similar to takeWhile, but also takes the first element that fails the - predicate. -} takeUntil :: (a -> Bool) -> [a] -> [a] takeUntil pred (x:xs) = (x : if pred x then [] else takeUntil pred xs) takeUntil _ [] = [] From byorgey at gmail.com Wed Aug 29 18:13:58 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Wed Aug 29 18:04:47 2007 Subject: [Haskell-cafe] defining mapPairs function In-Reply-To: <12395628.post@talk.nabble.com> References: <12395628.post@talk.nabble.com> Message-ID: <22fcbd520708291513q61273f54i2f7beee1c7489acd@mail.gmail.com> On 8/29/07, Alexteslin wrote: > > > Hello, > > I just came across with this question on the exam and can not think of > implementing it. Wait, is this an exam for a class you're taking? Or just a problem from an exam that you're trying to solve for fun? If the former, it really isn't appropriate to ask the list to solve the problem for you, or even for hints. Your work on the exam should be your own. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/3952df01/attachment-0001.htm From thomas.hartman at db.com Wed Aug 29 18:36:04 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Wed Aug 29 18:26:59 2007 Subject: [Haskell-cafe] compiling happs under 6.7 (unbound implicit parameter error) Message-ID: Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: happs88.build Type: application/octet-stream Size: 3176 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/cc4c82e7/happs88.obj -------------- next part -------------- A non-text attachment was scrubbed... Name: W.hs Type: application/octet-stream Size: 7221 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/cc4c82e7/W.obj -------------- next part -------------- A non-text attachment was scrubbed... Name: happs8.8patchforghc67 Type: application/octet-stream Size: 1072 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/cc4c82e7/happs8.obj From byorgey at gmail.com Wed Aug 29 19:08:51 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Wed Aug 29 18:59:40 2007 Subject: [Haskell-cafe] Looking for suggestions to improve my algorithm In-Reply-To: References: Message-ID: <22fcbd520708291608y757e3282sd8282b4b4c3555bd@mail.gmail.com> On 8/29/07, David Frey wrote: > > Hello Haskellers, > > I have been trying to learn a bit about Haskell by solving Project Euler > problems. For those of you who don't know what Project Euler is, see > http://projecteuler.net > > After solving problem 21, which is related to amicable pairs, I decided > to attempt problem 95 since it is an extension of the same topic. > > The full description of problem 95 is here: > http://projecteuler.net/index.php?section=problems&id=95 > > This is the summary: > "Find the smallest member of the longest amicable chain with no element > exceeding one million." > > I have attempted to solve this problem, but my solution is too resource > hungry to search the full set of 1000000 numbers. > > I am hoping someone reading this list can suggest : > - How I can improve my algorithm > - An alternative algorithm that will be more efficient > - Ways to profile a Haskell program to help me understand why my > implementation is performing poorly. > > In addition to the question above, I would also be interested in > comments on the style of the code. If there is a more idiomatic way to > write portions of the code, I would like to see what it is. > > My solution is at the bottom of this e-mail. The program will probably > run obscenely slow or die from stack overflow unless you replace > [1..999999] with [1..somethingSmaller] in main. > > Thanks, > David Frey Hi David, Project Euler is a good way to learn some Haskell, although it does tend to give you a crash course in understanding laziness, efficiency and such in Haskell (whether that's good or bad depends on your point of view!). All you need to do to stop your program from overflowing the stack is to change foldl to foldl' in the definition of main (foldl' is in Data.List so you'll also have to import that). The problem with foldl is that since Haskell is lazy, instead of evaluating things as it goes along, it builds up a huge string of thunks (=unevaluated expressions) and doesn't even start evaluating anything until it reaches the end of the list, which can easily blow the stack. foldl' is a strict version of foldl which forces evaluation to take place as it goes along. For an excellent explanation of all of this, I suggest you read http://haskell.org/haskellwiki/Stack_overflow. As soon as I replaced foldl with foldl' in your code, it no longer overflows the stack -- however, it's still quite slow! I didn't wait long enough for it to finish when I ran it up to a million. I don't have any advice on that front at the moment, perhaps someone else will come along with a suggestion or two. In the meantime, you can poke around http://haskell.org/haskellwiki/Performance to see if it gives you any ideas. Hope this helps, -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/cf18e63a/attachment-0001.htm From daniel.is.fischer at web.de Wed Aug 29 19:11:52 2007 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Aug 29 19:01:57 2007 Subject: [Haskell-cafe] Looking for suggestions to improve my algorithm In-Reply-To: References: Message-ID: <200708300111.53256.daniel.is.fischer@web.de> Am Mittwoch, 29. August 2007 23:12 schrieb David Frey: > Hello Haskellers, > > I have been trying to learn a bit about Haskell by solving Project Euler > problems. Good :) > For those of you who don't know what Project Euler is, see > http://projecteuler.net > > After solving problem 21, which is related to amicable pairs, I decided > to attempt problem 95 since it is an extension of the same topic. > > The full description of problem 95 is here: > http://projecteuler.net/index.php?section=problems&id=95 > > This is the summary: > "Find the smallest member of the longest amicable chain with no element > exceeding one million." > > I have attempted to solve this problem, but my solution is too resource > hungry to search the full set of 1000000 numbers. I haven't looked closely, but what stands out is the obscenely slow divisors function. This could be sped up if you factored the numbers using the list of primes less than 1000. But since you need the factorization of all numbers <= 1000000 (that ought to be included, the wording is 'not exceeding' - but it doesn't appear in the chain, so you won't get a false answer by omitting it), you can do even better. My suggestion: 1. create an array or a map containing the sum of divisors of each number from 1 to 1000000 1.1. 'smallest prime factor' is useful for that 2. look for chains in that array/map > > I am hoping someone reading this list can suggest : > - How I can improve my algorithm > - An alternative algorithm that will be more efficient > - Ways to profile a Haskell program to help me understand why my > implementation is performing poorly. compile with -prof -auto-all and run with euler95 +RTS -P then read euler95.prof and take a look at the ghc users guide for more profiling options > > In addition to the question above, I would also be interested in > comments on the style of the code. If there is a more idiomatic way to > write portions of the code, I would like to see what it is. I'll take a look and see. But don't hold your breath, 'idiomatic' isn't one of my strengths. > > My solution is at the bottom of this e-mail. The program will probably > run obscenely slow or die from stack overflow unless you replace > [1..999999] with [1..somethingSmaller] in main. > > Thanks, > David Frey Cheers, Daniel From daniel.is.fischer at web.de Wed Aug 29 19:29:10 2007 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Aug 29 19:19:13 2007 Subject: [Haskell-cafe] Looking for suggestions to improve my algorithm In-Reply-To: <22fcbd520708291608y757e3282sd8282b4b4c3555bd@mail.gmail.com> References: <22fcbd520708291608y757e3282sd8282b4b4c3555bd@mail.gmail.com> Message-ID: <200708300129.10407.daniel.is.fischer@web.de> Am Donnerstag, 30. August 2007 01:08 schrieb Brent Yorgey: > Hi David, > > Project Euler is a good way to learn some Haskell, although it does tend to > give you a crash course in understanding laziness, efficiency and such in > Haskell (whether that's good or bad depends on your point of view!). > > All you need to do to stop your program from overflowing the stack is to > change foldl to foldl' in the definition of main (foldl' is in Data.List so > you'll also have to import that). I didn't even need to do that. Worked fine for me as it is (I compiled with -O2, that probably helped). > The problem with foldl is that since > Haskell is lazy, instead of evaluating things as it goes along, it builds > up a huge string of thunks (=unevaluated expressions) and doesn't even > start evaluating anything until it reaches the end of the list, which can > easily blow the stack. foldl' is a strict version of foldl which forces > evaluation to take place as it goes along. For an excellent explanation of > all of this, I suggest you read > http://haskell.org/haskellwiki/Stack_overflow. > > As soon as I replaced foldl with foldl' in your code, it no longer > overflows the stack -- however, it's still quite slow! I didn't wait long > enough for it to finish when I ran it up to a million. 45 seconds on my 1200MHz thing, not incredibly fast, but not obscenely slow either. > I don't have any > advice on that front at the moment, perhaps someone else will come along > with a suggestion or two. In the meantime, you can poke around > http://haskell.org/haskellwiki/Performance to see if it gives you any > ideas. > > Hope this helps, > -Brent Cheers, Daniel From ryani.spam at gmail.com Wed Aug 29 19:39:16 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Wed Aug 29 19:30:04 2007 Subject: [Haskell-cafe] Looking for suggestions to improve my algorithm In-Reply-To: References: Message-ID: <2f9b2d30708291639t57215541y6faa0a129d873fc6@mail.gmail.com> The algorithm I would use: Treat the problem as a directed graph of 1 million vertices where each vertex has at most 1 outgoing edge. Each vertex is labeled with a number N(v). For each vertex v, if sum(divisors(N(v))) <= 1 million, that vertex has an outgoing edge to vertex v', where N(v') == sum(divisors(N(v))). Call this graph G0. 1) No vertex with 0 incoming edges can be part of an amicable chain. 2) No vertex with 0 outgoing edges can be part of an amicable chain. If there are any such vertices in the graph, you can remove them. Call this new graph G1. Lemma 3) G1 is a directed graph where every vertex has at most one outgoing edge. Proof) G0 has this property and we have only deleted vertices from G0, which can only remove the You can repeat this process until no such vertices remain. Call the final resultant graph Gn. Lemma 4) Each vertex in Gn has exactly 1 incoming edge and exactly 1 outgoing edge. Proof: 1) No vertex has 0 incoming edges or else we would have removed it above. 2) Pidgeonhole principle: There are exactly as many edges as vertices. If any vertex had 2 incoming edges, there must be at least one vertex with 0 incoming vertices. Leamma 5) Each vertex in Gn is part of exactly one cycle. Proof) Follow the outgoing vertex chain from a vertex. Since Gn is finite and each vertex has exactly 1 incoming & 1 outgoing edge, eventually you will return to that vertex. This forms a cycle and there were no other possible edges to follow. Therefore: Algorithm: 1) Generate G0 2) Iteratively remove vertices from G0 to create G1, G2, etc. until there are no vertices with 0 incoming or outgoing edges. Let this graph be Gn 3) Split the vertices of Gn into equivalence classes where each class represents a cycle 4) Find the largest equivalence class. 5) Find the smallest label in that equivalence class. As to how to profile: > ghc --make -auto-all -prof -O2 main.hs > main +RTS -p will generate a profile report in main.prof. I've found that functions that do a large amount of allocation tend to be the easiest to optimize. Adding additional strictness annotations (seq) sometimes helps. For constructing graphs, you may want to look at http://www.haskell.org/haskellwiki/Tying_the_Knot as an alternative to the "IsSeen" maps that you might use to iteratively construct a graph. I'd probably use something like this: type Graph a = Map a Vertex data Vertex a = Vertex a [Vertex a] instance Eq a => Eq (Vertex a) where Vertex a _ == Vertex b _ = a == b then: constructGraph :: Ord a => (a -> Graph a -> [Vertex a]) -> [a] -> Graph a constructGraph mkEdges labels = graph where graph = Map.fromList [(label, Vertex label (mkEdges label graph)) | label <- labels] Notice that graph is used in its own definition! You can picture this as first creating a map like this: 1 -> Vertex 1 _ 2 -> Vertex 2 _ 3 -> Vertex 3 _ ... Then when you query the map for the edges of Vertex 2, only then does the mkEdges get called, with the constructed graph as input, updating the "_" with pointers to the actual vertices. -- ryan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070829/49a237ef/attachment.htm From asloane at ics.mq.edu.au Wed Aug 29 21:14:37 2007 From: asloane at ics.mq.edu.au (Tony Sloane) Date: Wed Aug 29 21:05:35 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <6433dupp.wl%jeremy.shaw@linspireinc.com> References: <002901c7e765$4b076f00$e1164d00$@be> <9d55dbaf0708251519n24fcb6b9kf89a350f75ea1ac4@mail.gmail.com> <6433dupp.wl%jeremy.shaw@linspireinc.com> Message-ID: <2C13F60D-9E8E-45BB-BF8C-A0E499D65254@ics.mq.edu.au> On 26/08/2007, at 10:07 AM, Jeremy Shaw wrote: > There is also an old project to port nhc98 to PalmOS -- not sure if it > is still active, or how far they got. AFAIK, nothing was ever > released. Yes, we were working on this at Macquarie Uni. The project has suffered a bit from a lack of resources. A while back we shifted our attention from nhc to yhc, since that seems to be a more likely base for success. We have a preliminary port of the yhc runtime which a student developed. It runs some simple programs on Palm OS, but it needs work to be usable by others. I expect to find time to devote to this later in the year, although we will also be evaluating whether putting effort into Palm OS is worth it any more, given its uncertain future. cheers, Tony Sloane From westondan at imageworks.com Wed Aug 29 22:34:24 2007 From: westondan at imageworks.com (Dan Weston) Date: Wed Aug 29 22:25:16 2007 Subject: [Haskell-cafe] defining mapPairs function In-Reply-To: <12395696.post@talk.nabble.com> References: <12395628.post@talk.nabble.com> <12395696.post@talk.nabble.com> Message-ID: <46D62CB0.8060800@imageworks.com> Sometimes it is interesting to approach things from a different perspective. The goofyness below will have been useful if it interests you in point-free programming. And anyway, I sure had a good time writing it... I am composing several common Haskell idioms: 1) When adjacent list elements are paired is (duplicate,offset one of them, zip together): Prelude> let z = [2,3,5] in zipWith (*) z (tail z) [6,15] 2) Uninterleaving (slicing) a list: Prelude> let slice = fst . foldr (\a ~(x,y) -> (a:y,x)) ([],[]) Prelude> slice [1..10] [1,3,5,7,9] For fun, I will do the slicing by changing the odd-indexed elements to Just x, and the even ones to Nothing, then filter only the Justed elements. There is a twist in your problem: do something special with the last odd (orphaned) element, i.e. append it. One thing to watch out for is that functions like head, tail, last are partial functions that don't play well with the empty list. In my case, I forstall disaster by prepending an unused Nothing value to my list before calling last. For comparison with your concise solution, below is my much more obfuscated one. Believe it or not, this algorithm was the first one that popped into my head. I have encoded it in point-free notation so that it reads along with its algorithm description (and because it's so much fun!) If the use of &&& and >>> is new to you, just read through to get a taste of how it can be used. Note that there is no variable name anywhere in the code, only functions! Solving the same problem several different ways will help build your toolbox. I am not recommending my solution for your exam (it's longer and less efficient than yours), only pointing out that there is always more than one way to do something in Haskell. :) import Control.Arrow((&&&),(>>>)) import Data.Maybe(catMaybes,maybeToList) mapPair = (id &&& tail >>> -- offset list by one uncurry (zipWith (*)) >>> -- multiply adjacent alternate >>> -- mark even elements catMaybes) -- delete even elements &&& -- Tuple this up with... (alternate >>> -- keep odd indices (Nothing:) >>> -- make sure there is a last last >>> -- get last maybeToList) -- keep if it had odd index >>> -- and then... uncurry (++) -- append pair of lists where alternate = zipWith ($) (cycle [Just,const Nothing]) -- Mark even-indexed elements for deletion -- cycle goes on forever, but zipWith stops at -- the end of the shorter list, so no worries. In this formulation, you can see that the whole second half above is there just to handle the orphaned last element, suggesting that there is something unnatural in the problem specification (probably put there to keep you from just using zipWith!). Here is a worked example for [2,3,5,7,11] in case you're not used to point-free programming: (id &&& tail >>> -- ([2,3,5,7,11],[3,5,7,11]) uncurry (zipWith (*)) >>> -- [6,15,35,77] alternate >>> -- [Just 6,Nothing,Just 35,Nothing] catMaybes) -- [6,35] &&& (alternate >>> -- [Just 2,Nothing,Just 5,Nothing,Just 11] (Nothing:) >>> -- [Nothing,Just 2,Nothing,Just 5, -- Nothing,Just 11] last >>> -- Just 11 maybeToList) -- [11] >>> -- ([6,35],[11]) uncurry (++) -- [6,35,11] Dan Weston Alexteslin wrote: > > > Alexteslin wrote: >> Hello, >> >> I just came across with this question on the exam and can not think of >> implementing it. >> >> mapPair :: (a -> a -> a) -> [a] -> [a] >> >> such that mapPairs f [x1, x2, x3, x4...] = [f x1 x2, f x3 x4,...] >> >> and if the list contains an odd number of elements, the last one is kept >> unchanged, for example >> >> mapPairs f [x1, x2, x3] = [f x1 x2, x3] >> >> >> Any ideas will be appreciated, thanks >> > > Oh, I think i just defined it - seems to work. > I spent some time on the exam and made silly mistakes: > > mapPairs :: (a -> a -> a) -> [a] -> [a] > mapPairs f [x] = [x] > mapPairs f [] = [] > mapPairs f (x:xs) = f x (head xs) : mapPairs f (tail xs) > > I was concing f x to (head xs) as well and > mapPairs f [x] = x - this is very silly mistake. > > Does anyone think this is the right answer? > From hughperkins at gmail.com Wed Aug 29 23:34:45 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Wed Aug 29 23:25:34 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <002901c7e765$4b076f00$e1164d00$@be> References: <002901c7e765$4b076f00$e1164d00$@be> Message-ID: <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> On 8/26/07, Peter Verswyvelen wrote: > Game developers are really struggling to get performance out of the > Playstation 3 console. This console has a single PowerPC CPU with 6 Cell SPU > coprocessors, all running at 3.3GHz. These SPUs have 256KB very high speed > local RAM, and data from the 512MB main memory can stream in and out via DMA > into these SPUs. The problem is that with imperative approaches this is a > nightmare to manage?. > > It would be a very cool project to show that Haskell could run on such a > platform, making it easier to take advance of its awesome power J Cool idea :-) Hmmm, random thought along similar lines, I mean I know the answer to this thought is no, but I'm curious: could we get Haskell to run on a graphics card??? I mean, I'm guessing the answer is no (not a difficult guess ;-) ), but curious what it would take to make a graphics card able to run Haskell? From derek.a.elkins at gmail.com Wed Aug 29 23:42:22 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Wed Aug 29 23:33:14 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> Message-ID: <1188445342.5429.13.camel@derek-laptop> On Thu, 2007-08-30 at 11:34 +0800, Hugh Perkins wrote: > On 8/26/07, Peter Verswyvelen wrote: > > Game developers are really struggling to get performance out of the > > Playstation 3 console. This console has a single PowerPC CPU with 6 Cell SPU > > coprocessors, all running at 3.3GHz. These SPUs have 256KB very high speed > > local RAM, and data from the 512MB main memory can stream in and out via DMA > > into these SPUs. The problem is that with imperative approaches this is a > > nightmare to manage?. > > > > It would be a very cool project to show that Haskell could run on such a > > platform, making it easier to take advance of its awesome power J > > Cool idea :-) > > Hmmm, random thought along similar lines, I mean I know the answer to > this thought is no, but I'm curious: could we get Haskell to run on a > graphics card??? I mean, I'm guessing the answer is no (not a > difficult guess ;-) ), but curious what it would take to make a > graphics card able to run Haskell? Either the language of the graphics card is Turing complete and the answer is yes or the language isn't and the answer is no. From hughperkins at gmail.com Wed Aug 29 23:53:24 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Wed Aug 29 23:44:17 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <1188445342.5429.13.camel@derek-laptop> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> <1188445342.5429.13.camel@derek-laptop> Message-ID: <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> On 8/30/07, Derek Elkins wrote: > Either the language of the graphics card is Turing complete and the > answer is yes or the language isn't and the answer is no. Well, a quick google for "are graphics cards turing complete?" suggests that some nVidia cards are Turing complete, but I couldnt find any reliable source (eg nvidia.com) to confirm this, and I dont know enough either to figure it out for myself, or even to confirm that this is both a necessary and sufficient condition for running Haskell. Related question: assuming temporarily that it is possible theoretically to get Haskell to run on a graphics card, to what extent would this actually be useful? From max.vasin at gmail.com Wed Aug 29 23:56:59 2007 From: max.vasin at gmail.com (Max Vasin) Date: Wed Aug 29 23:47:46 2007 Subject: [Haskell-cafe] defining mapPairs function In-Reply-To: <404396ef0708291410k3a598e9bu2cede05d238cc8dc@mail.gmail.com> References: <12395628.post@talk.nabble.com> <12395696.post@talk.nabble.com> <404396ef0708291410k3a598e9bu2cede05d238cc8dc@mail.gmail.com> Message-ID: <6b85ec520708292056k218a0b45ja6adeb3f2a176069@mail.gmail.com> 2007/8/30, Neil Mitchell : > Hi > > > mapPairs :: (a -> a -> a) -> [a] -> [a] > > mapPairs f [x] = [x] > > mapPairs f [] = [] > > mapPairs f (x:xs) = f x (head xs) : mapPairs f (tail xs) > > It looks like it works, but you can get a better version by changing > the last line: > > mapPairs f (x:y:zs) = ... - left as an exercise, but no need for head or tail. And you can get less equations if you replace first two equations with mapPairs f x = x and place it after Neil's. -- WBR, Max Vasin JID: maxvasin@jabber.ru From allbery at ece.cmu.edu Thu Aug 30 00:21:19 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Thu Aug 30 00:12:08 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> Message-ID: <4E019229-5502-4F93-8ADB-E9753AA186F5@ece.cmu.edu> On Aug 29, 2007, at 23:34 , Hugh Perkins wrote: > Hmmm, random thought along similar lines, I mean I know the answer to > this thought is no, but I'm curious: could we get Haskell to run on a > graphics card??? I thought someone had done that recently as a graduate thesis. -- 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 dpiponi at gmail.com Thu Aug 30 01:03:35 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Thu Aug 30 00:54:23 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> <1188445342.5429.13.camel@derek-laptop> <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> Message-ID: <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> On 8/29/07, Hugh Perkins wrote: > Well, a quick google for "are graphics cards turing complete?" > suggests that some nVidia cards are Turing complete http://developer.nvidia.com/object/cuda.html It's a C compiler with multiprocessor streaming extensions that targets nvidia cards. But it's not that simple... -- Dan From miguelimo38 at yandex.ru Thu Aug 30 01:40:08 2007 From: miguelimo38 at yandex.ru (Miguel) Date: Thu Aug 30 01:31:15 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: 1630000000170725596 References: <002901c7e765$4b076f00$e1164d00$@be> 1630000000170725596 Message-ID: <1166591188452408@webmail30.yandex.ru> > Hmmm, random thought along similar lines, I mean I know the answer to > this thought is no, but I'm curious: could we get Haskell to run on a > graphics card??? I mean, I'm guessing the answer is no (not a > difficult guess ;-) ), but curious what it would take to make a > graphics card able to run Haskell? What about running Haskell on a PostScript printer? PostScript IS Turing-complete. From radoslawg at gmail.com Thu Aug 30 02:34:21 2007 From: radoslawg at gmail.com (=?UTF-8?Q?Rados=C5=82aw_Grzanka?=) Date: Thu Aug 30 02:25:09 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <2C13F60D-9E8E-45BB-BF8C-A0E499D65254@ics.mq.edu.au> References: <002901c7e765$4b076f00$e1164d00$@be> <9d55dbaf0708251519n24fcb6b9kf89a350f75ea1ac4@mail.gmail.com> <6433dupp.wl%jeremy.shaw@linspireinc.com> <2C13F60D-9E8E-45BB-BF8C-A0E499D65254@ics.mq.edu.au> Message-ID: <9d55dbaf0708292334h2db35b2dw90b661cb92abe523@mail.gmail.com> 2007/8/30, Tony Sloane : > > On 26/08/2007, at 10:07 AM, Jeremy Shaw wrote: > > > There is also an old project to port nhc98 to PalmOS -- not sure if it > > is still active, or how far they got. AFAIK, nothing was ever > > released. > > Yes, we were working on this at Macquarie Uni. The project has > suffered a bit from a lack of resources. A while back we shifted our > attention from nhc to yhc, since that seems to be a more likely base > for success. > > We have a preliminary port of the yhc runtime which a student > developed. It runs some simple programs on Palm OS, but it needs > work to be usable by others. This is really cool. I'd love to write some Haskell for Palm. :) > I expect to find time to devote to this > later in the year, although we will also be evaluating whether > putting effort into Palm OS is worth it any more, given its uncertain > future. Yeah. This is actually a problem. Palm OS is rather doomed to be obsolete and Pocket PC is probably better target. Anyway, does anyone else experience a feeling that at the time of buying yourself new gadget you are already in "deprecated zone"? ;) Cheers, Radek. -- Codeside: http://codeside.org/ Przedszkole Miejskie nr 86 w Lodzi: http://www.pm86.pl/ From hughperkins at gmail.com Thu Aug 30 03:00:42 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 30 02:51:30 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <1166591188452408@webmail30.yandex.ru> References: <002901c7e765$4b076f00$e1164d00$@be> <1166591188452408@webmail30.yandex.ru> Message-ID: <837db430708300000j4ac29ab6k5396768fa9aa40e3@mail.gmail.com> On 8/30/07, Miguel wrote: > What about running Haskell on a PostScript printer? PostScript IS Turing-complete. Yes, because postscript printers are famous for being really fast ;-) From hughperkins at gmail.com Thu Aug 30 03:01:02 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 30 02:51:50 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> <1188445342.5429.13.camel@derek-laptop> <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> Message-ID: <837db430708300001q49006e8ejc88fde757e826b7c@mail.gmail.com> Dan Piponi wrote: > http://developer.nvidia.com/object/cuda.html > > It's a C compiler with multiprocessor streaming extensions that > targets nvidia cards. Whoa :-O Cool :-) > But it's not that simple... Few things are ;-) Whats the catch? Can we use a graphics-card as an n-core machine, where n >= 1024? From bulat.ziganshin at gmail.com Thu Aug 30 03:03:35 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 30 03:01:10 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <1166591188452408@webmail30.yandex.ru> References: <002901c7e765$4b076f00$e1164d00$@be> 1630000000170725596 <1166591188452408@webmail30.yandex.ru> Message-ID: <1766705232.20070830110335@gmail.com> Hello Miguel, Thursday, August 30, 2007, 9:40:08 AM, you wrote: > What about running Haskell on a PostScript printer? PostScript IS Turing-complete. it would be cool to port SOE graphics to PostScript engine :) -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From bulat.ziganshin at gmail.com Thu Aug 30 03:15:47 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 30 03:11:56 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <837db430708300001q49006e8ejc88fde757e826b7c@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> <1188445342.5429.13.camel@derek-laptop> <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> <837db430708300001q49006e8ejc88fde757e826b7c@mail.gmail.com> Message-ID: <1085382914.20070830111547@gmail.com> Hello Hugh, Thursday, August 30, 2007, 11:01:02 AM, you wrote: >> But it's not that simple... > Few things are ;-) Whats the catch? Can we use a graphics-card as an > n-core machine, where n >= 1024? no. it's more like 8-16 cores with 64-element SSE instructions http://developer.download.nvidia.com/compute/cuda/0_8/NVIDIA_CUDA_Programming_Guide_0.8.pdf -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From mailing_list at istitutocolli.org Thu Aug 30 06:14:28 2007 From: mailing_list at istitutocolli.org (Andrea Rossato) Date: Thu Aug 30 06:10:21 2007 Subject: [Haskell-cafe] interaction between OS processes Message-ID: <20070830101428.GI16235@laptop.nowhere.net> Hi, there's something I don't get about interaction among OS processes and Haskell handles/channels. Suppose I have a very small program that takes a line and prints it till you write "quit": main = do s <- getLine case s of "quit" -> putStrLn "quitting" >> return () _ -> loop s where loop s = do putStrLn s main This is a small interactive process I would like to talk to from another Haskell program, like the following one which, indeed, is just a wrapper around the first. Now, if I write a single line with "quit", I get "quitting" back, otherwise the program doesn't work. I think I need some direction in order to understand how handles work. The same with channels, I'm afraid. Could you please point me in the right direction? Thanks for your kind attention. Andrea The not working code: import Control.Concurrent import System.Process import System.IO main = do c <- runInteractiveCommand "./main2" loop c loop c@(i,o,e,p) = do s <- getLine hPutStrLn i s hFlush i -- now "i" is closed, right? s' <- hGetLine o putStrLn s' loop c From hughperkins at gmail.com Thu Aug 30 06:46:51 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 30 06:37:38 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <1085382914.20070830111547@gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> <1188445342.5429.13.camel@derek-laptop> <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> <837db430708300001q49006e8ejc88fde757e826b7c@mail.gmail.com> <1085382914.20070830111547@gmail.com> Message-ID: <837db430708300346j3e5f3042v6814f074984df4cd@mail.gmail.com> So, according to the blurb, and since this is product-specific, I dont know if this is allowed on the newsgroup?, but it does seem to be a fairly unique product? : - this technology works on GeGForce 8800 cards or better - there's a dedicated processing unit available called the "Tesla", which is available in a standalone version that you can plug into a PCI port, or in various pre-built 1U servers. The Tesla standalone card: - 128 thread processor - 518 gigaflops - 1.5 GB dedicated memory - Fits in one full-length, dual slot with one open PCI Express x16 slot - Retails for about 1500usd (so, I can afford one, I guess) For anyone who's counting, some sources put the computational capacity of the human brain at around 10petaflops, so 20,000 of these processors ought to be approaching that. (At a cost of 30 million dollars ;-) ) Anyway, 128 threads, if it is true, sounds fun. It's not 1024-threads, but it's decent, and it's more than the 32-threads where automatic threading is rumoured to bottom out. From bulat.ziganshin at gmail.com Thu Aug 30 08:01:33 2007 From: bulat.ziganshin at gmail.com (Bulat Ziganshin) Date: Thu Aug 30 07:53:29 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <837db430708300346j3e5f3042v6814f074984df4cd@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> <1188445342.5429.13.camel@derek-laptop> <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> <837db430708300001q49006e8ejc88fde757e826b7c@mail.gmail.com> <1085382914.20070830111547@gmail.com> <837db430708300346j3e5f3042v6814f074984df4cd@mail.gmail.com> Message-ID: <56604449.20070830160133@gmail.com> Hello Hugh, Thursday, August 30, 2007, 2:46:51 PM, you wrote: > - this technology works on GeGForce 8800 cards or better afaik, on any 8xxx cards - the only difference is number of threads > - 128 thread processor it's the same as 8800GTX. please read CUDA manual first. these 128 threads are not independent, each 8 or 16 threads execute the same code -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com From simonmarhaskell at gmail.com Thu Aug 30 08:23:06 2007 From: simonmarhaskell at gmail.com (Simon Marlow) Date: Thu Aug 30 08:13:57 2007 Subject: [Haskell-cafe] Re: GHC optimisations In-Reply-To: References: <46C82F23.9020509@btinternet.com> <20070819191420.GA3019@localhost.localdomain> Message-ID: <46D6B6AA.4000108@microsoft.com> Simon Peyton-Jones wrote: > GHC does some constant folding, but little by way of strength reduction, or using shifts instead of multiplication. It's pretty easy to add more: it's all done in a single module. Look at primOpRules in the module PrelRules. Although it isn't done at the Core level as Simon says, GHC's native code generator does turn multiplies into shifts, amongst various other low-level optimisations. In fact it's not clear that this kind of thing *should* be done at a high level, since it's likely to be machine-dependent. Cheers, Simon From daveroundy at gmail.com Thu Aug 30 09:00:46 2007 From: daveroundy at gmail.com (David Roundy) Date: Thu Aug 30 08:51:37 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <1766705232.20070830110335@gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <1166591188452408@webmail30.yandex.ru> <1766705232.20070830110335@gmail.com> Message-ID: <20070830130045.GA29643@darcs.net> On Thu, Aug 30, 2007 at 11:03:35AM +0400, Bulat Ziganshin wrote: > Hello Miguel, > > Thursday, August 30, 2007, 9:40:08 AM, you wrote: > > > What about running Haskell on a PostScript printer? PostScript IS Turing-complete. > > it would be cool to port SOE graphics to PostScript engine :) I spent some time a few years back figuring out how to use TH to "compile" haskell to postscript, but I didn't really know what I was doing and did a pretty poor job. But I'd love to have a postscript compiler. It's *so* nice to be able to produce compact and readable postscript files (which you could with compiled code, in the sense that the data portion of the file--which is what you want to read anyhow--would be readable). I've often wrote C code to write postscript code, which has the advantage of giving viewable output that also has the raw data in a format that is both computer-readable and human-readable. It'd be much nicer to do this in Haskell. -- David Roundy http://www.darcs.net From chaddai.fouche at gmail.com Thu Aug 30 09:08:45 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Thu Aug 30 08:59:31 2007 Subject: [Haskell-cafe] Looking for suggestions to improve my algorithm In-Reply-To: <2f9b2d30708291639t57215541y6faa0a129d873fc6@mail.gmail.com> References: <2f9b2d30708291639t57215541y6faa0a129d873fc6@mail.gmail.com> Message-ID: I managed it in 7 seconds (on 1500 MHz) with an idea close to yours (but I used IntSet, not IntMap), Daniel Fisher gave you some good ideas to achieve it, the real snail in this problem is the sumDivisors function. -- Jeda? From duncan.coutts at worc.ox.ac.uk Thu Aug 30 09:19:02 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Thu Aug 30 09:07:49 2007 Subject: [Gtk2hs-users] [Haskell-cafe] Bug in Gtk2HS 0.9.12/SOE on WinXP? Or is it just me? In-Reply-To: <20070824115817.247543da@aligatoro.ret> References: <20070824115817.247543da@aligatoro.ret> Message-ID: <1188479942.10322.42.camel@localhost> On Fri, 2007-08-24 at 11:58 +0200, Malte Milatz wrote: > Peter Verswyvelen : > > However, in the code below the blue and green triangle should render on top of each other, but the green triangle is rendered incorrectly. > > > > Being a newbie, I hesitate to file a bug report... Can anyone reproduce this? Maybe it works fine on unix? > > I can reproduce this with 0.9.12. I think this is now fixed. It's included in the current Gtk2Hs darcs repo or if you want to use your existing Gtk2Hs-0.9.12 installation you can get the updated soegtk package from hackage: http://hackage.haskell.org/cgi-bin/hackage-scripts/package/soegtk Duncan From allbery at ece.cmu.edu Thu Aug 30 09:34:01 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Thu Aug 30 09:24:49 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <9d55dbaf0708292334h2db35b2dw90b661cb92abe523@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <9d55dbaf0708251519n24fcb6b9kf89a350f75ea1ac4@mail.gmail.com> <6433dupp.wl%jeremy.shaw@linspireinc.com> <2C13F60D-9E8E-45BB-BF8C-A0E499D65254@ics.mq.edu.au> <9d55dbaf0708292334h2db35b2dw90b661cb92abe523@mail.gmail.com> Message-ID: <16173ECF-51C3-4373-8524-A9C647AEA33E@ece.cmu.edu> On Aug 30, 2007, at 2:34 , Rados?aw Grzanka wrote: > obsolete and Pocket PC is probably better target. Anyway, does anyone > else experience a feeling that at the time of buying yourself new > gadget you are already in "deprecated zone"? ;) I've been feeling that way since 1982.... -- 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 allbery at ece.cmu.edu Thu Aug 30 09:35:34 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Thu Aug 30 09:26:23 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <837db430708300000j4ac29ab6k5396768fa9aa40e3@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <1166591188452408@webmail30.yandex.ru> <837db430708300000j4ac29ab6k5396768fa9aa40e3@mail.gmail.com> Message-ID: On Aug 30, 2007, at 3:00 , Hugh Perkins wrote: > On 8/30/07, Miguel wrote: >> What about running Haskell on a PostScript printer? PostScript IS >> Turing-complete. > > Yes, because postscript printers are famous for being really fast ;-) You youngsters don't remember when PostScript printers *were* faster than the workstations they were connected to. :) -- 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 duncan.coutts at worc.ox.ac.uk Thu Aug 30 09:45:25 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Thu Aug 30 09:34:13 2007 Subject: [Haskell-cafe] 2D game graphics library for Haskell? In-Reply-To: <000b01c7e639$f8469c90$e8d3d5b0$@be> References: <000b01c7e639$f8469c90$e8d3d5b0$@be> Message-ID: <1188481525.10322.68.camel@localhost> On Fri, 2007-08-24 at 12:31 +0200, peterv wrote: > Anyway, SOE is great for learning Haskell, but it lacks a couple of > fundamental functions to make it really attractive, like: > - Support for images > > - Support for rendering to an ?offscreen graphics surface? and > reading the pixels from that surface (for pixel-wise collision > detection) > > - Support for detecting non-ASCII key presses (cursor keys, etc) > > - Support for joysticks > Concurrent Clean seems to have a nice 2D game library and PLT/DrScheme > also has nice support for basic 2D graphics, but somehow I feel > Haskell is more mature and more elegant. > So before digging into ?advanced? APIs (like GTK itself, which I know > nothing about, I?m a Win32 GDI/XNA/WPF expert), I should ask the > question if something similar exists? It has to be as simple as SOE. Would it be possible to extend the GTK SOE with support for the features mentioned above? Is this insanely difficult for someone like me who knows a lot about Win32 but little Haskell? Graphics.SOE.Gtk is actually based on a very nice vector graphics library Graphics.Rendering.Cairo which can certainly do nice things like rendering to off-screen surfaces and much more besides, like transparency, arbitrary affine scaling/rotation/translation. It can load and save images in png and svg formats. It's also got a rather nice API, so instead of trying to extend the GTK SOE you might find it simpler just to use Cairo directly. Gtk+'s event processing can certainly detect non-ASCII key presses, it's just the SOE getKey api that's limited to Char. I've no idea how joystick input is implemented in X/Gtk, I expect it's possible. The other alternative though it's getting more low level, is to use the Haskell bindings for SDL. Duncan From twifkak at comcast.net Thu Aug 30 10:05:44 2007 From: twifkak at comcast.net (Devin Mullins) Date: Thu Aug 30 09:53:38 2007 Subject: [Haskell-cafe] defining mapPairs function In-Reply-To: <46D62CB0.8060800@imageworks.com> References: <12395628.post@talk.nabble.com> <12395696.post@talk.nabble.com> <46D62CB0.8060800@imageworks.com> Message-ID: <46D6CEB8.5070206@comcast.net> That's great (really, thank you for such a fun example of Arrow programming), but isn't the (*) on line two of mapPair supposed to be a "point"? How would you make a point-less version of mapPair that actually had the type signature (a->a->a)->[a]->[a]*? (For that matter, /would/ you?) Devin * Grr, you're right. Were it not for that odd requirement, the type could be loosened to (a->a->b)->[a]->[b]. Maybe mapPairs should take a monadic (that is, one-arg) function to handle the dangling oddies. Dan Weston wrote: > import Control.Arrow((&&&),(>>>)) > import Data.Maybe(catMaybes,maybeToList) > > mapPair = (id &&& tail >>> -- offset list by one > uncurry (zipWith (*)) >>> -- multiply adjacent > alternate >>> -- mark even elements > catMaybes) -- delete even elements > > &&& -- Tuple this up with... > > (alternate >>> -- keep odd indices > (Nothing:) >>> -- make sure there is a last > last >>> -- get last > maybeToList) -- keep if it had odd index > > >>> -- and then... > > uncurry (++) -- append pair of lists > > where alternate = zipWith ($) (cycle [Just,const Nothing]) > -- Mark even-indexed elements for deletion > -- cycle goes on forever, but zipWith stops at > -- the end of the shorter list, so no worries. From hughperkins at gmail.com Thu Aug 30 11:02:56 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 30 10:53:44 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <56604449.20070830160133@gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> <1188445342.5429.13.camel@derek-laptop> <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> <837db430708300001q49006e8ejc88fde757e826b7c@mail.gmail.com> <1085382914.20070830111547@gmail.com> <837db430708300346j3e5f3042v6814f074984df4cd@mail.gmail.com> <56604449.20070830160133@gmail.com> Message-ID: <837db430708300802l4822000ibc49aa4c229d567c@mail.gmail.com> On 8/30/07, Bulat Ziganshin wrote: > it's the same as 8800GTX. please read CUDA manual first. these 128 > threads are not independent, each 8 or 16 threads execute the same > code Hmmmm, yes you are right. The GPU contains 8 "multiprocessors", where each multiprocessor contains multiple processors that execute the same code at the same time ("data parallel"). There are 8 processors in each multiprocessor unit, which run at twice the clock speed, so in one clock cycle they can execute 16 threads; and in two clock cycles they can execute all 32 threads of a "warp" (group of threads running the same code). Sooo.... kindof an interesting architecture. To what extent do we think that this is representative of future "general-purpose" multi-core architectures? Looking at Haskell parallelization, things like maps, and folds of associative functions can be split across the threads of a single warp. On the other hand, things like independent lets that we want to run in parallel would need to be assigned to independent warps. On the whole, maps and folds may constitute the bulk of what we are trying to parallelize (certainly, SPJ's NDP focuses extensively on maps), so this is probably broadly compatible with the CUDA architecture? From chaddai.fouche at gmail.com Thu Aug 30 11:33:11 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Thu Aug 30 11:23:56 2007 Subject: [Haskell-cafe] Looking for suggestions to improve my algorithm In-Reply-To: References: <2f9b2d30708291639t57215541y6faa0a129d873fc6@mail.gmail.com> Message-ID: 2007/8/30, Chadda? Fouch? : > I managed it in 7 seconds (on 1500 MHz) with an idea close to yours > (but I used IntSet, not IntMap), Daniel Fisher gave you some good > ideas to achieve it, the real snail in this problem is the sumDivisors > function. > I put my final solution on the wiki, it get it done in 6s now (on a Pentium M 1.73Mhz). -- Jeda? From dpiponi at gmail.com Thu Aug 30 12:04:44 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Thu Aug 30 11:55:32 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <837db430708300802l4822000ibc49aa4c229d567c@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> <1188445342.5429.13.camel@derek-laptop> <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> <837db430708300001q49006e8ejc88fde757e826b7c@mail.gmail.com> <1085382914.20070830111547@gmail.com> <837db430708300346j3e5f3042v6814f074984df4cd@mail.gmail.com> <56604449.20070830160133@gmail.com> <837db430708300802l4822000ibc49aa4c229d567c@mail.gmail.com> Message-ID: <625b74080708300904w6d849d4frb9726cc52e94e3a8@mail.gmail.com> On 8/30/07, Hugh Perkins wrote: > On the whole, maps and folds may constitute the bulk of what we are > trying to parallelize (certainly, SPJ's NDP focuses extensively on > maps), so this is probably broadly compatible with the CUDA > architecture? Right. But the functions and data that we are trying to map and fold could be anything, so we are required to have the full functionality of Haskell running on the GPU - unless the compiler can smartly figure out what should run on the GPU and what shouldn't. All in all, this could be a fairly ambitious project. Another, more modest, approach would be to define a DSL, maybe along the lines of what Lennart Augustsson has been doing on his blog (http://augustss.blogspot.com/), and implement a compiler back end that generates GPU code from the DSL. Something similar for C++ is Michael McCool's Sh library (www.csee.umbc.edu/~olano/s2005c37/ch07.pdf) which has now developed into a more general purpose commercial product. It seems to me that this could be a killer application for Haskell without a major rewrite of the Haskell compiler. What's more, the same DSL could have different back ends targeting GPUs, multiple cores or even just single CPUs (where you'd still get the benefits of partial evaluation). -- Dan From peter at syncad.com Thu Aug 30 12:17:37 2007 From: peter at syncad.com (Peter Hercek) Date: Thu Aug 30 12:08:41 2007 Subject: [Haskell-cafe] let and fixed point operator Message-ID: Hi, I find the feature that the construct "let x = f x in expr" assigns fixed point of f to x annoying. The reason is that I can not simply chain mofifications a variable like e.g. this: f x = let x = x * scale in let x = x + transform in g x When one is lucky then it results in a compile error; in worse cases it results in stack overflow in runtime. The annoying part is figuring out new and new variable names for essentially the same thing to avoid the search/evaluation of the fixed point. I suppose Haskell was designed so that it makes sense. The only usage I can see is like this: let fact = \x -> if x == 0 then 1 else x * fact (x-1) in ... but that is not any shorter than: let fact x = if x == 0 then 1 else x * fact (x-1) in So the question is what am I missing? Any nice use cases where fixed point search is so good that it is worth the trouble with figuring out new and new variable names for essentially the same stuff? Peter. From dpiponi at gmail.com Thu Aug 30 12:26:24 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Thu Aug 30 12:17:12 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: Message-ID: <625b74080708300926w6e1613fcu913a3ee6ca7f903b@mail.gmail.com> On 8/30/07, Peter Hercek wrote: > f x = > let x = x * scale in > let x = x + transform in > g x Why are you trying to call three different things by the same name 'x' in one tiny block of code? That's very confusing and makes it hard to reason equationally about the code. -- Dan From byorgey at gmail.com Thu Aug 30 12:37:19 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Thu Aug 30 12:28:08 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: Message-ID: <22fcbd520708300937x87bc427y7598a8a59f6b9d5d@mail.gmail.com> On 8/30/07, Peter Hercek wrote: > > Hi, > > I find the feature that the construct "let x = f x in expr" > assigns fixed point of f to x annoying. The reason is that > I can not simply chain mofifications a variable like e.g. this: > > f x = > let x = x * scale in > let x = x + transform in > g x > > When one is lucky then it results in a compile error; in worse > cases it results in stack overflow in runtime. The annoying > part is figuring out new and new variable names for essentially > the same thing to avoid the search/evaluation of the fixed point. > > I suppose Haskell was designed so that it makes sense. The only > usage I can see is like this: > > let fact = \x -> if x == 0 then 1 else x * fact (x-1) in > > ... but that is not any shorter than: > > let fact x = if x == 0 then 1 else x * fact (x-1) in > > So the question is what am I missing? Any nice use cases where > fixed point search is so good that it is worth the trouble with > figuring out new and new variable names for essentially the same > stuff? > > Peter. This is not really about fix points, it is about the very essence of functional programming. You cannot "modify" variables in the way you are suggesting; a variable such as x must *always refer to the same thing* within a given scope. This is not a liability, but rather a very nice thing: it makes it much easier to reason about programs if a given name always refers to the same thing. In an imperative language, where you really can modify the contents of variables, you do not have this guarantee. The same variable could refer to different values at different points in the program, which can lead to much confusion. Now, I do understand your annoyance; it certainly is annoying to type something like f x = let y = x * scale in let z = y + transform in g z where you have to come up with a bunch of different names for the intermediate values. But it's actually possible to do this in a much nicer way which is idiomatic in a functional language such as Haskell. Note that what you are really doing here is sending x through a "pipeline" of functions which transform it into another value. The way to combine functions into a pipeline is by using function concatenation: f = g . (+ transform) . (* scale) This is exactly the same thing, but no annoying intermediate names in sight! This simply says that f is the function you get when you first multiply by scale, then add transform, then finally apply function g. If you don't like the "point-free" style, you could also write something like f x = g $ (+ transform) $ (* scale) $ x (The $ simply lets you avoid writing lots of parentheses.) Hope this helps, -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/8afef084/attachment-0001.htm From peter at syncad.com Thu Aug 30 12:37:18 2007 From: peter at syncad.com (Peter Hercek) Date: Thu Aug 30 12:28:28 2007 Subject: [Haskell-cafe] Re: let and fixed point operator In-Reply-To: <625b74080708300926w6e1613fcu913a3ee6ca7f903b@mail.gmail.com> References: <625b74080708300926w6e1613fcu913a3ee6ca7f903b@mail.gmail.com> Message-ID: 1 f x = 2 let x = x * scale in 3 g x Hmmm ... just assume that the scope of the x on line 3 (which hides the x from the higher level scope is extended from line 3 to the beginning part of line 2 (from line start to the equal sign). OCAML does it. "Let before" in Clean does it too. Does not sound bad to me either. So this sounds to me like weak argument compared to disadvantages. There should be something else (I'm missing) there too... Thanks, Peter. Dan Piponi wrote: > On 8/30/07, Peter Hercek wrote: > >> f x = >> let x = x * scale in >> let x = x + transform in >> g x > > Why are you trying to call three different things by the same name 'x' > in one tiny block of code? That's very confusing and makes it hard to > reason equationally about the code. > -- > Dan From ketil at ii.uib.no Thu Aug 30 12:38:01 2007 From: ketil at ii.uib.no (Ketil Malde) Date: Thu Aug 30 12:28:50 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: Message-ID: <1188491881.6674.97.camel@nmd9999> On Thu, 2007-08-30 at 18:17 +0200, Peter Hercek wrote: > I find the feature that the construct "let x = f x in expr" > assigns fixed point of f to x annoying. Any alternative? Non-recursive assignments? > f x = > let x = x * scale in > let x = x + transform in > g x I think it is often it is better to avoid temporary names. I guess this is a simplified example, but I think it is better to write: f x = g (transform + scale * x) Or even use point-free style to avoid fixpoint? f = g . (+transform) . (* scale) -k From byorgey at gmail.com Thu Aug 30 12:38:54 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Thu Aug 30 12:29:40 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <22fcbd520708300937x87bc427y7598a8a59f6b9d5d@mail.gmail.com> References: <22fcbd520708300937x87bc427y7598a8a59f6b9d5d@mail.gmail.com> Message-ID: <22fcbd520708300938uc42fe9cyd41d79d589a02118@mail.gmail.com> On 8/30/07, Brent Yorgey wrote: > > > > The way to combine functions into a pipeline is by using function > concatenation: > Oops, of course I meant "function composition" instead of "function concatenation". -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/605f9db5/attachment.htm From derek.a.elkins at gmail.com Thu Aug 30 12:40:36 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Thu Aug 30 12:31:30 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: Message-ID: <1188492036.5429.23.camel@derek-laptop> On Thu, 2007-08-30 at 18:17 +0200, Peter Hercek wrote: > Hi, > > I find the feature that the construct "let x = f x in expr" > assigns fixed point of f to x annoying. The reason is that > I can not simply chain mofifications a variable like e.g. this: > > f x = > let x = x * scale in > let x = x + transform in > g x The common answer is that such code is considered ugly in most circumstances. Nevertheless, one solution would be to use the Identity monad and write that as, f x = runIdentity $ do x <- x*scale x <- x + transform return (g x) > > When one is lucky then it results in a compile error; in worse > cases it results in stack overflow in runtime. The annoying > part is figuring out new and > new variable names for essentially > the same thing to avoid the search/evaluation of the fixed point. > > I suppose Haskell was designed so that it makes sense. The only > usage I can see is like this: > > let fact = \x -> if x == 0 then 1 else x * fact (x-1) in > > ... but that is not any shorter than: > > let fact x = if x == 0 then 1 else x * fact (x-1) in > > So the question is what am I missing? Any nice use cases where > fixed point search is so good that it is worth the trouble with > figuring out new and new variable names for essentially the same > stuff? > > Peter. Haskell is lazy, we can have (mutually) recursive values. The canonical example, fibs = 0:1:zipWith (+) fibs (tail fibs) Slightly more interesting, karplusStrong = y where y = map (\x -> 1-2*x) (take 50 (randoms (mkStdGen 1))) ++ zipWith (\x y -> (x+y)/2) y (tail y) However, the real point is that you shouldn't be naming and renaming the "same" thing. Going back to your original example, it would be nicer to most to write it as, f = g . transform displacement . scale factor or pointfully f x = g (transform displacement (scale factor x)) with the appropriate combinators. From andrewcoppin at btinternet.com Thu Aug 30 13:16:12 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 30 13:05:52 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: Message-ID: <46D6FB5C.7090103@btinternet.com> OK, so it's only tangentally related, but... do you have *any idea* how many times I've written something like let x = (some complex function of x) in (some other complex function of x) when in fact what I *meant* to do was type x' instead of x?! It's really maddening to write 50,000 lines of code, eventually get it to compile, run it, and have the program lock up and start consuming so much virtual memory that the entire PC becomes unstable within seconds. (This isn't helped by the fact that Ctrl+C doesn't seem to make either GHCi or GHC-compiled programs halt...) Now you have 50,000 lines of otherwise untested code, and there's a bug within it *somewhere*... good luck. Obviously you might very well have *meant* to write x = f x. But would it be possible to add some kind of optional compiler warning to find such assignments? It can be a nightmare trying to track down where you made the mistake... From peter at syncad.com Thu Aug 30 13:16:59 2007 From: peter at syncad.com (Peter Hercek) Date: Thu Aug 30 13:08:38 2007 Subject: [Haskell-cafe] Re: let and fixed point operator In-Reply-To: <1188492036.5429.23.camel@derek-laptop> References: <1188492036.5429.23.camel@derek-laptop> Message-ID: Derek Elkins wrote: > On Thu, 2007-08-30 at 18:17 +0200, Peter Hercek wrote: >> Hi, >> >> I find the feature that the construct "let x = f x in expr" >> assigns fixed point of f to x annoying. The reason is that >> I can not simply chain mofifications a variable like e.g. this: >> >> f x = >> let x = x * scale in >> let x = x + transform in >> g x > > The common answer is that such code is considered ugly in most > circumstances. Nevertheless, one solution would be to use the Identity > monad and write that as, > f x = runIdentity $ do > x <- x*scale > x <- x + transform > return (g x) This is nice but more complicated. The goal should be to have it as simple as possible. > Haskell is lazy, we can have (mutually) recursive values. The canonical > example, > fibs = 0:1:zipWith (+) fibs (tail fibs) > Slightly more interesting, > karplusStrong = y > where y = map (\x -> 1-2*x) (take 50 (randoms (mkStdGen 1))) > ++ zipWith (\x y -> (x+y)/2) y (tail y) This is very nice argument! Thanks. I actually used it myself, but did not realize it when I was looking for the pro/contra arguments. This with the fact that it is not that good style to use the same name for intermediate results might be worth it. > However, the real point is that you shouldn't be naming and renaming the > "same" thing. Going back to your original example, it would be nicer to > most to write it as, > f = g . transform displacement . scale factor > or pointfully > f x = g (transform displacement (scale factor x)) > with the appropriate combinators. Essentially the same idea as the one from Brent Yorgey. Works fine till the operations can fill easily on one line. Then it does not scale that well since when it needs to be on more lines it interferes with automatic insertion of curly braces and semicolons by the layout rules (which are influenced by the context). Of course when there are more transformations it makes sense to name the intermediate results differently, but even few transformations may not fit easily when identifier names are long. Thanks, Peter. From byorgey at gmail.com Thu Aug 30 13:28:39 2007 From: byorgey at gmail.com (Brent Yorgey) Date: Thu Aug 30 13:19:24 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <46D6FB5C.7090103@btinternet.com> References: <46D6FB5C.7090103@btinternet.com> Message-ID: <22fcbd520708301028m2bafc822gd85a44acef3f0709@mail.gmail.com> > > It's really maddening to write 50,000 lines of code, eventually get it > to compile, run it, and have the program lock up and start consuming so > much virtual memory that the entire PC becomes unstable within seconds. (This isn't helped by the fact that Ctrl+C doesn't seem to make either > GHCi or GHC-compiled programs halt...) Now you have 50,000 lines of > otherwise untested code, and there's a bug within it *somewhere*... good > luck. Well, this is why you should test your program in bits and pieces before you get to that point. Writing 50,000 LOC before you even run your first test is a horrible idea in any programming language. -Brent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/8264cbd4/attachment.htm From daveroundy at gmail.com Thu Aug 30 13:40:07 2007 From: daveroundy at gmail.com (David Roundy) Date: Thu Aug 30 13:30:54 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <46D6FB5C.7090103@btinternet.com> References: <46D6FB5C.7090103@btinternet.com> Message-ID: <20070830174006.GB30773@darcs.net> On Thu, Aug 30, 2007 at 06:16:12PM +0100, Andrew Coppin wrote: > Obviously you might very well have *meant* to write x = f x. But would > it be possible to add some kind of optional compiler warning to find > such assignments? It can be a nightmare trying to track down where you > made the mistake... If you enable -Wall, ghc will warn you about this, provided that x was already bound in this context. -- David Roundy http://www.darcs.net From dpiponi at gmail.com Thu Aug 30 13:41:11 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Thu Aug 30 13:31:58 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <46D6FB5C.7090103@btinternet.com> References: <46D6FB5C.7090103@btinternet.com> Message-ID: <625b74080708301041g76b2664dp59eec01057d16f00@mail.gmail.com> On 8/30/07, Andrew Coppin wrote: > Obviously you might very well have *meant* to write x = f x. But would > it be possible to add some kind of optional compiler warning to find > such assignments? The thing that convinced me to learn Haskell in the first place was the fact that you could write x = f x. Equations where you refer to the same variable on the left and right hand sides are the bread of butter and mathematics, and I was really pleased to find a programming language that let me do the same. So to me the idea of having a warning for this is a bit like putting a sign on bottled water saying "Warning: Contents may be wet". But that's just me. :-) Still, it might be useful to for the compiler to warn when a newly introduced name shadows another one. -- Dan From paul.hudak at yale.edu Thu Aug 30 13:53:47 2007 From: paul.hudak at yale.edu (Paul Hudak) Date: Thu Aug 30 13:44:34 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <46D6FB5C.7090103@btinternet.com> References: <46D6FB5C.7090103@btinternet.com> Message-ID: <46D7042B.4040504@yale.edu> Andrew Coppin wrote: > OK, so it's only tangentally related, but... do you have *any idea* > how many times I've written something like > > let x = (some complex function of x) > in (some other complex function of x) > > when in fact what I *meant* to do was type x' instead of x?! I try not to use primes (x', x'', etc.) on variables for exactly this reason, and instead try to use more descriptive names, such as "newx", or "y", or whatever. Of course you can still make typing mistakes, but that's always the case... -Paul From jerzy.karczmarczuk at info.unicaen.fr Thu Aug 30 14:04:06 2007 From: jerzy.karczmarczuk at info.unicaen.fr (jerzy.karczmarczuk@info.unicaen.fr) Date: Thu Aug 30 13:54:13 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <22fcbd520708301028m2bafc822gd85a44acef3f0709@mail.gmail.com> References: <46D6FB5C.7090103@btinternet.com> <22fcbd520708301028m2bafc822gd85a44acef3f0709@mail.gmail.com> Message-ID: Brent Yorgey quotes: >> It's really maddening to write 50,000 lines of code, eventually get it >> to compile, run it, and have the program lock up and start consuming so >> much virtual memory that the entire PC becomes unstable within seconds. ... > Well, this is why you should test your program in bits and pieces > before you get to that point. Writing 50,000 LOC before you even run > your first test is a horrible idea in any programming language. I would rephrase this in a more brutal way. Writing 50000 lines of code in a language which seems to be badly mastered is a suicidary exercice. The let x=f x construct touches the essence of Haskell, its laziness, and it is used as a co-recursive way to replace loops. If it appears as the effect of forgetting the prime in x', use variables with long, meaningful names. This will economize some frustration. == An anecdote. Hundreds of years ago, when I taught programming in Cracow, Poland, we had some students from Vietnam (North, of course). One of them wrote programs where *all* variable names were ... you guess it, Vietnamese. It was easy to remember for him, no errors, no confusion. The only touchy point in this affair was that my group counted also three Vietnamese girls, who always when the boy with his poker-face produced publicly his solution, became red and began to giggle, or shouted angrily something I couldn't understand. Had I noted or memorized those programs, I would probably learn a good collection of particularly succulent Vietnamese swearwords. == Perhaps you should decorate your program a bit as well? Jerzy Karczmarczuk From chaddai.fouche at gmail.com Thu Aug 30 14:59:57 2007 From: chaddai.fouche at gmail.com (=?ISO-8859-1?Q?Chadda=EF_Fouch=E9?=) Date: Thu Aug 30 14:50:43 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: <46D6FB5C.7090103@btinternet.com> <22fcbd520708301028m2bafc822gd85a44acef3f0709@mail.gmail.com> Message-ID: Another interesting example of the x = f x use : coins = [1,2,5,10,20,50,100,200] beautiful = foldl (\without p -> let (poor,rich) = splitAt p without with = poor ++ zipWith (++) (map (map (p:)) with) rich in with ) ([[]] : repeat []) I don't remember who wrote this code (I rewrote it from memory since it impressed me quite a bit), but it's a very fast and beautiful (in my eyes at least) solution to the "menu" problem : (beautiful coins !! 200) would give you all the set of coins you could use to pay for 200, in less than 40ms on my computer... But, even more trivial... You use this all the time when you define recursive function, you know ? You would need to add a "rec" keyword to the language if you disallowed this. Myself I'm a big fan of the point-free style (to a limit) and find that it scale very well indeed when you begin to name the combination of functions you want to use. -- Jeda? From rodrigogribeiro at gmail.com Thu Aug 30 15:03:06 2007 From: rodrigogribeiro at gmail.com (Rodrigo Geraldo) Date: Thu Aug 30 14:53:52 2007 Subject: [Haskell-cafe] Newbie question: Why gfoldl has this strange type? Message-ID: <21ba18fc0708301203m3ffa1af8ud0c3b00851bdc4d5@mail.gmail.com> Hi! I am a novice in Haskell, and particularly I have interested in generic programming. This interest motivated me to read paper Scrap your boilerplate: A practical design pattern for generic programming, but I didn't understand the type of the function gfoldl, that was present in class Term (Data). Somebody could help me to understand the type of this function? Thanks... Rodrigo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/6cfd40e1/attachment.htm From trebla at vex.net Thu Aug 30 15:11:51 2007 From: trebla at vex.net (Albert Y. C. Lai) Date: Thu Aug 30 15:02:39 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: Message-ID: <46D71677.1090103@vex.net> Peter Hercek wrote: > So the question is what am I missing? Any nice use cases where > fixed point search is so good that it is worth the trouble with > figuring out new and new variable names for essentially the same > stuff? When I write functional code, I do find myself writing recursions much more often than writing imperative-wannabe assignments. I appreciate that Haskell's "let" defaults to recursion. I don't appreciate that OCaml makes a distinction between "let" and "letrec", since every time I change a non-recursive definition to a recursive one, I am prone to forget to change "let" to "letrec", IOW it is a hidden hazard to maintenance and evolution. When I write imperative code in Haskell, the notation is so different from functional code that "let" doesn't even come into the equation. When I write imperative code in imperative languages, my mental model treats "x:=x+1" as "x'=x+1 and y'=y and z'=z and ...", following several treatises on imperative semantics(*). Going back to functional programming, when I do write imperative-wannabe assignments, I totally like having names x, x', x'', etc., since they're in my head anyway. Underlying all this is probably the soberness of recognizing that "=" is not ":=". (*) Such as: Eric C. R. Hehner, "A Practical Theory of Programming". First edition Springer 1993. Current edition at http://www.cs.toronto.edu/~hehner/aPToP/ C. A. R. Hoare and He Jifeng, "Unifying Theories of Programming". Prentice Hall 1998. The Z specification language. From bf3 at telenet.be Thu Aug 30 15:18:30 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Thu Aug 30 15:09:13 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: Message-ID: <000301c7eb3a$8cc88310$a6598930$@be> F# and Concurrent Clean introduced special syntax for doing this. Basically they just invent new names for you. In Haskell (warning: I'm a newbie, so take this with a grain of salt), I guess you just use monads if you want to pass a value from one function to another under some context, or you could just make your own little much simpler combinator like: infixl 0 \> -- I just took the first weird symbol combination that came to mind, this does not mean anything (I hope ;-) x \> fx = fx x f x = x * scale \> \x -> x + transform \> \x -> g x like this you don't have to invent new names, and you don't have to type much more. I'm sure this silly sequencing operator must already exist in the library somewhere? -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Peter Hercek Sent: Thursday, August 30, 2007 6:18 PM To: haskell-cafe@haskell.org Subject: [Haskell-cafe] let and fixed point operator Hi, I find the feature that the construct "let x = f x in expr" assigns fixed point of f to x annoying. The reason is that I can not simply chain mofifications a variable like e.g. this: f x = let x = x * scale in let x = x + transform in g x When one is lucky then it results in a compile error; in worse cases it results in stack overflow in runtime. The annoying part is figuring out new and new variable names for essentially the same thing to avoid the search/evaluation of the fixed point. I suppose Haskell was designed so that it makes sense. The only usage I can see is like this: let fact = \x -> if x == 0 then 1 else x * fact (x-1) in ... but that is not any shorter than: let fact x = if x == 0 then 1 else x * fact (x-1) in So the question is what am I missing? Any nice use cases where fixed point search is so good that it is worth the trouble with figuring out new and new variable names for essentially the same stuff? Peter. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From duncan.coutts at worc.ox.ac.uk Thu Aug 30 15:31:29 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Thu Aug 30 15:20:15 2007 Subject: [Haskell-cafe] cabal install of HDBC-odbc fails on ghc 6.7, -I flag causes problems In-Reply-To: References: Message-ID: <1188502289.10322.99.camel@localhost> On Wed, 2007-08-29 at 10:05 -0400, Thomas Hartman wrote: > > Ah ok, so I did > > echo ":main build -v3" | /usr/local/bin/ghci-6.7.20070816 Setup.hs > 1>build.out 2>build.err > > and this does indeed seem more informative. advice? Turns out this was a bug in FilePath that Cabal was hitting. The bug was fixed some days ago in Cabal by not using the offending FilePath function. Hopefully the FilePath function will also be fixed. So the solution is to update your development version of Cabal to the latest version. Note that Cabal-1.1.6.x does not have this problem, only Cabal-1.1.7. Duncan From bf3 at telenet.be Thu Aug 30 15:32:23 2007 From: bf3 at telenet.be (Peter Verswyvelen) Date: Thu Aug 30 15:23:04 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <625b74080708300904w6d849d4frb9726cc52e94e3a8@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <837db430708292034x52ad0d95nf02e66a6d4c86e2a@mail.gmail.com> <1188445342.5429.13.camel@derek-laptop> <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> <837db430708300001q49006e8ejc88fde757e826b7c@mail.gmail.com> <1085382914.20070830111547@gmail.com> <837db430708300346j3e5f3042v6814f074984df4cd@mail.gmail.com> <56604449.20070830160133@gmail.com> <837db430708300802l4822000ibc49aa4c229d567c@mail.gmail.com> <625b74080708300904w6d849d4frb9726cc52e94e3a8@mail.gmail.com> Message-ID: <000a01c7eb3c$7d3997c0$77acc740$@be> Although I'm sure a lot can be done on modern GPU's (especially the DirectX 10 cards = Nvidia 8x00, that can write back to main memory, called "geometry shaders"), a Playstation 3 runs Linux, doesn't cost a lot, and it has 7 CPUs running at 3+ GHz, and 6 of these have parallel vector processing capacities. I think it should be easier (but far from easy) to implement Haskell on a PS3 then it is on a GPU. I developed imperative software for both, but not in depth, but to me GPUs are still too much oriented towards graphics, whilest the PS3 CPUs are more general purpose (although they also expect to process streams of data). See http://cell.scei.co.jp/e_download.html -----Original Message----- From: haskell-cafe-bounces@haskell.org [mailto:haskell-cafe-bounces@haskell.org] On Behalf Of Dan Piponi Sent: Thursday, August 30, 2007 6:05 PM To: haskell-cafe@haskell.org Subject: Re: Re[4]: [Haskell-cafe] Haskell on the Playstation 3? :-) On 8/30/07, Hugh Perkins wrote: > On the whole, maps and folds may constitute the bulk of what we are > trying to parallelize (certainly, SPJ's NDP focuses extensively on > maps), so this is probably broadly compatible with the CUDA > architecture? Right. But the functions and data that we are trying to map and fold could be anything, so we are required to have the full functionality of Haskell running on the GPU - unless the compiler can smartly figure out what should run on the GPU and what shouldn't. All in all, this could be a fairly ambitious project. Another, more modest, approach would be to define a DSL, maybe along the lines of what Lennart Augustsson has been doing on his blog (http://augustss.blogspot.com/), and implement a compiler back end that generates GPU code from the DSL. Something similar for C++ is Michael McCool's Sh library (www.csee.umbc.edu/~olano/s2005c37/ch07.pdf) which has now developed into a more general purpose commercial product. It seems to me that this could be a killer application for Haskell without a major rewrite of the Haskell compiler. What's more, the same DSL could have different back ends targeting GPUs, multiple cores or even just single CPUs (where you'd still get the benefits of partial evaluation). -- Dan _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe From westondan at imageworks.com Thu Aug 30 15:36:53 2007 From: westondan at imageworks.com (Dan Weston) Date: Thu Aug 30 15:27:44 2007 Subject: [Haskell-cafe] defining mapPairs function In-Reply-To: <46D6CEB8.5070206@comcast.net> References: <12395628.post@talk.nabble.com> <12395696.post@talk.nabble.com> <46D62CB0.8060800@imageworks.com> <46D6CEB8.5070206@comcast.net> Message-ID: <46D71C55.80805@imageworks.com> That's just a minor change of plumbing: import Control.Arrow((***),(&&&),(>>>),app) import Data.Maybe(catMaybes,maybeToList) mapPair :: (a -> a -> a) -> [a] -> [a] mapPair = curry mp where mp = (((zipWith >>> uncurry) *** -- (inter-elem function (id &&& tail) >>> -- ,duplicate and offset) app >>> -- apply fst to snd alternate >>> -- mark even elements catMaybes)) -- delete even elements &&& -- Tuple this up with... (snd >>> alternate >>> -- keep odd indices (Nothing:) >>> -- make sure there is a last last >>> -- get last maybeToList) -- keep if it had odd index >>> -- and then... uncurry (++) -- append pair of lists alternate = zipWith ($) (cycle [Just,const Nothing]) -- Mark even-indexed elements for deletion -- cycle goes on forever, but zipWith stops at -- the end of the shorter list, so no worries. When you find yourself manually plumbing the inputs, that's probably where point-free has morphed into point-less programming! I plead guilty! :) Dan Weston Devin Mullins wrote: > That's great (really, thank you for such a fun example of Arrow > programming), but isn't the (*) on line two of mapPair supposed to be a > "point"? How would you make a point-less version of mapPair that > actually had the type signature (a->a->a)->[a]->[a]*? (For that matter, > /would/ you?) > > Devin > * Grr, you're right. Were it not for that odd requirement, the type > could be loosened to (a->a->b)->[a]->[b]. Maybe mapPairs should take a > monadic (that is, one-arg) function to handle the dangling oddies. > > Dan Weston wrote: >> import Control.Arrow((&&&),(>>>)) >> import Data.Maybe(catMaybes,maybeToList) >> >> mapPair = (id &&& tail >>> -- offset list by one >> uncurry (zipWith (*)) >>> -- multiply adjacent >> alternate >>> -- mark even elements >> catMaybes) -- delete even elements >> >> &&& -- Tuple this up with... >> >> (alternate >>> -- keep odd indices >> (Nothing:) >>> -- make sure there is a last >> last >>> -- get last >> maybeToList) -- keep if it had odd index >> >> >>> -- and then... >> >> uncurry (++) -- append pair of lists >> >> where alternate = zipWith ($) (cycle [Just,const Nothing]) >> -- Mark even-indexed elements for deletion >> -- cycle goes on forever, but zipWith stops at >> -- the end of the shorter list, so no worries. > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From chad.scherrer at gmail.com Thu Aug 30 15:38:47 2007 From: chad.scherrer at gmail.com (Chad Scherrer) Date: Thu Aug 30 15:29:33 2007 Subject: [Haskell-cafe] redirecting stdout Message-ID: Is it possible to write a function redirect :: Handle -> IO () -> IO () so that "redirect h action" is just like action, except that all the output written to stdout now gets sent to h instead? Thanks, Chad From tretriluxana.s at gmail.com Thu Aug 30 15:54:33 2007 From: tretriluxana.s at gmail.com (Sukit Tretriluxana) Date: Thu Aug 30 15:45:19 2007 Subject: [Haskell-cafe] darcs behind firewall Message-ID: <8252533f0708301254m167fcccfn7a71208e3d9beb8b@mail.gmail.com> Hi all, Does anyone know how to specify proxy server and port for darcs to use when it connects to servers? I am behind firewall most of the time and all requests have to go through a proxy. Thanks, Ed -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/13ab20ea/attachment.htm From darrelll at amgen.com Thu Aug 30 16:01:29 2007 From: darrelll at amgen.com (Lewis-Sandy, Darrell) Date: Thu Aug 30 15:52:17 2007 Subject: [Haskell-cafe] FFI and DLLs Message-ID: <567ACB2E39C83543B746F1AD7F5E5E040C294CD4@wa-mb2-sea.amgen.com> An early proposal for the FFI supported importing functions directly from dynamic link libraries: www. haskell.org/hdirect/ffi-a4.ps.gz This looks like it was dropped from the final version of the addendum in favor of C header files as the sole form of import entities. Not being a C programmer, how would one go about importing a foreign function (e.g. void Foo(void) ) from a dynamic link library (e.g. foo.dll)?? Would someone be willing to provide an explicit example? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/c5ba72ac/attachment.htm From bos at serpentine.com Thu Aug 30 16:25:04 2007 From: bos at serpentine.com (Bryan O'Sullivan) Date: Thu Aug 30 16:17:05 2007 Subject: [Haskell-cafe] redirecting stdout In-Reply-To: References: Message-ID: <46D727A0.4020609@serpentine.com> Chad Scherrer wrote: > Is it possible to write a function > > redirect :: Handle -> IO () -> IO () > > so that "redirect h action" is just like action, except that all the > output written to stdout now gets sent to h instead? No. The file descriptor used for IO is wired into a Handle, just as in a FILE * in C. You can change where stdout points using hDuplicateTo, but that affects the entire process. References: <000301c7eb3a$8cc88310$a6598930$@be> Message-ID: On Thu, 30 Aug 2007, Peter Verswyvelen wrote: > infixl 0 \> -- I just took the first weird symbol combination that came to > mind, this does not mean anything (I hope ;-) > > x \> fx = fx x > > f x = x * scale \> \x -> > x + transform \> \x -> > g x > > like this you don't have to invent new names, and you don't have to type > much more. > > I'm sure this silly sequencing operator must already exist in the library > somewhere? Sure, its name is (>>=). It must be used for the Identity monad, as mentioned by Derek Elkins earlier in this thread. From thomas.hartman at db.com Thu Aug 30 16:27:46 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Thu Aug 30 16:18:34 2007 Subject: [Haskell-cafe] darcs behind firewall In-Reply-To: <8252533f0708301254m167fcccfn7a71208e3d9beb8b@mail.gmail.com> Message-ID: If you are on linux (I'm on ubuntu) you should be able to set export http_proxy=http://proxyserver.com:1234 export https_proxy=http://proxyserver.com:123 vars, per what your sysadmin says. In my case, these are set to the same var that permits me to use firefox via the proxy, in firefox -> edit-> preferences -> network tab -> connection settings, http proxy. and darcs should "just work" thomas. "Sukit Tretriluxana" Sent by: haskell-cafe-bounces@haskell.org 08/30/2007 03:54 PM To haskell-cafe@haskell.org cc Subject [Haskell-cafe] darcs behind firewall Hi all, Does anyone know how to specify proxy server and port for darcs to use when it connects to servers? I am behind firewall most of the time and all requests have to go through a proxy. Thanks, Ed_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/b9600f31/attachment.htm From andrewcoppin at btinternet.com Thu Aug 30 17:10:33 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 30 17:00:10 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <22fcbd520708301028m2bafc822gd85a44acef3f0709@mail.gmail.com> References: <46D6FB5C.7090103@btinternet.com> <22fcbd520708301028m2bafc822gd85a44acef3f0709@mail.gmail.com> Message-ID: <46D73249.10206@btinternet.com> Brent Yorgey wrote: > > > It's really maddening to write 50,000 lines of code, eventually get it > to compile, run it, and have the program lock up and start > consuming so > much virtual memory that the entire PC becomes unstable within > seconds. > > (This isn't helped by the fact that Ctrl+C doesn't seem to make > either > GHCi or GHC-compiled programs halt...) Now you have 50,000 lines of > otherwise untested code, and there's a bug within it > *somewhere*... good > luck. > > > Well, this is why you should test your program in bits and pieces > before you get to that point. Writing 50,000 LOC before you even run > your first test is a horrible idea in any programming language. Horrible? Yes. Avoidable? Not always, sadly... (NB. 50,000 is an exaggeration. I've never written a program that large in my entire life in any programming language I've ever used.) The problem is that, depending on the program, sometimes you have to write quite a lot of infrastructure before you get to the point where there's anything finished enough to test. Obviously it's better to avoid that happening, but that's easier said then done! From andrewcoppin at btinternet.com Thu Aug 30 17:11:02 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 30 17:00:43 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <20070830174006.GB30773@darcs.net> References: <46D6FB5C.7090103@btinternet.com> <20070830174006.GB30773@darcs.net> Message-ID: <46D73266.5090401@btinternet.com> David Roundy wrote: > On Thu, Aug 30, 2007 at 06:16:12PM +0100, Andrew Coppin wrote: > >> Obviously you might very well have *meant* to write x = f x. But would >> it be possible to add some kind of optional compiler warning to find >> such assignments? It can be a nightmare trying to track down where you >> made the mistake... >> > > If you enable -Wall, ghc will warn you about this, provided that x was > already bound in this context. > Most excellent. GHC saves the day again... From andrewcoppin at btinternet.com Thu Aug 30 17:13:53 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Thu Aug 30 17:03:29 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <625b74080708301041g76b2664dp59eec01057d16f00@mail.gmail.com> References: <46D6FB5C.7090103@btinternet.com> <625b74080708301041g76b2664dp59eec01057d16f00@mail.gmail.com> Message-ID: <46D73311.1070006@btinternet.com> Dan Piponi wrote: > On 8/30/07, Andrew Coppin wrote: > >> Obviously you might very well have *meant* to write x = f x. But would >> it be possible to add some kind of optional compiler warning to find >> such assignments? >> > > The thing that convinced me to learn Haskell in the first place was > the fact that you could write x = f x. Equations where you refer to > the same variable on the left and right hand sides are the bread of > butter and mathematics, and I was really pleased to find a programming > language that let me do the same. Yeah, but... programs aren't like mathematics. I know people claim that they are, but they aren't. In mathematics, if you write "x = f y" you mean that these two expressions are equal. In Haskell, if you say "x = f y" you mean *make* then equal! (Let us not even go into the times when expressions like "z = f z" actually means "z[n+1] = f [z]"...) > So to me the idea of having a > warning for this is a bit like putting a sign on bottled water saying > "Warning: Contents may be wet". But that's just me. :-) > Well, it's definitely a valid thing to want to do, which is why I asked for a *warning* not an error. ;-) Still, this seems to be an extremely common way for me to hurt myself, so... > Still, it might be useful to for the compiler to warn when a newly > introduced name shadows another one. > ...or that... From peter at syncad.com Thu Aug 30 17:28:03 2007 From: peter at syncad.com (Peter Hercek) Date: Thu Aug 30 17:19:02 2007 Subject: [Haskell-cafe] Re: let and fixed point operator In-Reply-To: References: <46D6FB5C.7090103@btinternet.com> <22fcbd520708301028m2bafc822gd85a44acef3f0709@mail.gmail.com> Message-ID: Chadda? Fouch? wrote: > But, even more trivial... You use this all the time when you define > recursive function, you know ? You would need to add a "rec" keyword > to the language if you disallowed this. Great and new reason too. Trying to make a difference based on presence of formal argument would be bad since point-free is useful too. Well, in my opinion, only to a certain degree since from some point on it is more understandable to name intermediate results (points). Thanks, Peter. From thomas.hartman at db.com Thu Aug 30 17:37:10 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Thu Aug 30 17:27:59 2007 Subject: [Haskell-cafe] happs on ghc 6.7 won't work because of dependency on Data.Binary (everything that depends on Data.Binary broken at present) ( unknown symbol `stg_uncheckedShiftRL64' ) Message-ID: happs on ghc 6.7 won't work because of dependency on Data.Binary, since everything that depends on Data.Binary is broken at present. This is for Data.Binary installed via cabal from darcs get --partial http://darcs.haskell.org/binary . Cabal installed without any errors, but perhaps there should have been one since it appears broke. So I think my project of using the ghc debugger to help understand happs is on ice until this gets resolved. Unless this has been fixed since August 16. (Anyone out there got a more recent version?) $ cat UseDataBinary.hs import Data.Binary main = putStrLn "hello world" $ /usr/local/bin/ghc-6.6.1 -e 'main' UseDataBinary.hs hello world $ /usr/local/bin/ghc-6.7.20070816 -e 'main' UseDataBinary.hs : /usr/local/lib/binary-0.3/ghc-6.7.20070816/HSbinary-0.3.o: unknown symbol `stg_uncheckedShiftRL64' ghc-6.7.20070816: unable to load package `binary-0.3' $ /usr/local/bin/ghc-6.7.20070816 -e '' UseDataBinary.hs --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/e9fd5127/attachment.htm From dpiponi at gmail.com Thu Aug 30 17:38:25 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Thu Aug 30 17:29:14 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <46D73311.1070006@btinternet.com> References: <46D6FB5C.7090103@btinternet.com> <625b74080708301041g76b2664dp59eec01057d16f00@mail.gmail.com> <46D73311.1070006@btinternet.com> Message-ID: <625b74080708301438ra50b898pac6c875c797f866a@mail.gmail.com> On 8/30/07, Andrew Coppin wrote: > Yeah, but... programs aren't like mathematics. I know people claim that > they are, but they aren't. But the raison d'etre of Haskell is to make programming more like mathematics. That motivates everything from the fact that it's a declarative language, and the support for equational reasoning, to the fact that IO happens in a monad, and the option to use primes on variables names. > In mathematics, if you write "x = f y" you mean that these two > expressions are equal. In Haskell, if you say "x = f y" you mean *make* > then equal! Haskell is a declarative language, not an imperative language. When you write "x = f x" in Haskell, you're declaring to the compiler that x equals f x. In an imperative language like Java, the line x = f(x) gives the compiler the imperative to emit instructions to store the value of f(x) in a 'box' called x. In Haskell, there is no box. (When you get down to the nuts and bolts, a Haskell compiler and a Java compiler may ultimately actually do the same thing here, but the way you think about a language is as important as what instructions the code generator emits.) -- Dan From jerzy.karczmarczuk at info.unicaen.fr Thu Aug 30 17:58:00 2007 From: jerzy.karczmarczuk at info.unicaen.fr (jerzy.karczmarczuk@info.unicaen.fr) Date: Thu Aug 30 17:48:06 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <625b74080708301438ra50b898pac6c875c797f866a@mail.gmail.com> References: <46D6FB5C.7090103@btinternet.com> <625b74080708301041g76b2664dp59eec01057d16f00@mail.gmail.com> <46D73311.1070006@btinternet.com> <625b74080708301438ra50b898pac6c875c797f866a@mail.gmail.com> Message-ID: Dan Piponi writes: >> In mathematics, if you write "x = f y" you mean that these two >> expressions are equal. In Haskell, if you say "x = f y" you mean *make* >> then equal! > Haskell is a declarative language, not an imperative language. When > you write "x = f x" in Haskell, you're declaring to the compiler that > x equals f x. In an imperative language like Java, the line x = f(x) > gives the compiler the imperative to emit instructions to store the > value of f(x) in a 'box' called x. In Haskell, there is no box. Well, there are boxes... But there also thunks and latent, yet-unevaluated graphs... Anyway, I believe strongly that ALL people who have problems with the Haskell protocole, and they are numerous, I teach a good sample of them, should be encouraged to learn Prolog. IN DEPTH, and I mean it, Andrew Coppin and Peter Hercek ! In Prolog A=B is the unification, which is a bit more than equality, and something much more aggressive than an assignment. When you REALLY understand unification, it will be easier to see the lazy instantiation of the Haskell assignment, and, additionally, it becomes much more easy to understand the automatic inference of types, which sooner or later must be harnessed by all Haskell programmers... The best. Jerzy Karczmarczuk From dpiponi at gmail.com Thu Aug 30 18:02:21 2007 From: dpiponi at gmail.com (Dan Piponi) Date: Thu Aug 30 17:53:06 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: <46D6FB5C.7090103@btinternet.com> <625b74080708301041g76b2664dp59eec01057d16f00@mail.gmail.com> <46D73311.1070006@btinternet.com> <625b74080708301438ra50b898pac6c875c797f866a@mail.gmail.com> Message-ID: <625b74080708301502h66e7dd1av40b79d5b124ea123@mail.gmail.com> On 8/30/07, jerzy.karczmarczuk@info.unicaen.fr wrote: > Dan Piponi writes: > > In Haskell, there is no box. > > Well, there are boxes... > But there also thunks and latent, yet-unevaluated graphs... But the point of Haskell is to provide an abstraction that hides these details from you. (Though ultimately it's a leaky abstraction and there comes a point where you do need to know about these things.) > Anyway, I believe strongly that ALL people who have problems with the > Haskell protocole, and they are numerous, I teach a good sample of them, > should be encouraged to learn Prolog. I'd second that. It's hard to see the difference between declarative and imperative programming when you only have one instance of a declarative language from which to generalise. -- Dan From derek.a.elkins at gmail.com Thu Aug 30 18:05:53 2007 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Thu Aug 30 17:56:41 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: <46D6FB5C.7090103@btinternet.com> <625b74080708301041g76b2664dp59eec01057d16f00@mail.gmail.com> <46D73311.1070006@btinternet.com> <625b74080708301438ra50b898pac6c875c797f866a@mail.gmail.com> Message-ID: <1188511554.5429.28.camel@derek-laptop> On Thu, 2007-08-30 at 23:58 +0200, jerzy.karczmarczuk@info.unicaen.fr wrote: > Dan Piponi writes: > > >> In mathematics, if you write "x = f y" you mean that these two > >> expressions are equal. In Haskell, if you say "x = f y" you mean *make* > >> then equal! > > > > Haskell is a declarative language, not an imperative language. When > > you write "x = f x" in Haskell, you're declaring to the compiler that > > x equals f x. In an imperative language like Java, the line x = f(x) > > gives the compiler the imperative to emit instructions to store the > > value of f(x) in a 'box' called x. In Haskell, there is no box. > > Well, there are boxes... > But there also thunks and latent, yet-unevaluated graphs... > > Anyway, I believe strongly that ALL people who have problems with the > Haskell protocole, and they are numerous, I teach a good sample of them, > should be encouraged to learn Prolog. IN DEPTH, and I mean it, Andrew > Coppin and Peter Hercek ! > > In Prolog A=B is the unification, which is a bit more than equality, and > something much more aggressive than an assignment. When you REALLY > understand unification, it will be easier to see the lazy instantiation > of the Haskell assignment, and, additionally, it becomes much more easy > to understand the automatic inference of types, which sooner or later > must be harnessed by all Haskell programmers... One should learn Prolog anyway. From thomas.hartman at db.com Thu Aug 30 19:04:21 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Thu Aug 30 18:55:08 2007 Subject: [Haskell-cafe] Re: trouble compiling regex posix head (I think >0.92) on ghc 6.7 In-Reply-To: <46D6F191.8030509@list.mightyreason.com> Message-ID: I darcs pulled cabal head to get latest cabal, removed -Werror from GHC-Options in the cabal file, removed HsRegexPosixConfig.h and tried again with the same result. It seems to really want that file. With, it installs, without, no install. $ darcs whatsnew { hunk ./regex-posix.cabal 16 -Build-Depends: regex-base >= 0.80, base >= 2.0 +Build-Depends: regex-base >= 0.80, base >= 2.0, array, containers, byt estring hunk ./regex-posix.cabal 32 -GHC-Options: -Wall -Werror -O2 +GHC-Options: -Wall -O2 hunk ./regex-posix.cabal 43 -Include-Dirs: include +Include-Dirs: include/regex } Chris Kuklewicz 08/30/2007 12:34 PM To Thomas Hartman/ext/dbcom@DBAmericas cc haskell-cafe@haskell.org, "cvs-ghc@haskell.org" Subject Re: trouble compiling regex posix head (I think >0.92) on ghc 6.7 Thomas Hartman wrote: > > I'm trying to compile regex-posix on ghc 6.7. (Ultimate goal: happs on > 6.7). I have not explored ghc 6.7. You should also try posting on the mailing list. > > First, I patched by changing the cabal file to be compatible with the > new libraries broken out of base. I also had to add HsRegexPosixConfig.h > to include/regex (I just copied it from somewhere else on my hard drive > where I guess it had been put by an earlier regex-posix install, I don't > know if it's compatible here but at least it permitted things to compile > further.) I had no idea what HsRegexPosixConfig was, and I have no such file at all. So I looked in Wrap.hsc and found: > #ifdef HAVE_REGEX_H > #define HAVE_REGCOMP 1 > #else > #ifndef __NHC__ > #include "HsRegexPosixConfig.h" > #else > #define HAVE_REGEX_H 1 > #define HAVE_REGCOMP 1 > #endif > #endif Note that I did not write that section -- that was added by someone else. So HsRegexPosixConfig.h should only matter if HAVE_REGEX_H is undefined. The regex-base.cabal file says: "CC-Options: -DHAVE_REGEX_H" So unless Cabal is having a very very bad day, I assume that HsRegexPosixConfig.h is never needed. That it matters to your build to have that file seems _wrong_ to me. The only header file it should need is "regex.h" > Setup.hs build -v3 had a lot of warnings but didn't seem to fail. > However, Setup.hs install -v3 didn't work. You might try to change the cabal file. Currently I think it is "GHC-Options: -Wall -Werror -O2" and remove -Werror "GHC-Options: -Wall -O2" And you can change the cabal "Include-Dirs" to point to wherever it will find "regex.h" > the problem in build seems to occur around "upsweep partially failed or > main not exported"... That means nothing to me. > > [6 of 6] Compiling Text.Regex.Posix ( Text/Regex/Posix.hs, > dist/build/Text/Regex/Posix.o ) > *** Parser: > *** Renamer/typechecker: > > Text/Regex/Posix.hs:57:2: > Warning: The export item `module Text.Regex.Posix.String' exports > nothing > > Text/Regex/Posix.hs:59:2: > Warning: The export item `module Text.Regex.Posix.Sequence' exports > nothing > > Text/Regex/Posix.hs:61:2: > Warning: The export item `module Text.Regex.Posix.ByteString' > exports nothing > > Text/Regex/Posix.hs:63:2: > Warning: The export item `module Text.Regex.Posix.ByteString.Lazy' > exports nothing Those warning are slightly bogus. Including the module should export the instances. > *** Deleting temp files: > Deleting: /tmp/ghc9618_0/ghc9618_0.s > Warning: deleting non-existent /tmp/ghc9618_0/ghc9618_0.s > Upsweep partially successful. > *** Deleting temp files: > Deleting: > link(batch): upsweep (partially) failed OR > Main.main not exported; not linking. > *** Deleting temp files: > Deleting: > *** Deleting temp dirs: > Deleting: /tmp/ghc9618_0 > > complete output (along with patch) is attached. > > I'd appreciate any advice. > > best, thomas. > > --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/0af48def/attachment-0001.htm From ok at cs.otago.ac.nz Thu Aug 30 19:08:29 2007 From: ok at cs.otago.ac.nz (ok) Date: Thu Aug 30 18:59:21 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <1188491881.6674.97.camel@nmd9999> References: <1188491881.6674.97.camel@nmd9999> Message-ID: <9FCAEE1A-38DE-4000-9118-73E25824DB8E@cs.otago.ac.nz> What is so bad about f x = g x'' where x'' = x' + transform x' = x * scale (if you really hate inventing temporary names, that is). From tretriluxana.s at gmail.com Thu Aug 30 19:18:18 2007 From: tretriluxana.s at gmail.com (Sukit Tretriluxana) Date: Thu Aug 30 19:09:04 2007 Subject: [Haskell-cafe] darcs behind firewall In-Reply-To: References: <8252533f0708301254m167fcccfn7a71208e3d9beb8b@mail.gmail.com> Message-ID: <8252533f0708301618r4826f3dbh7bf9b09ef7cbc4ba@mail.gmail.com> Thank you so much. That works nicely!! Ed On 8/30/07, Thomas Hartman wrote: > > > If you are on linux (I'm on ubuntu) you should be able to set > > export http_proxy=http://proxyserver.com:1234 > export https_proxy=http://proxyserver.com:123 > > vars, per what your sysadmin says. In my case, these are set to the same > var that permits me to use firefox via the proxy, in firefox -> edit-> > preferences -> network tab -> connection settings, http proxy. > > and darcs should "just work" > > thomas. > > > > > *"Sukit Tretriluxana" * > Sent by: haskell-cafe-bounces@haskell.org > > 08/30/2007 03:54 PM > To > haskell-cafe@haskell.org cc > > Subject > [Haskell-cafe] darcs behind firewall > > > > > > > Hi all, > > Does anyone know how to specify proxy server and port for darcs to use > when it connects to servers? I am behind firewall most of the time and all > requests have to go through a proxy. > > Thanks, > Ed_______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > --- > > This e-mail may contain confidential and/or privileged information. If you > > are not the intended recipient (or have received this e-mail in error) > please notify the sender immediately and destroy this e-mail. Any > unauthorized copying, disclosure or distribution of the material in this > e-mail is strictly forbidden. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/98d2807a/attachment.htm From ryani.spam at gmail.com Thu Aug 30 19:57:58 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Thu Aug 30 19:48:43 2007 Subject: [Haskell-cafe] Newbie question: Why gfoldl has this strange type? In-Reply-To: <21ba18fc0708301203m3ffa1af8ud0c3b00851bdc4d5@mail.gmail.com> References: <21ba18fc0708301203m3ffa1af8ud0c3b00851bdc4d5@mail.gmail.com> Message-ID: <2f9b2d30708301657l96f7314y84d76c628ca776c7@mail.gmail.com> Just so nobody else has to look it up: Data.Generics.Basics.gfoldl :: Data a => (c (a -> b) -> a -> c b) -> (g -> c g) -> a -> c a -- ryan On 8/30/07, Rodrigo Geraldo wrote: > > Hi! > > I am a novice in Haskell, and particularly I have interested in generic > programming. This interest motivated me to read paper Scrap your > boilerplate: A practical design pattern for generic programming, but I > didn't understand the type of the function gfoldl, that was present in class > Term (Data). Somebody could help me to understand the type of this function? > > Thanks... > > Rodrigo > > _______________________________________________ > 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/haskell-cafe/attachments/20070830/32f05b8c/attachment.htm From ryani.spam at gmail.com Thu Aug 30 20:00:32 2007 From: ryani.spam at gmail.com (Ryan Ingram) Date: Thu Aug 30 19:51:17 2007 Subject: [Haskell-cafe] Newbie question: Why gfoldl has this strange type? In-Reply-To: <2f9b2d30708301657l96f7314y84d76c628ca776c7@mail.gmail.com> References: <21ba18fc0708301203m3ffa1af8ud0c3b00851bdc4d5@mail.gmail.com> <2f9b2d30708301657l96f7314y84d76c628ca776c7@mail.gmail.com> Message-ID: <2f9b2d30708301700i49a05521n723737029824de06@mail.gmail.com> Actually, it's a higher rank type and that doesn't show up on hoogle's main page. gfoldl :: (forall a b . Data a => c (a -> b) -> a -> c b) -> (forall g . g -> c g) -> a -> c a -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070830/751e25ed/attachment.htm From wnoise at ofb.net Thu Aug 30 20:23:42 2007 From: wnoise at ofb.net (Aaron Denney) Date: Thu Aug 30 20:14:44 2007 Subject: [Haskell-cafe] Re: interaction between OS processes References: <20070830101428.GI16235@laptop.nowhere.net> Message-ID: On 2007-08-30, Andrea Rossato wrote: > Hi, > > there's something I don't get about interaction among OS processes and > Haskell handles/channels. This looks like a buffering problem. You might be able to make it work by explicitly setting "line buffering" with hSetBuffering -- Aaron Denney -><- From hughperkins at gmail.com Thu Aug 30 22:18:46 2007 From: hughperkins at gmail.com (Hugh Perkins) Date: Thu Aug 30 22:09:32 2007 Subject: [Haskell-cafe] Haskell on the Playstation 3? :-) In-Reply-To: <625b74080708300904w6d849d4frb9726cc52e94e3a8@mail.gmail.com> References: <002901c7e765$4b076f00$e1164d00$@be> <1188445342.5429.13.camel@derek-laptop> <837db430708292053i4d853c94u78383706a108e3d5@mail.gmail.com> <625b74080708292203t726bf8dfn63ffeb6ff09d6a7@mail.gmail.com> <837db430708300001q49006e8ejc88fde757e826b7c@mail.gmail.com> <1085382914.20070830111547@gmail.com> <837db430708300346j3e5f3042v6814f074984df4cd@mail.gmail.com> <56604449.20070830160133@gmail.com> <837db430708300802l4822000ibc49aa4c229d567c@mail.gmail.com> <625b74080708300904w6d849d4frb9726cc52e94e3a8@mail.gmail.com> Message-ID: <837db430708301918y3e9f5aa7hcac9d250ebbfc98c@mail.gmail.com> On 8/31/07, Dan Piponi wrote: > Right. But the functions and data that we are trying to map and fold > could be anything, so we are required to have the full functionality > of Haskell running on the GPU - unless the compiler can smartly figure > out what should run on the GPU and what shouldn't. All in all, this > could be a fairly ambitious project. Well, yes, I didnt say it would be easy ;-) It could be useful to make a ballpark estimate of what kind of performance we'd get running Haskell on a GPU, compared to running on a CPU. Any ideas on how to do this? By the way, is there some reason we couldnt give the entire haskell program to every thread, and simply pass in something roughly equivalent to the program counter in with the data? From mailing_list at istitutocolli.org Fri Aug 31 05:31:38 2007 From: mailing_list at istitutocolli.org (Andrea Rossato) Date: Fri Aug 31 05:23:35 2007 Subject: [Haskell-cafe] Re: interaction between OS processes In-Reply-To: References: <20070830101428.GI16235@laptop.nowhere.net> Message-ID: <20070831093138.GN16235@laptop.nowhere.net> On Fri, Aug 31, 2007 at 12:23:42AM +0000, Aaron Denney wrote: > On 2007-08-30, Andrea Rossato wrote: > > Hi, > > > > there's something I don't get about interaction among OS processes and > > Haskell handles/channels. > > This looks like a buffering problem. You might be able to make it work by > explicitly setting "line buffering" with hSetBuffering Thanks for your kind attention, but I don't think it's a matter of buffering (I indeed tried playing with hSetBuffering with no results). As I said I'm not even sure if what I intend to do can actually be done...;-) Basically I'd like to write the equivalent of "expect", which talks to interactive programs (with the difference the mine is supposed to talk to a program I wrote, so I don't need to embed a domain specific language in it). Since I don't know all this handle/channel/process interaction stuff I'm leaning towards some other kind of server/client type of interaction, probably with sockets...:-( Thanks again. Andrea From vikrant.patil at gmail.com Fri Aug 31 11:02:15 2007 From: vikrant.patil at gmail.com (Vikrant) Date: Fri Aug 31 10:53:02 2007 Subject: [Haskell-cafe] gtk library installation from ubuntu repository Message-ID: Hi, I am using ubuntu 7.04. If I try to install libghc6-gtk-dev package using apt-get (or aptitude) my installation hangs at following stage building GHCi library /usr/lib/haskell-packages/ghc6/lib/gtk- 0.9.10.5/HSgtk.o... it doesn;t move later and machine just slogs! Then I have no other way than killing the process which in turn does not allow me install anything later. In last three days I have installed ubuntu with haskell on three different machines and it seems I have always got this problem whenever I tried to install libghc6-soegtk-dev. does anybody know that the package @ ubuntu repository is faulty or something wrong here? any fix to this problem! (probably I should put this on ubuntu users list... but putting mail here because if it is problem with libghc6-soegtk-dev, then somebody from you must have experienced it!) Thanks N Regards, VIkrant -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/a41d65bd/attachment-0001.htm From duncan.coutts at worc.ox.ac.uk Fri Aug 31 11:43:00 2007 From: duncan.coutts at worc.ox.ac.uk (Duncan Coutts) Date: Fri Aug 31 11:31:43 2007 Subject: [Haskell-cafe] gtk library installation from ubuntu repository In-Reply-To: References: Message-ID: <1188574980.10322.134.camel@localhost> On Fri, 2007-08-31 at 20:32 +0530, Vikrant wrote: > Hi, > I am using ubuntu 7.04. If I try to install libghc6-gtk-dev package > using apt-get (or aptitude) my installation hangs at following stage > > building GHCi > library /usr/lib/haskell-packages/ghc6/lib/gtk-0.9.10.5/HSgtk.o... It's a packaging bug that was fixed in the 0.9.11 debian package. So try and use the 0.9.11 version of the package: http://packages.debian.org/unstable/libdevel/libghc6-gtk-dev You may also like to pester some ubuntu maintainer person to get the ubuntu package up to at least the latest debian version. (I'm also hoping debian will get the Gtk2Hs 0.9.12 package that's been out for a little while now) Duncan From johan.gronqvist at gmail.com Fri Aug 31 11:50:42 2007 From: johan.gronqvist at gmail.com (=?UTF-8?B?Sm9oYW4gR3LDtm5xdmlzdA==?=) Date: Fri Aug 31 11:41:58 2007 Subject: [Haskell-cafe] Re: let and fixed point operator In-Reply-To: References: <46D6FB5C.7090103@btinternet.com> <625b74080708301041g76b2664dp59eec01057d16f00@mail.gmail.com> <46D73311.1070006@btinternet.com> <625b74080708301438ra50b898pac6c875c797f866a@mail.gmail.com> Message-ID: jerzy.karczmarczuk@info.unicaen.fr skrev: > Anyway, I believe strongly that ALL people who have problems with the > Haskell protocole, and they are numerous, I teach a good sample of them, > should be encouraged to learn Prolog. IN DEPTH, Do you have a recommendation on how to do this? (e.g., books, web-pages, (available) lecture notes, problem sets) / johan From paul.hudak at yale.edu Fri Aug 31 12:00:41 2007 From: paul.hudak at yale.edu (Paul Hudak) Date: Fri Aug 31 11:51:28 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <9FCAEE1A-38DE-4000-9118-73E25824DB8E@cs.otago.ac.nz> References: <1188491881.6674.97.camel@nmd9999> <9FCAEE1A-38DE-4000-9118-73E25824DB8E@cs.otago.ac.nz> Message-ID: <46D83B29.7080800@yale.edu> ok wrote: > What is so bad about > > f x = g x'' > where x'' = x' + transform > x' = x * scale > > (if you really hate inventing temporary names, that is). There's nothing at all wrong with this, assuming it's what you meant to type :-), and it might even correspond perfectly to the mathematical notation used in some textbook. But I would argue that this example is pretty simple, and that if there were a lot of xs and x's and x''s then the chance of making a typing mistake is greater, I believe, than if you had used x, xscaled, and xtransformed. (On the other hand this is all pretty subjective... :-) -Paul From tretriluxana.s at gmail.com Fri Aug 31 12:19:53 2007 From: tretriluxana.s at gmail.com (Sukit Tretriluxana) Date: Fri Aug 31 12:10:38 2007 Subject: [Haskell-cafe] GHC 6.6.1 binary package for Ubuntu available? Message-ID: <8252533f0708310919sc72e8f4ia7c752925b8d5999@mail.gmail.com> Hi, I am wondering if there is the binary package for GHC 6.6.1 for Ubuntu. I searched in the package manager and I only see the version 6.6. Thanks, Ed -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/7740aa88/attachment.htm From thomas.hartman at db.com Fri Aug 31 12:39:37 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 31 12:30:19 2007 Subject: [Haskell-cafe] GHC 6.6.1 binary package for Ubuntu available? In-Reply-To: <8252533f0708310919sc72e8f4ia7c752925b8d5999@mail.gmail.com> Message-ID: you may find this helpful. "Sukit Tretriluxana" Sent by: haskell-cafe-bounces@haskell.org 08/31/2007 12:19 PM To haskell-cafe@haskell.org cc Subject [Haskell-cafe] GHC 6.6.1 binary package for Ubuntu available? Hi, I am wondering if there is the binary package for GHC 6.6.1 for Ubuntu. I searched in the package manager and I only see the version 6.6. Thanks, Ed_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/f83ca5b8/attachment.htm From thomas.hartman at db.com Fri Aug 31 12:40:08 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 31 12:30:49 2007 Subject: [Haskell-cafe] GHC 6.6.1 binary package for Ubuntu available? In-Reply-To: <8252533f0708310919sc72e8f4ia7c752925b8d5999@mail.gmail.com> Message-ID: you may find this helpful. (with link) http://www.haskell.org/pipermail/haskell-cafe/2007-April/024137.html "Sukit Tretriluxana" Sent by: haskell-cafe-bounces@haskell.org 08/31/2007 12:19 PM To haskell-cafe@haskell.org cc Subject [Haskell-cafe] GHC 6.6.1 binary package for Ubuntu available? Hi, I am wondering if there is the binary package for GHC 6.6.1 for Ubuntu. I searched in the package manager and I only see the version 6.6. Thanks, Ed_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/c3ac5e54/attachment.htm From aeyakovenko at gmail.com Fri Aug 31 13:42:32 2007 From: aeyakovenko at gmail.com (Anatoly Yakovenko) Date: Fri Aug 31 13:33:16 2007 Subject: [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from source on feisty Message-ID: i have ghc6_6.6.1-2ubuntu2_i386.deb and ghc6-prof_6.6.1-2ubuntu2_i386.deb installed, but i cant seem to get mtl to install, can someone tell me what this output means? i just switched to a debian based system from gentoo, so i dont grok dpkg yet: aeyakovenko@snowcrash:~$ sudo dpkg -i libghc6-mtl-dev_1.0.1-2_i386.deb (Reading database ... 129709 files and directories currently installed.) Preparing to replace libghc6-mtl-dev 1.0-3 (using libghc6-mtl-dev_1.0.1-2_i386.deb) ... ghc-pkg: cannot find package mtl-1.0 dpkg: warning - old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... ghc-pkg: cannot find package mtl-1.0 dpkg: error processing libghc6-mtl-dev_1.0.1-2_i386.deb (--install): subprocess new pre-removal script returned error exit status 1 Reading package info from stdin ... done. ghc-pkg: dependency base-2.0 doesn't exist (use --force to override) dpkg: error while cleaning up: subprocess post-installation script returned error exit status 1 Errors were encountered while processing: libghc6-mtl-dev_1.0.1-2_i386.deb From thomas.hartman at db.com Fri Aug 31 13:51:39 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 31 13:42:24 2007 Subject: [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from source on feisty In-Reply-To: Message-ID: you may want to generate the .deb rather than take the deb that was packaged for gutsy. http://www.haskell.org/pipermail/haskell-cafe/2007-April/024137.html pupeno's guide to do this: http://pupeno.com/2006/12/17/unstable-packages-on-ubuntu/ "Anatoly Yakovenko" Sent by: haskell-cafe-bounces@haskell.org 08/31/2007 01:42 PM To haskell-cafe@haskell.org cc Subject [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from source on feisty i have ghc6_6.6.1-2ubuntu2_i386.deb and ghc6-prof_6.6.1-2ubuntu2_i386.deb installed, but i cant seem to get mtl to install, can someone tell me what this output means? i just switched to a debian based system from gentoo, so i dont grok dpkg yet: aeyakovenko@snowcrash:~$ sudo dpkg -i libghc6-mtl-dev_1.0.1-2_i386.deb (Reading database ... 129709 files and directories currently installed.) Preparing to replace libghc6-mtl-dev 1.0-3 (using libghc6-mtl-dev_1.0.1-2_i386.deb) ... ghc-pkg: cannot find package mtl-1.0 dpkg: warning - old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... ghc-pkg: cannot find package mtl-1.0 dpkg: error processing libghc6-mtl-dev_1.0.1-2_i386.deb (--install): subprocess new pre-removal script returned error exit status 1 Reading package info from stdin ... done. ghc-pkg: dependency base-2.0 doesn't exist (use --force to override) dpkg: error while cleaning up: subprocess post-installation script returned error exit status 1 Errors were encountered while processing: libghc6-mtl-dev_1.0.1-2_i386.deb _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/2047ac3e/attachment-0001.htm From aeyakovenko at gmail.com Fri Aug 31 13:56:21 2007 From: aeyakovenko at gmail.com (Anatoly Yakovenko) Date: Fri Aug 31 13:47:04 2007 Subject: [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from source on feisty In-Reply-To: References: Message-ID: yea, i built the deb from gutsy's deb-src repository using apt-get source --build. i am trying to figure out why that deb that i build doesn't work On 8/31/07, Thomas Hartman wrote: > > > you may want to generate the .deb rather than take the deb that was > packaged for gutsy. > > http://www.haskell.org/pipermail/haskell-cafe/2007-April/024137.html > > pupeno's guide to do this: > > http://pupeno.com/2006/12/17/unstable-packages-on-ubuntu/ > > > > > *"Anatoly Yakovenko" * > Sent by: haskell-cafe-bounces@haskell.org > > 08/31/2007 01:42 PM > To > haskell-cafe@haskell.org cc > Subject > [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from > source on feisty > > > > > i have ghc6_6.6.1-2ubuntu2_i386.deb and > ghc6-prof_6.6.1-2ubuntu2_i386.deb installed, but i cant seem to get > mtl to install, can someone tell me what this output means? i just > switched to a debian based system from gentoo, so i dont grok dpkg > yet: > > aeyakovenko@snowcrash:~$ sudo dpkg -i libghc6-mtl-dev_1.0.1-2_i386.deb > (Reading database ... 129709 files and directories currently installed.) > Preparing to replace libghc6-mtl-dev 1.0-3 (using > libghc6-mtl-dev_1.0.1-2_i386.deb) ... > ghc-pkg: cannot find package mtl-1.0 > dpkg: warning - old pre-removal script returned error exit status 1 > dpkg - trying script from the new package instead ... > ghc-pkg: cannot find package mtl-1.0 > dpkg: error processing libghc6-mtl-dev_1.0.1-2_i386.deb (--install): > subprocess new pre-removal script returned error exit status 1 > Reading package info from stdin ... done. > ghc-pkg: dependency base-2.0 doesn't exist (use --force to override) > dpkg: error while cleaning up: > subprocess post-installation script returned error exit status 1 > Errors were encountered while processing: > libghc6-mtl-dev_1.0.1-2_i386.deb > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > --- > > This e-mail may contain confidential and/or privileged information. If you > > are not the intended recipient (or have received this e-mail in error) > please notify the sender immediately and destroy this e-mail. Any > unauthorized copying, disclosure or distribution of the material in this > e-mail is strictly forbidden. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/b4be2460/attachment.htm From thomas.hartman at db.com Fri Aug 31 14:24:18 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 31 14:15:01 2007 Subject: [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from source on feisty In-Reply-To: Message-ID: did you have a look at the pupeno blog link? He suggests using fakeroot apt-get source build. Not sure why the fakeroot, but perhaps it makes a difference. thomas. "Anatoly Yakovenko" 08/31/2007 01:56 PM To Thomas Hartman/ext/dbcom@DBAmericas cc haskell-cafe@haskell.org Subject Re: [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from source on feisty yea, i built the deb from gutsy's deb-src repository using apt-get source --build. i am trying to figure out why that deb that i build doesn't work On 8/31/07, Thomas Hartman wrote: you may want to generate the .deb rather than take the deb that was packaged for gutsy. http://www.haskell.org/pipermail/haskell-cafe/2007-April/024137.html pupeno's guide to do this: http://pupeno.com/2006/12/17/unstable-packages-on-ubuntu/ "Anatoly Yakovenko" Sent by: haskell-cafe-bounces@haskell.org 08/31/2007 01:42 PM To haskell-cafe@haskell.org cc Subject [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from source on feisty i have ghc6_6.6.1-2ubuntu2_i386.deb and ghc6-prof_6.6.1-2ubuntu2_i386.deb installed, but i cant seem to get mtl to install, can someone tell me what this output means? i just switched to a debian based system from gentoo, so i dont grok dpkg yet: aeyakovenko@snowcrash:~$ sudo dpkg -i libghc6-mtl-dev_1.0.1-2_i386.deb (Reading database ... 129709 files and directories currently installed.) Preparing to replace libghc6-mtl-dev 1.0-3 (using libghc6-mtl-dev_1.0.1-2_i386.deb) ... ghc-pkg: cannot find package mtl-1.0 dpkg: warning - old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... ghc-pkg: cannot find package mtl-1.0 dpkg: error processing libghc6-mtl-dev_1.0.1-2_i386.deb (--install): subprocess new pre-removal script returned error exit status 1 Reading package info from stdin ... done. ghc-pkg: dependency base-2.0 doesn't exist (use --force to override) dpkg: error while cleaning up: subprocess post-installation script returned error exit status 1 Errors were encountered while processing: libghc6-mtl-dev_1.0.1-2_i386.deb _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. --- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/38495929/attachment.htm From aeyakovenko at gmail.com Fri Aug 31 14:27:36 2007 From: aeyakovenko at gmail.com (Anatoly Yakovenko) Date: Fri Aug 31 14:18:19 2007 Subject: [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from source on feisty In-Reply-To: References: Message-ID: that makes no difference, it just builds the package without actually switching to root, otherwise you are doing unnecessary work with extra privileges. On 8/31/07, Thomas Hartman wrote: > > > did you have a look at the pupeno blog link? He suggests using fakeroot > apt-get source build. > > Not sure why the fakeroot, but perhaps it makes a difference. > > thomas. > > > > *"Anatoly Yakovenko" * > > 08/31/2007 01:56 PM > To > Thomas Hartman/ext/dbcom@DBAmericas cc > haskell-cafe@haskell.org Subject > Re: [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from source > on feisty > > > > > yea, i built the deb from gutsy's deb-src repository using apt-get source > --build. i am trying to figure out why that deb that i build doesn't work > > On 8/31/07, *Thomas Hartman* <*thomas.hartman@db.com*> > wrote: > > you may want to generate the .deb rather than take the deb that was > packaged for gutsy. > * > **http://www.haskell.org/pipermail/haskell-cafe/2007-April/024137.html * > > pupeno's guide to do this: > * > **http://pupeno.com/2006/12/17/unstable-packages-on-ubuntu/ * > > > > *"Anatoly Yakovenko" <**aeyakovenko@gmail.com* *> > * > Sent by: *haskell-cafe-bounces@haskell.org* > > 08/31/2007 01:42 PM > > To > *haskell-cafe@haskell.org* cc > Subject > [Haskell-cafe] trying to install gutsy's libghc6-mtl-dev from > source on feisty > > > > > > > i have ghc6_6.6.1-2ubuntu2_i386.deb and > ghc6-prof_6.6.1-2ubuntu2_i386.deb installed, but i cant seem to get > mtl to install, can someone tell me what this output means? i just > switched to a debian based system from gentoo, so i dont grok dpkg > yet: > > aeyakovenko@snowcrash:~$ sudo dpkg -i libghc6-mtl-dev_1.0.1-2_i386.deb > (Reading database ... 129709 files and directories currently installed.) > Preparing to replace libghc6-mtl-dev 1.0-3 (using > libghc6-mtl-dev_1.0.1-2_i386.deb) ... > ghc-pkg: cannot find package mtl-1.0 > dpkg: warning - old pre-removal script returned error exit status 1 > dpkg - trying script from the new package instead ... > ghc-pkg: cannot find package mtl-1.0 > dpkg: error processing libghc6-mtl-dev_1.0.1-2_i386.deb (--install): > subprocess new pre-removal script returned error exit status 1 > Reading package info from stdin ... done. > ghc-pkg: dependency base-2.0 doesn't exist (use --force to override) > dpkg: error while cleaning up: > subprocess post-installation script returned error exit status 1 > Errors were encountered while processing: > libghc6-mtl-dev_1.0.1-2_i386.deb > _______________________________________________ > Haskell-Cafe mailing list* > **Haskell-Cafe@haskell.org* * > **http://www.haskell.org/mailman/listinfo/haskell-cafe* > > > --- > > This e-mail may contain confidential and/or privileged information. If you > > are not the intended recipient (or have received this e-mail in error) > please notify the sender immediately and destroy this e-mail. Any > unauthorized copying, disclosure or distribution of the material in this > e-mail is strictly forbidden. > > > --- > > This e-mail may contain confidential and/or privileged information. If you > > are not the intended recipient (or have received this e-mail in error) > please notify the sender immediately and destroy this e-mail. Any > unauthorized copying, disclosure or distribution of the material in this > e-mail is strictly forbidden. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/0201bf3d/attachment-0001.htm From andrewcoppin at btinternet.com Fri Aug 31 14:45:25 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 31 14:34:57 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: <46D6FB5C.7090103@btinternet.com> <625b74080708301041g76b2664dp59eec01057d16f00@mail.gmail.com> <46D73311.1070006@btinternet.com> <625b74080708301438ra50b898pac6c875c797f866a@mail.gmail.com> Message-ID: <46D861C5.2060702@btinternet.com> jerzy.karczmarczuk@info.unicaen.fr wrote: > Anyway, I believe strongly that ALL people who have problems with the > Haskell protocole, and they are numerous, I teach a good sample of them, > should be encouraged to learn Prolog. IN DEPTH, and I mean it, Andrew > Coppin and Peter Hercek ! > In Prolog A=B is the unification, which is a bit more than equality, and > something much more aggressive than an assignment. When you REALLY > understand unification, it will be easier to see the lazy instantiation > of the Haskell assignment, and, additionally, it becomes much more easy > to understand the automatic inference of types, which sooner or later > must be harnessed by all Haskell programmers... I did once try to learn Prolog. And failed. Miserably. I just couldn't bend my head around how the Prolog interpreter manages to make seemingly "impossible" leaps of deduction. (It's a *machine*! How can it deduce arbitrarily complex conclusions from any arbitrary set of axioms? That requires *intelligence*!) And yet, in other, seemingly identical cases, it utterly fails to deduce patently *obvious* results... really weird! And then I read a book. A golden book. (No, seriously. The cover is gold-coloured.) It was called "The Fun of Programming". And it demonstrates how to write a Haskell program that performs exactly the same "impossible" feats. And now, finally, it makes sense. (I still have no idea what the hell all that business with the "cut" operator is though...) From igloo at earth.li Fri Aug 31 14:45:30 2007 From: igloo at earth.li (Ian Lynagh) Date: Fri Aug 31 14:36:15 2007 Subject: [Haskell-cafe] Re: trouble compiling regex posix head (I think >0.92) on ghc 6.7 In-Reply-To: References: <46D6F191.8030509@list.mightyreason.com> Message-ID: <20070831184530.GA32143@matrix.chaos.earth.li> On Thu, Aug 30, 2007 at 07:04:21PM -0400, Thomas Hartman wrote: > > I had no idea what HsRegexPosixConfig was, and I have no such file at all. I believe autoreconf will make HsRegexPosixConfig.h.in, and configure will then make HsRegexPosixConfig.h. > > Text/Regex/Posix.hs:57:2: > > Warning: The export item `module Text.Regex.Posix.String' exports > > nothing > > Those warning are slightly bogus. Including the module should export the > instances. You don't need to explicitly export instances; they are exported whether you want them to be or not. Thanks Ian From andrewcoppin at btinternet.com Fri Aug 31 14:47:06 2007 From: andrewcoppin at btinternet.com (Andrew Coppin) Date: Fri Aug 31 14:36:38 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <46D83B29.7080800@yale.edu> References: <1188491881.6674.97.camel@nmd9999> <9FCAEE1A-38DE-4000-9118-73E25824DB8E@cs.otago.ac.nz> <46D83B29.7080800@yale.edu> Message-ID: <46D8622A.30103@btinternet.com> Paul Hudak wrote: > ok wrote: >> What is so bad about >> >> f x = g x'' >> where x'' = x' + transform >> x' = x * scale >> >> (if you really hate inventing temporary names, that is). > There's nothing at all wrong with this, assuming it's what you meant > to type :-), and it might even correspond perfectly to the > mathematical notation used in some textbook. But I would argue that > this example is pretty simple, and that if there were a lot of xs and > x's and x''s then the chance of making a typing mistake is greater, I > believe, than if you had used x, xscaled, and xtransformed. (On the > other hand this is all pretty subjective... :-) OMG! "Mathematical" and "subjective" in the same sentence! ;-) Personally, I find that if I've got more than 2 of the thing, I number them rather than attach multiple primes... but that's just me. From s.clover at gmail.com Fri Aug 31 16:01:14 2007 From: s.clover at gmail.com (Sterling Clover) Date: Fri Aug 31 15:52:01 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: <46D83B29.7080800@yale.edu> References: <1188491881.6674.97.camel@nmd9999> <9FCAEE1A-38DE-4000-9118-73E25824DB8E@cs.otago.ac.nz> <46D83B29.7080800@yale.edu> Message-ID: On this topic, I'm just now teaching myself Haskell and am running into a whole range of stylistic questions like this. My big bad Java habits tend towards long camelCase function names, which I'm trying to wean myself off. But the variable conventions are the real issue. As far as I can tell, if you're writing type descriptors you just use [a,b,c...]. But what are the other general patterns for metasyntactic variable use? In particular for a function -- n, m, etc or x, y, etc? What about for f' defined in a let block of f? If I use x y at the top level I need to use another set below -- is that where x' y' are more appropriate, or x1, y1? For tuples I tend to pattern match with (a,b), and for lists I tend to use (h:r) for head and rest. Are there other, more universal standards for these sorts of things? Another related question is whether using these short sweet variable names makes sense, or whether I should try to use more descriptive ones. Obviously these are pretty small points of style, but I'm just trying to nail the Haskell idiom as closely as possible. I've already found myself falling into namespace traps though, playing around with math functions & etc. where an adequately descriptive name for one context in maybe a let block steps on something which deserves the name equally well in the global namespace. I try to keep the global namespace pretty clean, but things keep popping up -- I'm thinking maybe another convention would come to the rescue here, like camelCase or hyphen-ated for global and all lowers for local? --S. On 8/31/07, Paul Hudak wrote: > > ok wrote: > > What is so bad about > > > > f x = g x'' > > where x'' = x' + transform > > x' = x * scale > > > > (if you really hate inventing temporary names, that is). > There's nothing at all wrong with this, assuming it's what you meant to > type :-), and it might even correspond perfectly to the mathematical > notation used in some textbook. But I would argue that this example is > pretty simple, and that if there were a lot of xs and x's and x''s then > the chance of making a typing mistake is greater, I believe, than if you > had used x, xscaled, and xtransformed. (On the other hand this is all > pretty subjective... :-) > > -Paul > > _______________________________________________ > 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/haskell-cafe/attachments/20070831/a807c3a8/attachment.htm From allbery at ece.cmu.edu Fri Aug 31 16:16:57 2007 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Fri Aug 31 16:07:40 2007 Subject: [Haskell-cafe] let and fixed point operator In-Reply-To: References: <1188491881.6674.97.camel@nmd9999> <9FCAEE1A-38DE-4000-9118-73E25824DB8E@cs.otago.ac.nz> <46D83B29.7080800@yale.edu> Message-ID: <216A6816-866C-468B-AC19-3F1F7CDC9087@ece.cmu.edu> On Aug 31, 2007, at 16:01 , Sterling Clover wrote: > In particular for a function -- n, m, etc or x, y, etc? What about > for f' defined in a let block of f? If I use x y at the top level I > need to use another set below -- is that where x' y' are more > appropriate, or x1, y1? Usual style is x',y'. For longer names, camelCase is the usual convention but some libraries which basically import everything from C via the FFI use C_style_names. Imported constants/macros which are uppercase with _ tend to be mapped to tHIS_KIND_OF_NAME (see for example the Win32 package). One thing to watch out for is that monads tend to carry their own metaconventions: a generic monad is "m", a reader monad is "r", a state monad is "s", functors are "f". > For tuples I tend to pattern match with (a,b), and for lists I tend > to use (h:r) for head and rest. Are there The common convention for lists is e.g. (x:xs) (the latter is "x-es"). > other, more universal standards for these sorts of things? Another > related question is whether using these short sweet variable names > makes sense, or whether I should try to use more descriptive ones. I generally use something short but descriptive when writing something specific, and single-character generic names when writing something that's generic and/or polymorphic. -- 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 k.kosciuszkiewicz at gmail.com Fri Aug 31 16:24:35 2007 From: k.kosciuszkiewicz at gmail.com (Krzysztof =?utf-8?Q?Ko=C5=9Bciuszkiewicz?=) Date: Fri Aug 31 16:15:19 2007 Subject: [Haskell-cafe] Re: interaction between OS processes In-Reply-To: <20070831093138.GN16235@laptop.nowhere.net> References: <20070830101428.GI16235@laptop.nowhere.net> <20070831093138.GN16235@laptop.nowhere.net> Message-ID: <20070831202435.GC32418@localdomain> On Fri, Aug 31, 2007 at 11:31:38AM +0200, Andrea Rossato wrote: > Thanks for your kind attention, but I don't think it's a matter of > buffering (I indeed tried playing with hSetBuffering with no results). That is because you need to change output buffering on both ends. I don't know about haskell, but stdio says that handles to tty's are line-buffered, stderr is not buffered and all other handles are fully buffered. Of course you can flush the handles instead. > Basically I'd like to write the equivalent of "expect", which talks to > interactive programs (with the difference the mine is supposed to talk > to a program I wrote, so I don't need to embed a domain specific > language in it). AFAIR expect uses pseudo-ttys (ptys) because in general one can't force a program to change it's output buffering mode, so forcing it to talk to a pair of terminals instead of fifos is used as a workaround. Have a look at pty(7). Cheers, -- Krzysztof Ko?ciuszkiewicz Skype: dr.vee, Gadu: 111851, Jabber: kokr@jabberpl.org Mobile IRL: +353851383329, Mobile PL: +48783303040 "Simplicity is the ultimate sophistication" -- Leonardo da Vinci From thomas.hartman at db.com Fri Aug 31 18:13:46 2007 From: thomas.hartman at db.com (Thomas Hartman) Date: Fri Aug 31 18:04:35 2007 Subject: [Haskell-cafe] wanted: HAppS example combining state and io Message-ID: Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: https1-whatsnew Type: application/octet-stream Size: 1933 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/8054e4f1/https1-whatsnew-0001.obj -------------- next part -------------- A non-text attachment was scrubbed... Name: HTTP1.hs Type: application/octet-stream Size: 4794 bytes Desc: not available Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070831/8054e4f1/HTTP1-0001.obj From tanimoto at u.arizona.edu Fri Aug 31 23:09:04 2007 From: tanimoto at u.arizona.edu (Paulo Tanimoto) Date: Fri Aug 31 22:59:46 2007 Subject: [Haskell-cafe] GHC 6.6.1 binary package for Ubuntu available? In-Reply-To: References: <8252533f0708310919sc72e8f4ia7c752925b8d5999@mail.gmail.com> Message-ID: Dear Ed, GHC 6.6.1 is available for the upcoming Ubuntu release (Gutsy). http://packages.ubuntu.com/gutsy/devel/ghc6 I personally like to set up a chroot environment for these things, so here's what I have: $ ghc --version The Glorious Glasgow Haskell Compilation System, version 6.6.1 Paulo On 8/31/07, Thomas Hartman wrote: > > you may find this helpful. (with link) > > http://www.haskell.org/pipermail/haskell-cafe/2007-April/024137.html > > > > > "Sukit Tretriluxana" > Sent by: haskell-cafe-bounces@haskell.org > > 08/31/2007 12:19 PM > > To haskell-cafe@haskell.org > > cc > > > Subject [Haskell-cafe] GHC 6.6.1 binary package for Ubuntu available? > > > > > > > > Hi, > > I am wondering if there is the binary package for GHC 6.6.1 for Ubuntu. I searched in the package manager and I only see the version 6.6. > > Thanks, > Ed_______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > > --- > > This e-mail may contain confidential and/or privileged information. If you > are not the intended recipient (or have received this e-mail in error) > please notify the sender immediately and destroy this e-mail. Any > unauthorized copying, disclosure or distribution of the material in this > e-mail is strictly forbidden. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > >