Re: [Haskell-cafe] X11 package bug: XClientMessageEvent long data
On Wed, Mar 16, 2011 at 12:10:59AM -0400, Dylan Alex Simon wrote: Does anyone know the current maintenance status of the X11 package? I emailed Spencer Janssen a number of months ago and never heard back. So, I'll put this here in case any one else runs into it or can get it to the right place. This is a proposed bug fix for a problem I ran into using xmonad client messages to send remote commands on 64LP architectures (i.e., amd64), wherein the C X11 library and Haskell's disagree about the size of client message arguments. Tue Nov 16 23:41:49 EST 2010 Dylan Simon dy...@dylex.net * change XClientMessageEvent long data The XClientMessageEvent.data.l field is actually a long, not an int, so it must be interpreted as such, even though format is set to 32 in this case. Ostensibly this is an Xlib bug, but it is unlikely to be fixed there. diff -rN -u old-src/Graphics/X11/Xlib/Extras.hsc new-src/Graphics/X11/Xlib/Extras.hsc --- old-src/Graphics/X11/Xlib/Extras.hsc 2011-03-15 22:40:39.687844812 -0400 +++ new-src/Graphics/X11/Xlib/Extras.hsc 2011-03-15 22:40:39.724522814 -0400 @@ -601,7 +601,7 @@ 16 - do a - peekArray 10 datPtr return $ map fromIntegral (a::[Word16]) 32 - do a - peekArray 5 datPtr - return $ map fromIntegral (a::[Word32]) + return $ map fromIntegral (a::[CLong]) _ - error X11.Extras.clientMessage: illegal value return $ ClientMessageEvent { ev_event_type= type_ Sorry, I must have missed your message. Send me a darcs patch and I'll see to applying it. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] X Haskell Bindings
On Sat, Aug 16, 2008 at 04:07:25PM -0500, Antoine Latter wrote: Haskellers, I'm slowly porting XCB (the X C Bindings) to Haskell, and I would like input from any interested parties. The following is a summary of my plan so far. I'm interested in hearing any suggestions or concerns about what a Haskell library for writing X clients should look like. This is not a release announcement, and I can't make any promises about when this will be delivered. Code is available in darcs: -- darcs get http://community.haskell.org/~aslatter/code/xhb Some of the advantages XCB claims over xlib are: + smaller API + latency hiding when communicating with the X server + direct access to the X protocol + improved threading support + easier to extend What I plan for the X Haskell Bindings (XHB) are as follows: + All requests to the server are non-blocking (under most circumstances) + Requests which produce a reply from the server return a token or receipt + The caller may then, at a time of their choosing, query the receipt for the response (or error) from the server. This query is blocking. The API will look something like: -- | Create a window as specified createWindow :: Connection - CreateWindow - IO () -- | Instruct the server that it should begin displaying the named window mapWindow :: Connection - WINDOW - IO () -- | List all of the extensions supported by the server listExtensions :: Connection - IO (Receipt (ListExtensionsReply)) -- | Query a receipt for a response getReply :: Receipt a - IO (Either XError a) Note that the first two requests do not have replies, whereas the third request expects a reply from the server. Since the request to create a window has so many parameters, these parameters are all wrapped up into a CreateWindow data type, which is only ever used by the createWindow function. The mapWindow request only has one parameter, so it does not need it's own MapWindow data type. I think this is a nice idea. This type signature from the X11 library is absolutely unmanageable: createWindow :: Display - Window - Position - Position - Dimension - Dimension - CInt - CInt - WindowClass - Visual - AttributeMask - Ptr SetWindowAttributes - IO Window What I don't have planned out is what to do with the stream of events and errors that come back from the server. If an error is related to an outstanding receipt, it gets dumped there for the caller to examine directly. Other errors go into an error queue. Events go into a similar event queue. How should this queue be exposed in the API? Should the user of the library register an error/event callback? registerErrorCallback :: Connection - (XError - IO ()) - IO () Classic libX11 does this, and it is rather inconvenient to program with. Occasionally it is necessary to handle an error thrown by a specific request, yielding code like this: do h - getHandler c -- save the old handler so we can restore it later setHandler c myHandlingFn performSomeActionsWhichMayFail setHandler c h Not only is this code ugly, it does not work correctly when the connection may be concurrently used by several threads. Or is something like this enough: pollForError :: Connection - IO (Maybe (XError)) waitForError :: Connection - IO XError I think XCB's error system is particularly nice. Requests with no corresponding responses have two variants: unchecked (the default), and checked. Unchecked requests have a void return type, and any errors they generate go in the error queue. Checked requests return a cookie (the same mechanism used for requests with responses) which can be used to collect any errors generated by that response. Each X extension defines its own set of errors and events (potentially). Should all of these be lumped together into one giant sum-type for errors and one for events? Take care, Antoine Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: Advice sought for 6.9 and Arrow/Category
On Tue, Jul 15, 2008 at 05:45:55PM +0200, Conal Elliott wrote: By the way, here's how I'm changing my code to work with the new and old arrow interface. I'd appreciate any suggested improvements. The old code (example): import Control.Arrow [...] instance Arrow (~) = Arrow (Bijection (~)) where Bi ab ba Bi bc cb = Bi (ab bc) (cb ba) [...] The new code: #if __GLASGOW_HASKELL__ = 609 import Control.Category import Prelude hiding ((.), id) #endif import Control.Arrow [...] #if __GLASGOW_HASKELL__ = 609 instance Category (~) = Category (Bijection (~)) where id = Bi id id Bi bc cb . Bi ab ba = Bi (bc . ab) (ba . cb) #endif instance Arrow (~) = Arrow (Bijection (~)) where #if __GLASGOW_HASKELL__ 609 Bi ab ba Bi bc cb = Bi (ab bc) (cb ba) #endif [...] I'm testing for ghc version. Could I somehow test for the base-library version instead? - Conal Yes. Here is a snippet from binary.cabal: flag applicative-in-base library if flag(applicative-in-base) build-depends: base = 2.0 cpp-options: -DAPPLICATIVE_IN_BASE else build-depends: base 2.0 Cheers, Spencer Janssen ___ Glasgow-haskell-users mailing list Glasgow-haskell-users@haskell.org http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
Re: [Haskell-cafe] IMAP and NNTP libraries
On Sun, Jun 22, 2008 at 02:52:33AM -0300, Maurício wrote: Hi, Are there mature libraries for IMAP and NNTP available to Haskell? Thanks, Maurício There is the haskellnet project: http://darcs.haskell.org/SoC/haskellnet/ I'm not sure whether it is mature or maintained. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] test driving cabal install... cabal install and normal install (runghc Setup) don't mix... two package.conf files...
On Thu, May 29, 2008 at 06:11:04PM -0700, Thomas Hartman wrote: After a little drama with zlib, I managed to get cabal-install installed. I then attempted to do cabal install HAppS-Server since this is a module with a lot of dependencies, and in rapid development flux, so perenially painful for me to install. The result is that I managed to install everything up to HAppS-State, which I think is the last dependency, but then seemed to hang indefinitely in the middle of installing HAppS-Server at the end. OK, I thought, then perhaps I can do normal runghc Setup.hs after downloading and unzipping the tar from http://hackage.haskell.org/cgi-bin/hackage-scripts/package/HAppS-Server-0.9.2.1 However, this resulted in error [EMAIL PROTECTED]:~/haskellInstalls/smallInstalls/HAppS-Server-0.9.2.1runghc Setup.hs configure ... Setup.hs: At least the following dependencies are missing: HAppS-Data =0.9.2... Strange, because I had just installed that module via cabal-install, and I could load it in ghci with :m +HappS.Data. 'cabal install' installs packages to your user database by default. However, 'Setup configure' only uses packages from the global database unless the --user flag is passed. I then ran ghc-pkg and got this strange result that my packages were broken into two different files. Is this by design? ghc-pkg list /usr/local/lib/ghc-6.8.2/package.conf: Cabal-1.2.3.0, Cabal-1.3.11, Cabal-1.5.2, DeepArrow-0.2, /home/thartman/.ghc/i386-linux-6.8.2/package.conf: HAppS-Data-0.9.2.1, HAppS-IxSet-0.9.2.1, HAppS-State-0.9.2.1, Yep, this is by design. The first is a global database that will require root access to modify. The second is your user database which you can modify without root access. I am curious if anybody else is able to install HAppS-Server using cabal install, and whether they can shed any light on the other isuses I raised. Thomas. I tried building HAppS-server the other day, and had a similar experience. It seems that HAppS uses some incredibly elaborate TH/typeclass hacks that take gobs of resources to compile -- my box actually ran out of memory attempting to build it. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Rotating backdrop (aka learning Haskell)
On Tue, May 20, 2008 at 09:15:57AM +0100, Yann Golanski wrote: To help me learn Haskell, I decided on a simple (AH!) problem: given a list of images, display a random one as my desktop backdrop. After some time, change the image. Simple? What I actually want to do is a little more specific: Read a list of images (one per line) from a file. Given that a working day is about 8 hours, I want to see all the images during the day. So, the time between changes should be (nbr_of_images) / (8 * 60 * 60) seconds. Of course, if the file changes (I add or remove any number of images) this need to change and be recalculated. Clearly, I want some interaction with a pseudo-random number generator. Because this is a learning exercise, I want to have a pretty GUI for this. Three buttons: Exit (which quits the application), Reset (re-reads the file whether it changed or not) and Next (display the next image). Then I want a counter and a progress bar telling me when the next change will occur. 1- Get a list out of a file: I managed to do that using the following: parseImageFile :: FilePath - IO [String] parseImageFile file = do inpStr - readFile file return $ filter (/=) (breaks (=='\n') inpStr) Nice, simple and I understand what it is doing. 2- Get a random element from a list and remove it: Okay, this I understand less well. I looked at the solutions of problems 23 and 20 in http://www.haskell.org/haskellwiki/99_questions so there is a skeleton there. However, my list is IO [String] Hum, monads. Any pointers as to how to do that? 3- Wait and do something later How, I have no idea how to do that! Help? One way is System.Concurrent.threadDelay, though there might be another way that integrates more nicely with wxHaskell. Hopefully you can find it in their documentation. http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent.html#v%3AthreadDelay 4- I guess that progress bars and updating text will be somewhere in the GUI (I chose wxHaskell)... Again, no idea where. 5- How do you call an external program in Haskell? Either xv or Esetroot will do the job of displaying the image. Is there a Haskell native way to do that? Try the System.Cmd.system function. http://www.haskell.org/ghc/docs/latest/html/libraries/process/System-Cmd.html#v%3Asystem Once this is done and I have commented to the code, I will be happy to put it onto the wiki as a teaching aid. Thanks. -- [EMAIL PROTECTED] -= H+ =- www.kierun.org PGP: 009D 7287 C4A7 FD4F 1680 06E4 F751 7006 9DE2 6318 Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Two-iteration optimisation (was: GHC Predictability)
On Wed, May 14, 2008 at 06:08:28PM +0100, Paul Johnson wrote: We've had a big debate over mean xs = foldl' (+) 0 xs / fromIntegral (length xs) For anyone who didn't follow it, the problem is that mean needs to traverse its argument twice, so the entire list has to be held in memory. So if xs = [1..10] then mean xs uses all your memory, but foldl' (+) 0 xs and length xs by themselves do not. The solution is for the programmer to rewrite mean to accumulate a pair containing the running total and count together, then do the division. This makes me wonder: could there be a compiler optimisation rule for this, collapsing two iterations over a list into one. I've never tried writing GHC rules, but something like: f (foldl' g x) (foldl' h x) = (uncurry f) (foldl' (\i (gt,ht) - (g i gt, h i ht))) The first problem that occurs to me is the number of permutations of fold and map functions. Paul. There are two problems with this rule. The first is that the function is not strict in 'gt' and 'ht' -- this is easily fixed with a little bit of seq. The other problem is that 'f' must be strict in both parameters for this rule to hold. As far as I know, there is no access to strictness information in rule pragmas. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] GHC predictability
On Mon, May 12, 2008 at 08:01:53PM +0100, Andrew Coppin wrote: I offer up the following example: mean xs = sum xs / length xs Now try, say, mean [1.. 1e9], and watch GHC eat several GB of RAM. (!!) I don't see why the performance implications of this program are surprising. Just ask any programmer used to a strict language how much memory [1 .. 1e9] will require. If we now rearrange this to mean = (\(s,n) - s / n) . foldr (\x (s,n) - let s' = s+x; n' = n+1 in s' `seq` n' `seq` (s', n')) (0,0) and run the same example, and watch it run in constant space. This will use linear stack space. You probably meant to use foldl'? Better: mean = uncurry (/) . foldl' f (0, 0) where f (!s, !n) x = (s + x, n + 1) -- or, if you require Haskell '98: f (s, n) x = s `seq` n `seq` (s + x, n + 1) This version is very legible in my opinion. In fact, the algorithm is identical to what I'd write in C. Also, mean [1 .. 1e9] will actually work in Haskell, while in C you'll just run out of memory. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] problem building array package
On Fri, Jan 18, 2008 at 06:19:13PM +, Jim Burton wrote: Building array from cabal with ghc6.6: ~/array-0.1.0.0$ runhaskell Setup.hs configure Configuring array-0.1.0.0... ~/array-0.1.0.0$ runhaskell Setup.hs build Preprocessing library array-0.1.0.0... Building array-0.1.0.0... [ 1 of 10] Compiling Data.Array.Base ( Data/Array/Base.hs, dist/build/Data/Array/Base.o ) Data/Array/Base.hs:391:23: Not in scope: `Arr.numElements' Data/Array/Base.hs:1067:35: Not in scope: `ArrST.numElementsSTArray' Data/Array/Base.hs:1079:51: Not in scope: `ArrST.numElementsSTArray' Any ideas why? Thanks, Jim The array package isn't needed for GHC 6.6, as Data.Array.* is included in the base package. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Poisx select support
On Wed, Jan 16, 2008 at 02:09:31PM -0600, Galchin Vasili wrote: Hi Don, Sorry ..I wasn't clear enough.I am trying to determine from the Haskell FFI doc what datatype to use in order to model C's void *, e.g. for mmap http://www.opengroup.org/onlinepubs/95399/functions/mmap.html Regards, Vasili For C's void *, I'd use Ptr (). Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: wish for more-usable bindist
On Fri, Jan 04, 2008 at 08:24:32PM -0500, Isaac Dupree wrote: the i386 linux ghc bindist still uses readline 4 http://haskell.org/ghc/download_ghc_682.html, which is hard to get: readline 5.0 came out almost three and a half years ago ftp://ftp.cwru.edu/pub/bash/ And I don't want to pollute my Ubuntu system with compatibility RPMs; in fact I intend to install the bindist as my local user so I don't pollute it with extra GHCs either, except I can't. Could there be a bindist with modern readline, or perhaps is it possible to statically link with readline? ~Isaac Here's a little trick I picked up from Stefan O'Rear: sed -e 's/readline.so.4/readline.so.5' --in-place ~/lib/ghc-6.8.2/ghc-6.8.2 Surprisingly, this produces a working GHC. Cheers, Spencer Janssen ___ Glasgow-haskell-users mailing list Glasgow-haskell-users@haskell.org http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
Re: [Haskell-cafe] Concurrency questions
On Mon, Jan 07, 2008 at 09:40:29PM +, Andrew Coppin wrote: Well, I was thinking more of using them for two things. One is for speculative work (i.e., doing work which we might need later - but don't bother unless there's cores going spare). For (pure) speculative tasks, try Control.Parallel.par. Mmm, OK. I'll try that. (I wasn't actually aware that STM is working yet...) STM has been available for quite awhile, as early as GHC 6.4 if memory serves. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: How to use #ifdef WIN32
On Thursday 20 December 2007 18:37:15 Jim Burton wrote: I want to switch code on the OS but this always goes through to the #else (on windows or elsewhere): {-# OPTIONS -cpp #-} #ifdef WIN32 main = putStrLn hello windows #else main = putStrLn hello something else #endif Does this depend on a Makefile setting WIN32, or should there be something predefined? Thanks, If you're using Cabal, something like this should work: if os(win32) cpp-options: -DWIN32 Cheers, Spencer Janssen ___ Glasgow-haskell-users mailing list Glasgow-haskell-users@haskell.org http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
Re: How to use #ifdef WIN32
On Thursday 20 December 2007 22:04:13 Duncan Coutts wrote: On Thu, 2007-12-20 at 21:16 -0600, Spencer Janssen wrote: If you're using Cabal, something like this should work: if os(win32) cpp-options: -DWIN32 To be precise: if os(windows) cpp-options: -DWIN32 See, Cabal is (mostly) Neil I hate mingw Mitchell compliant. :-) Duncan Should example 4 in section 2.1.5 of the Cabal manual be changed, then? Or are win32 and windows equivalent? Spencer Janssen ___ Glasgow-haskell-users mailing list Glasgow-haskell-users@haskell.org http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
Re: [Haskell-cafe] New to Haskell
On Tuesday 18 December 2007 01:31:59 Cristian Baboi wrote: A few days ago, for various reasons, I've started to look at Haskell. At first I was quite impressed, after reading some FAQ, and some tutorials. Evrything was nice and easy ... until I've started writing some code on my own. What I should have been told about upfront: - the syntax for an expression - the syntax for a block - the adhoc syntax rules (how to distinguish among a tuple and a pharanthesized expression and how to find the start and end of a block for example ) - the fact that lambda expressions are not the same thing as algebraic data values - what guarantees are made by the LANGUAGE that an IO action (such as do putStrLn Hello world ) is not performed twice - the lambda expressions can be written (input) but cannot be printed (output) The biggest problem for me, so far, is the last one. Here is some strange example: module Hugs where aa::Int aa=7 cc:: (Int-Int)-(Int-Int-Int)-Int-(Int-Int) cc a op b = \x- case x of { _ | x==aa - x+1 ; _- a x `op` b } f::Int-Int f(1)=1 f(2)=2 f(_)=3 g::Int-Int g(1)=13 g(2)=23 g(_)=33 h::[Int-Int] - Int -Int h [] x = x h [rr] x= let { u=Hugs.f ; v=Hugs.g } in case rr of { u - Hugs.g(x)+aa ; v - Hugs.f(x)+aa ; _ -rr (x) + aa } h (rr:ll) x = h [rr] x + h (ll) x What I don't understand is why I'm forced to use guards like x==aa in cc, when aa is clearly bounded (is 7) and why in function h, the bounded u and v become free variables in the case expression. I don't think anyone has mentioned it yet, so I'll go ahead. Many of the questions you ask are well covered by the Haskell Report: http://haskell.org/onlinereport/ The report is terse, but quite usable as a reference. Moreover, it is The Final Word on all these semantic and syntactic questions. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Looking for largest power of 2 = Integer
On Tuesday 04 December 2007 15:47:19 David Benbennick wrote: On Dec 4, 2007 11:51 AM, Don Stewart [EMAIL PROTECTED] wrote: Awesome. We can use this in Data.Bits, if you've got some QuickChecks for it. Hear hear. But is there any way to just make the compiler use fastTestBit in place of testBit :: (Bits a) = a - Int - Bool when a = Integer? (That is, without having to introduce a new function to the public interface of Data.Bits.) Some kind of SPECIALIZE pragma, perhaps? I've attached a program with two QuickCheck properties. Unfortunately they fail on negative Integers. I can't figure out why. No fancy specialization is needed. Since testBit is part of the Bits class, simply 'testBit = fastTestBit' in the instance for Integer. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Re: Waiting for thread to finish
On Tuesday 27 November 2007 18:46:00 Brad Clow wrote: I was just watching top while executing this and noticed that it really only used one core (I am using GHC 6.8.1 on a MacBook). Does anyone know why? Did you compile with -threaded, and run with +RTS -N2? Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Hosting of Haskell project
On Wednesday 10 October 2007 11:05:28 Magnus Therning wrote: I recently had reason to do some encoding-related coding and noticed that Haskell was somewhat lacking (I could only find code for base64, on the other hand there are two implementations of it :-). I've almost reached a state where I wouldn't be ashamed of sharing the code so I looked into my options of free hosting. It seems I only have one option for publishing the code: - Request a project on code.haskell.org. I could only find one option for a homepage for the project: - Create a page on the Wiki. You could perhaps use code.haskell.org for this? I'm not sure if that's kosher. There seems to be no option when it comes to tracking bugs. :-( Xmonad uses Google Code's bug tracker, which has worked quite nicely. I could also not locate any option for publishing haddock pages. :-( Haddock documentation is automatically generated for released packages on hackage.haskell.org. Have I missed anything? /M Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Re: bizarre memory usage with data.binary
On Tuesday 02 October 2007 19:51:47 Anatoly Yakovenko wrote: If its specifically the list instance, where we currently trade laziness for efficiency of encoding (which may or may not be the right thing), I'd suggest a fully lazy encoding instance? Its not really a list, its more of a tree that has shared nodes, so something like this: A / \ B C \ / D / \ EF I suspect that maybe after encode/decode i end up with something like A / \ B C / \ D D / \/ \ EFE F That is correct, binary doesn't attempt to share substructures. If you'd like to do this, you'll need to do it by hand. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] How can I pass IOUArrays to FFI functions?
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 ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Bathroom reading
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 ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D )
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 ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Haskell vs GC'd imperative languages, threading, parallelizeability (is that a word? :-D )
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...) ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Order of evaluation
On Thursday 26 July 2007 11:02:00 Jon Harrop wrote: On Thursday 26 July 2007 17:03:31 C.M.Brown wrote: Hi Jon, On Thu, 26 Jul 2007, Jon Harrop wrote: If you have a boolean-or expression: a || b will a be evaluated before b in Haskell as it is in other languages? Yes, I believe it is defined thus: True || _= True _|| True = True _|| _= False Therefore it is strict in its first argument (it needs to evaluate its first argument in order to know which pattern match to take). Wonderful, thanks guys. The reason I ask is that I'm just looking over the Haskell ray tracer and it occurred to me that evaluation order makes an asymptotic difference to performance. The reason is simply that one order considers near spheres first and culls far spheres whereas the opposite order ends up traversing all spheres. Do foldl and foldr reduce from the first and last elements of a list, respectively? Well, beginning and end are somewhat fuzzy concepts when laziness is involved. Consider this example: foldr (||) False [a, b, c] === (a || (b || (c || False))) foldl (||) False [a, b, c] === (((False || a) || b) || c) Note that the least-nested application with foldr is (a || ...) -- this means that foldr can potentially yield some result after looking at the first element of the input. This is especially useful with (||), because it only uses the second argument when the first is False. In contrast, foldl's least-nested application is (... || c) -- foldl must traverse to the end of the input before giving an answer. As it is traveling to the end, it will also build up the expression seen in the example. On the surface, it seems we'll require O(n) heap to build this thunk. However, if the compiler is sufficiently smart, bits of this expression will be evaluated as you go along, requiring only O(1) memory, rather than O(n). We can also force this incremental evaluation with Data.List.foldl'. Now, imagine folding (+) instead of (||). (+) evaluates both arguments before computing a result. In that case, foldr will take O(n) stack. With a sufficiently smart compiler, foldl will only use O(1) memory. To summarize: Use foldr when the operator is lazy (||, , ++, :). Use foldl when the operator is strict (*, +). Use foldl' when you don't trust the compiler to optimize foldl. Specifically, I'm wondering if this has an effect on the foldr optimization that Spencer proposed (that certainly gives a ~50% speedup here) that was attributed to avoiding lazy accumulators, IIRC. Did I propose something? I recall looking at this code before, but I can't remember the details. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Sparse documentation
On Tue, 3 Jul 2007 09:23:02 -1000 (HST) Tim Newsham [EMAIL PROTECTED] wrote: How about STM? It would be nice if I didn't have to scan the paper each time I do something with STM. Isn't that the point of having an API reference? -Brent Tim Newsham http://www.thenewsh.com/~newsham/ What is missing in STM's documentation? TArray, TChan, TMVar have just as much documentation as their non-transactional counterparts. The documentation for TVar and STM is also available, but perhaps more difficult to find. Note that Control.Concurrent.STM.TVar (similarly Control.Monad.STM) does not have any documentation on the page, but each identifier is a link to GHC specific modules that give more documentation. This is a bug in Haddock: it doesn't know how to include documentation from another package. Cheers, Spencer Janssen Documentation: http://www.haskell.org/ghc/docs/latest/html/libraries/stm/Control-Concurrent-STM-TVar.html http://www.haskell.org/ghc/docs/latest/html/libraries/base/GHC-Conc.html#t%3ATVar http://www.haskell.org/ghc/docs/latest/html/libraries/stm/Control-Monad-STM.html http://www.haskell.org/ghc/docs/latest/html/libraries/base/GHC-Conc.html#t%3ASTM etc. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Haskell version of ray tracer code is much slower than the original ML
On Thu, 21 Jun 2007 11:55:04 +0100 Philip Armstrong [EMAIL PROTECTED] wrote: In odd spare moments, I took John Harrops simple ray tracer[1] made a Haskell version: http://www.kantaka.co.uk/cgi-bin/darcsweb.cgi?r=ray darcs get http://www.kantaka.co.uk/darcs/ray It's pretty much a straight translation into idiomatic Haskell (as far as my Haskell is idiomatic anyway). Unfortunately, it's a lot slower than the ML version, despite turning all the optimisation options up as far as they'll go. Profiling suggests that much of the time is spent in the intersection' function, and that the code is creating (and garbage collecting) an awful lot of (-|) vector subtraction thunks. Trying to make intersection' or ray_sphere stricter (with seq) appears to have no effect whatsoever: the output of -ddump-simpl is unchanged (with the arguments all staying lazy). Am I missing anything obvious? I don't want to carry out herculean code rewriting efforts: that wouldn't really be in the spirit of the thing. cheers, Phil [1] http://www.ffconsultancy.com/languages/ray_tracer/comparison.html With a very minor change (attached), your Haskell ray tracer runs faster than the OCaml version on my machine. There's a bug GHC where it does not recognize -fexcess-precision at the command line, but an OPTIONS_GHC pragma does work correctly. This flag brings runtime from about 60s to 20s on my machine (Core Duo 1.83GHz) -- compared to 25s for the OCaml version. Results (each run twice to avoid OS buffering of the executable): % uname -a Linux localhost 2.6.22-rc4 #5 SMP Tue Jun 19 17:29:36 CDT 2007 i686 Genuine Intel(R) CPU T2400 @ 1.83GHz GenuineIntel GNU/Linux % ghc --version The Glorious Glasgow Haskell Compilation System, version 6.6 % ocamlopt -version 3.09.3 % (time ./hsray) | md5sum ./hsray 20.23s user 0.03s system 98% cpu 20.536 total 63a359e5c388f2004726d83d4337f56b - % (time ./hsray) | md5sum ./hsray 19.74s user 0.07s system 99% cpu 19.907 total 63a359e5c388f2004726d83d4337f56b - % (time ./mlray) | md5sum ./mlray 25.55s user 0.00s system 98% cpu 25.831 total 63a359e5c388f2004726d83d4337f56b - % (time ./mlray) | md5sum ./mlray 25.63s user 0.04s system 98% cpu 25.981 total 63a359e5c388f2004726d83d4337f56b - Cheers, Spencer Janssen ray_pragma.dpatch Description: Binary data ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Collections
On Tue, 19 Jun 2007 19:26:20 +0100 Andrew Coppin [EMAIL PROTECTED] wrote: When I was at university, we learned a programming language known as Smalltalk. I was rather good at it. [Ironically, making small talk is one of the things I do worst IRL! But anyway, back to the topic...] In Smalltalk, there is a wide selection of collection types, all with different facilities and efficiency trade offs. There is bag, set, list, array, ordered list, dictionary, hash table, weak array, etc. A whole menagerie of collection types. See Edison (http://www.eecs.tufts.edu/~rdocki01/edison.html). Yes, the standard library is lacking a few structures (I often miss priority queues), but the code certainly exists elsewhere. However, Haskell only has 1 type of collection: linked lists. (And only single-linked at that.) While other normal programming languages spend huge amounts of effort trying to select exactly the right collection type for the task in hand, Haskell programs only ever use linked lists. I think you need to read more Haskell code. Data.Map and Data.Set (both tree-based data structures) are used very often. Arrays exist in the standard library, but aren't used very often -- O(1) access is usually not needed and the O(n) update cost for immutable arrays is quite expensive. Also, note the wild success of Data.ByteString -- a structure that is like a weird list/array hybrid. Why is that, exactly? Lists are very handy in a lazy programming language -- Haskell lets us use lists not only as a data structure, but as control structures as well. Also, lists or Data.Map are often close enough. Who needs a bag when Map a Int gets the job done? What good is a heap when Data.Map supports findMin? Cheers, Spencer Janssen Does writing software in Haskell magically change the properties of these data structures such that lists become more efficient than all the other types? Or is it that other data structures are only efficient when used with in-place updates? (The latter statement appears to be isomorphic to stating that Haskell programs must necessarily be less efficient than impure ones.) Thoughts? ___ 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
Re: Locating shared libraries
On Sat, 16 Jun 2007 08:21:50 +1000 skaller [EMAIL PROTECTED] wrote: One way to measure this is: if you removed GHC and applications, and there are (necessarily) no users of the remaining library package .. the library package shouldn't be in the global public place (/usr/lib+include etc). As I understand it, the entire point of this effort (shared libraries in GHC) is to allow dynamically linked Haskell executables. In this case, applications outside the GHC toolchain will in fact depend on these shared objects. As a concrete case, a binary darcs package could be a user of libghc66-base.so and libghc66-mtl.so -- with no dependencies on the GHC compiler package itself. Does this pass your litmus test? Cheers, Spencer Janssen ___ Glasgow-haskell-users mailing list Glasgow-haskell-users@haskell.org http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
[Haskell] ANNOUNCE: xmonad 0.2
The xmonad dev team is pleased to announce the 0.2 release of: xmonad: a tiling window manager http://xmonad.org About: Xmonad is a tiling window manager for X. Windows are arranged automatically to tile the screen without gaps or overlap, maximising screen use. All features of the window manager are accessible from the keyboard: a mouse is strictly optional, greatly increasing productivity in X. Xmonad is written and extensible in Haskell, and custom layout algorithms, and other extesions, may be implemented by the user in config files. Layouts may be applied dynamically, and separate layouts can be used on each workspace. A guiding principle of the user interface is predictability: users should know in advance precisely the window arrangement that will result from any action, leading to an intuitive user interface. Features: * Automatic window tiling and management * First class keyboard support: a mouse is unnecessary * Full multihead/Xinerama support * XRandR support to rotate, add or remove monitors * Per-workspace layout algorithms * Per-screen non-built in status bars, with arbitrary geometry * Dynamic restart/reconfigure preserving workspace state * Tiny code base (~500 lines of Haskell) * Fast, small and simple. No interpreters, no heavy extension languages Since 0.1, the following notable features and bug fixes have appeared: New features: * XRandR support, for dynamically adding, removing or rotating monitors * State-preserving dynamic restart * Popup, customisable status bar support * Multiple clients may appear in the master pane * mod-shift-j/k, to swap windows with their neighbours * mod-n, to resize windows * User-specified layout algorithms may be written in config files * All layouts may be 'mirrored' (rotated) * configurable window border size and colour Design changes: * Reimplemented core of xmonad with a 'zipper' data type to track focus by construction. We believe this is a first. * Use of Neil Mitchell's 'catch' program to verify pattern match safety * Use of ReaderT and StateT to partition read-only and modifiable values * Custom layout messages handled with open data type simulation * More QuickCheck properties Bug fixes: * numlock handling is fixed More information, screenshots, documentation and community resources are available from: http://xmonad.org Xmonad is available from hackage, and via darcs. Happy hacking! The Xmonad Team: Spencer Janssen Don Stewart Jason Creighton Xmonad has also received patches from: Alec Berryman Chris Mears Daniel Wagner David Glasser David Lazar David Roundy Joe Thornber Miikka Koskinen Neil Mitchell Nick Burlett Robert Marlow Sam Hughes Shae Erisson ___ Haskell mailing list Haskell@haskell.org http://www.haskell.org/mailman/listinfo/haskell
[Haskell-cafe] ANNOUNCE: xmonad 0.2
The xmonad dev team is pleased to announce the 0.2 release of: xmonad: a tiling window manager http://xmonad.org About: Xmonad is a tiling window manager for X. Windows are arranged automatically to tile the screen without gaps or overlap, maximising screen use. All features of the window manager are accessible from the keyboard: a mouse is strictly optional, greatly increasing productivity in X. Xmonad is written and extensible in Haskell, and custom layout algorithms, and other extesions, may be implemented by the user in config files. Layouts may be applied dynamically, and separate layouts can be used on each workspace. A guiding principle of the user interface is predictability: users should know in advance precisely the window arrangement that will result from any action, leading to an intuitive user interface. Features: * Automatic window tiling and management * First class keyboard support: a mouse is unnecessary * Full multihead/Xinerama support * XRandR support to rotate, add or remove monitors * Per-workspace layout algorithms * Per-screen non-built in status bars, with arbitrary geometry * Dynamic restart/reconfigure preserving workspace state * Tiny code base (~500 lines of Haskell) * Fast, small and simple. No interpreters, no heavy extension languages Since 0.1, the following notable features and bug fixes have appeared: New features: * XRandR support, for dynamically adding, removing or rotating monitors * State-preserving dynamic restart * Popup, customisable status bar support * Multiple clients may appear in the master pane * mod-shift-j/k, to swap windows with their neighbours * mod-n, to resize windows * User-specified layout algorithms may be written in config files * All layouts may be 'mirrored' (rotated) * configurable window border size and colour Design changes: * Reimplemented core of xmonad with a 'zipper' data type to track focus by construction. We believe this is a first. * Use of Neil Mitchell's 'catch' program to verify pattern match safety * Use of ReaderT and StateT to partition read-only and modifiable values * Custom layout messages handled with open data type simulation * More QuickCheck properties Bug fixes: * numlock handling is fixed More information, screenshots, documentation and community resources are available from: http://xmonad.org Xmonad is available from hackage, and via darcs. Happy hacking! The Xmonad Team: Spencer Janssen Don Stewart Jason Creighton Xmonad has also received patches from: Alec Berryman Chris Mears Daniel Wagner David Glasser David Lazar David Roundy Joe Thornber Miikka Koskinen Neil Mitchell Nick Burlett Robert Marlow Sam Hughes Shae Erisson ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Should do 1 compile
On Wed, 23 May 2007 19:54:27 +0100 Neil Mitchell [EMAIL PROTECTED] wrote: Hi foo = do (1 :: Int) While intuitively this should be disallowed, it seems a pity that desugaring couldn't be totally separated from typechecking. Hmm. You can always desugar as: do x == return () x Although then you are relying on the Monad laws more than you possibly should. You could also have: monady :: Monad m = m a - m a monady x = x do x == monady x How about: do x == (x :: Monad m = m a) Or even: do x == (asTypeOf x (return ())) Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Poor first impression
On Fri, 27 Apr 2007 06:28:48 -0300 Fernando Cassia [EMAIL PROTECTED] wrote: I admit in shame never having heard about Haskell before. I know about PHP, Python, IBM' s REXX, TCL, TCL/TK, perl... but Haskell, never. So, here's how I landed in Haskell-land: I was looking for a simple ncurses-based text mode mp3 player with some sort of basic GUI and found HMP3 written in, you guessed it, Haskell. So I follow the directions and download the huge 30MB+ ghc-6.6.1-i386-unknown-linux.tar.bz2. Bunzip2 it. tar xvf it. ./configure and make install. So far, so good. and I get the following message, supposedly telling me that the haskell compiler was installed OK... === Installation of ghc-6.6.1 was successful. To use, add /usr/local/bin to your PATH. For documentation, see /usr/local/share/ghc-6.6.1/html/index.html === (/usr/local/bin is already in my path) So I decide to call the ghc compiler with no arguments to see if it was indeed installed, and I get this: [EMAIL PROTECTED] ghc-6.6.1]# ghc /usr/local/lib/ghc-6.6.1/ghc-6.6.1: error while loading shared libraries: libreadline.so.4: cannot open shared object file: No such file or directory # Yes, that is a bit annoying. The readline issues are mentioned on the download page though -- you were warned ;). GHC 6.6.1 is only a day old, so there aren't very many binary builds available. On the other hand, GHC 6.6 has RPMs for FC5: http://www.haskell.org/ghc/download_ghc_66.html#x86linux So, I conclude that Haskell is not ready for prime time, if it cannot install itself correclty including shared libs in a standard Fedora Core 6 system. Please don't make generalizations from a single experience with a compiler version that is less than a day old. Goodbye Haskell, I just wanted to compile a MP3 player, and perhaps if the compiler installed OK with no issues, I'd have taken a look at the language. But as of right now, I don't have time to waste with broken compiler installers. Byebye FC Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell] ANNOUNCE: xmonad 0.1
The xmonad dev team is pleased to announce the inaugural release of: xmonad: a tiling window manager http://xmonad.org Xmonad is a minimalist tiling window manager for X, written in Haskell. Windows are managed using automatic layout algorithms, which can be dynamically reconfigured. At any time windows are arranged so as to maximise the use of screen real estate. All features of the window manager are accessible purely from the keyboard: a mouse is entirely optional. Xmonad is configured in Haskell, and custom layout algorithms may be implemented by the user in config files. A principle of Xmonad is predictability: the user should know in advance precisely the window arrangement that will result from any action. By default xmonad provides three layout algorithms: tall, wide and fullscreen. In tall or wide mode, windows are tiled and arranged to prevent overlap and maximise screen use. Sets of windows are grouped together on virtual screens, and each screen retains its own layout, which may be reconfigured dynamically. Multiple physical monitors are supported via Xinerama, allowing simultaneous display of a number of screens. By utilising the expressivity of a modern functional language with a rich static type system, Xmonad provides a complete, featureful window manager in less than 500 lines of code, with an emphasis on correctness and robustness. Internal properties of the window manager are checked using a combination of static guarantees provided by the type system, and type-based automated testing. A benefit of this is that the code is simple to understand, and easy to modify. More information, screenshots, documentation and community resources are available from: http://xmonad.org Xmonad is available from hackage, and via darcs. Happy hacking! The Xmonad Team: Spencer Janssen Don Stewart Jason Creigh ___ Haskell mailing list Haskell@haskell.org http://www.haskell.org/mailman/listinfo/haskell
[Haskell-cafe] ANNOUNCE: xmonad 0.1
The xmonad dev team is pleased to announce the inaugural release of: xmonad: a tiling window manager http://xmonad.org Xmonad is a minimalist tiling window manager for X, written in Haskell. Windows are managed using automatic layout algorithms, which can be dynamically reconfigured. At any time windows are arranged so as to maximise the use of screen real estate. All features of the window manager are accessible purely from the keyboard: a mouse is entirely optional. Xmonad is configured in Haskell, and custom layout algorithms may be implemented by the user in config files. A principle of Xmonad is predictability: the user should know in advance precisely the window arrangement that will result from any action. By default xmonad provides three layout algorithms: tall, wide and fullscreen. In tall or wide mode, windows are tiled and arranged to prevent overlap and maximise screen use. Sets of windows are grouped together on virtual screens, and each screen retains its own layout, which may be reconfigured dynamically. Multiple physical monitors are supported via Xinerama, allowing simultaneous display of a number of screens. By utilising the expressivity of a modern functional language with a rich static type system, Xmonad provides a complete, featureful window manager in less than 500 lines of code, with an emphasis on correctness and robustness. Internal properties of the window manager are checked using a combination of static guarantees provided by the type system, and type-based automated testing. A benefit of this is that the code is simple to understand, and easy to modify. More information, screenshots, documentation and community resources are available from: http://xmonad.org Xmonad is available from hackage, and via darcs. Happy hacking! The Xmonad Team: Spencer Janssen Don Stewart Jason Creigh ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Parallel executing of actions
On Sun, 15 Apr 2007 18:01:44 +0200 Mitar [EMAIL PROTECTED] wrote: Hi! Is there a parallel version of mapM_? Like it is for map (parMap)? This version will fork a new thread for each action: \begin{code} import Control.Concurrent import Control.Monad parSequence_ xs = do m - newEmptyMVar mapM_ (\x - forkIO x putMVar m ()) xs replicateM_ (length xs) (takeMVar m) parMapM_ f xs = parSequence_ $ map f xs \end{code} I would like to execute actions in parallel as the computation of necessary data for actions is quite computational heavy. But it does not matter in which order those actions are executed. (I am rendering pixels with OpenGL and it does not matter in which order I draw them, but it matters that for one pixel it takes some time to calculate its color.) The example would be: main :: IO () main = do -- the order of printed characters is not important -- instead of putStrLn there will be a computationally big function -- so it would be great if those computations would be done in parallel -- and results printed out as they come mapM_ rwhnf (putStrLn) [a,b,c,d] Is this possible? Without unsafe functions? And without changing the semantics of the program. Of course the semantics of the program will change, the order in which the actions are executed is unknown! Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] SmallCheck and parser testing
On Tue, 3 Apr 2007 16:01:56 +0100 Joel Reymont [EMAIL PROTECTED] wrote: Folks, I'm trying to figure out how to test a Parsec-based parser with Smallcheck [1]. My test AST is below and the goal is to return StyleValue Int here if the parser is fed an integer, or return Solid when parsing Solid, etc. data Style = StyleValue Expr | Solid | Dashed | Dotted | Dashed2 | Dashed3 deriving Show I figure that the following is needed somehow: instance Serial Style where series = cons1 StyleValue . depth 0 \/ cons0 Solid \/ cons0 Dashed \/ cons0 Dashed2 \/ cons0 Dashed3 \/ cons0 Dotted My parser is 'style', so I would be passing it as p below run p input = case (parse p input) of Left err - do { putStr parse error at ; print err } Right x - x How do I go from here to making sure my parser is valid? There are several ways to check your parser. If you have a pretty printer, you can check that the parse of a pretty printed term is equal to the term itself. \begin{code} parseEq :: String - Style - Bool parseEq s t = case parse style s of Left err - False Right x - x == t prop_parsePretty t = parseEq (pretty t) t \end{code} You can also use a unit-testing style. Imagine you have a list of strings and the correct parse trees for each. You can then check that the parses match the expected results. \begin{code} knownParses :: [(String, Style)] knownParses = ??? prop_unitTest = all (uncurry parseEq) knownParses \end{code} Cheers, Spencer Janssen I thought of the following property (thanks sjanssen) prop_parse p s = show (run p s) == s but I don't know how to proceed from here. Thanks, Joel [1] http://www.cs.york.ac.uk/fp/darcs/smallcheck/ -- http://wagerlabs.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
Re: [Haskell-cafe] Read Instance for UArray won't port to linux
It looks like you forgot to pass a compiler flag, namely -fglasgow-exts. Cheers, Spencer Janssen On Tue, 13 Mar 2007 22:20:20 -0700 (PDT) SevenThunders [EMAIL PROTECTED] wrote: I have the pleasure of porting a good sized Haskell application to linux. So far the Haskell code has compiled without incident, however some code that I hacked to implement a Read instance for Unboxed Arrays does not compile on linux even though it compiles just fine on Windows XP in Haskell 6.6. The code reads as, instance Read (UArray Int Double) where readsPrec p = readParen (p 9) (\r - [(array b as :: UArray Int Double, u) | (array,s) - lex r, (b,t) - reads s, (as,u) - reads t ]) The error in linux is: Illegal instance declaration for `Read (UArray Int Double)' (The instance type must be of form (T a b c) where T is not a synonym, and a,b,c are distinct type variables) In the instance declaration for `Read (UArray Int Double)' Why does it want three parameters for the instance type? I am baffled by this. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] ANNOUNCE: The Monad.Reader - Issue 6
Yet another higher order solution: dropWhile' p0 xs = foldr f (const []) xs $ p0 where f y ys p | p y = ys p | otherwise = y : ys (const False) Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] newbie timing question
On Jan 26, 2007, at 4:56 PM, Sean McLaughlin wrote: Hello, I'm trying to write a simple function to time an application. -- this doesn't work time f x = do n1 - CPUTime.getCPUTime let res = f x in do n2 - CPUTime.getCPUTime return (res,n2 - n1) On a function that takes 8 seconds to complete, returns (True,4600) Remember that Haskell is lazy -- res won't be evaluated until it is forced. See the evaluate function in Control.Exception to force a value in the IO monad. Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Strings in Haskell
On Jan 22, 2007, at 7:18 PM, Alexy Khrabrov wrote: Greetings -- I'm looking at several FP languages for data mining, and was annoyed to learn that Erlang represents each character as 8 BYTES in a string which is just a list of characters. Now I'm reading a Haskell book which states the same. The standard string type in Haskell is indeed a linked list of characters, with about 12 bytes of overhead per character. Is there a more efficient Haskell string-handling method? Yes! There is a library called Data.ByteString [1], it is included with the latest versions of GHC and Hugs, and is also available as a standalone package. Data.ByteString represents strings as packed arrays of bytes, so the overhead is about 1 byte per character. This library exhibits fantastic performance, rivaling C's speed while maintaining the elegance of Haskell. Cheers, Spencer Janssen [1] http://www.cse.unsw.edu.au/~dons/fps.html ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] an advanced foldification problem
Take this obscure function: \begin{code} func :: (a - a - Maybe a) - a - [a] - [a] func f s0 xs0 = foldr (\x xs s - maybe (xs s) ((x:) . xs) (f s x)) return xs0 s0 \end{code} And mergeGroupToList becomes: \begin{code} mergeGroupToList g xs = func mergeGroups g xs \end{code} Cheers, Spencer Janssen On Jan 11, 2007, at 11:37 AM, Seth Gordon wrote: I have a data type Group, representing a group of geographic information that is all referring to the same location, and a function mergeGroups that tries to merge two groups: mergeGroups :: Group - Group - Maybe Group Then I have a function mergeGroupToList that tries to merge its first argument with every element of the second argument: mergeGroupToList :: Group - [Group] - [Group] mergeGroupToList g [] = [g] mergeGroupToList g1 (g2:gs) = case (mergeGroups g1 g2) of Nothing - g2 : (mergeGroupToList g1 gs) Just g3 - mergeGroupToList g3 gs How can I rewrite mergeGroupToList in terms of foldr? ___ 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
Re: [Haskell-cafe] MissingH: profiler support?
The typical way to add profiling support to a Cabal lib is to add -p at configure time (ie runhaskell Setup.hs configure -p). Have you tried this? Cheers, Spencer Janssen On Jan 8, 2007, at 4:13 PM, Chris Eidhof wrote: Hey all, I'm trying to profile my application, which makes use of MissingH. But when compiling with -prof -auto-all, I get the following error: Language.hs:8:7: Could not find module `Data.String': Perhaps you haven't installed the profiling libraries for package MissingH-0.18.0? Use -v to see a list of the files searched for. When compiling without those options, everything works just fine. I built missingh from source, and added -prof -auto-all to GHCPARMS, and did a ./setup configure,make,install and still no result. Does anyone know what could be wrong? I'd really like to keep using MissingH and having profiling support at the same time. Thanks, -chris ___ 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
[Haskell-cafe] The Data.Array.* hierarchy is unsafe (or, Segfaulting for fun and profit)
I've discovered a problem in the array libraries that allows one to read arbitrary memory locations without the use of any unsafeFoo functions. Both GHC and Hugs are affected. import Data.Array.IArray import Data.Array.Unboxed Here is a poorly behaved instance of Ix: inRange and index ignore the bounds supplied. newtype EvilIx = E Int deriving (Eq, Ord) instance Ix EvilIx where inRange _ _ = True index _ (E i) = i range (E x, E y) = map E $ range (x, y) One can read arbitrary memory locations, eventually indexing far enough to cause a segmentation fault. main = print [a ! E (2^i) | i - [0..]] where a :: UArray EvilIx Int a = array (E 0, E 0) [] This problem is not specific to UArrays: main' = print [a ! E (2^i) | i - [0..]] where a :: Array EvilIx String a = array (E 0, E 0) [] The issue is that the array operators trust the Ix instance to manage boundaries correctly. The solution is to double check the value returned by index with the actual length of the array. I volunteer to write the fix, if I can extract some hints from more knowledgeable folk. There's sizeOfByteArray#, is there an analog for an Array#? I need to know how to find the length of Hugs array primitives too. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Command line utility that shrinks/simplifies functions applications ?
I believe you're talking about the `pl' plugin for lambdabot. Lambdabot has an offline mode, visit the homepage for the source: http://www.cse.unsw.edu.au/~dons/lambdabot.html There is also a web interface to lambdabot, but I can't seem to find the link. Cheers, Spencer Janssen On Nov 30, 2006, at 8:32 AM, Nicola Paolucci wrote: Hi All! Haskell newbie here with a very simple question because google and hoogle are of no help. On the IRC channel #haskell (which I cannot access now from work) I saw somebody using a tool which automatically simplifies expressions,composition of multiple functions to the bare minimum. It was a query to lambdabot I think. Is that tool/library also standalone ? What's its name ? Where can I find it ? That really rocked ... Thanks, Nick ___ 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
Re: [Haskell-cafe] Priority Queue?
I recommend the Edison library, which has several heap implementations. http://www.eecs.tufts.edu/~rdocki01/edison.html Cheers, Spencer Janssen On Nov 26, 2006, at 3:58 PM, Ken Takusagawa wrote: Is there a Haskell implementation of an efficient priority queue (probably heap-based) out there that I can use? I do not see it in the GHC libraries. ___ 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
Re: runtime fusion for Data.ByteString.cons ?
On Nov 19, 2006, at 11:54 AM, Claus Reinke wrote: I noticed that ByteString is drastically slower than String if I use cons a lot. according to the source, that is expected because of the memcpy for the second parameter. Have you considered constructing your strings with unfoldr? It should be able to handle most (all?) of your string producing functions efficiently. Cheers, Spencer Janssen ___ Glasgow-haskell-users mailing list Glasgow-haskell-users@haskell.org http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
Re: Major type-class overhaul
On Nov 17, 2006, at 5:40 PM, Duncan Coutts wrote: I'd certainly support that. Am I right in thinking that it'd allow Data.Set to be made an instance of Monad, because the Ord constraint would be available in the body of the bind method? return is still a problem, because there is no Ord constraint there. Spencer Janssen ___ Glasgow-haskell-users mailing list Glasgow-haskell-users@haskell.org http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
Re: [Haskell-cafe] Unicode strings
The problem is that GHC's output functions only print the lowest 8 bits of each code point. To print these higher code points, you'll need to translate your [Char] into a byte encoding that your terminal will understand (most likely UTF-8). I know there are several of these floating around in the wild, hopefully someone will chime in with a code snippet soon. Also, I seem to remember that Bulat's Streams library supports some Unicode encodings, perhaps you can check there? Cheers, Spencer Janssen On Nov 5, 2006, at 12:17 PM, Pupeno wrote: Hello, I am trying to make a program that outputs some Unicode characters but the output doesn't match what I try to print. Attached is a little test program. It tries to print the arrows ←↑→↓ but instead it outputs \220\221\222\223 (that is, character number 220, then 221, then 222). I've also tried writing the Unicode code points (although GHC 6.6 should deal just fine with Unicode source code) and I get the same result. In case anybody wants to try, this would be the string: \8592\8593\8594\8595. I am also attaching the output file, you can see that the contents are not right. Any ideas what am I doing wrong here ? Thank you. -- Pupeno [EMAIL PROTECTED] (http://pupeno.com) test.hs test.output ___ 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
Re: [Haskell-cafe]Prime Generator time limit exceeded
The problem with your approach is the gratuitous use of division, which tends to be very slow. In my solution, I first generate a list of seed primes, all primes less than sqrt 10. Then, for each input m and n, I generate all multiples of the seed primes between m and n. I then output each number that isn't a multiple of a seed prime. Tips: - Haskell will infer the Integer type by default, an unbounded type. Operations on Integer are often considerably slower than Int, the corresponding bounded type. - The accumArray function is a handy way to collect all the generated multiples. For maximum speed, use a UArray Int Bool. - gcd is a particularly expensive function to use here, perhaps you can use the mod function instead? - here is a handy function to generate your seed primes: sieve [] = [] sieve (x:xs) = x : [y | y - xs, y `mod` x /= 0] Spencer Janssen On Nov 1, 2006, at 10:49 AM, alaiyeshi wrote: Hi I'm new to Haskell. I found this site on the Haskell wiki https://www.spoj.pl. But I got some trouble on trying to solve the problem titled Prime Generator https://www.spoj.pl/problems/PRIME1. The online-judge system tells me time limit excedded Would you be so kind to tell me how to make it more faster? And any other suggestion is welcome. Thanks in advance. --Code begin module Main where import IO import List main = do input_size-getLine content-get_contents (read input_size) mapM_ (\r- do mapM_ (print) (primeGenerator (parse r)); putStrLn ) content get_contents n | n == 0 = return [] | otherwise = do content-getLine rests-get_contents (n-1) return ([content]++rests) primeGenerator [start,end] = [x | x-[start..end], all (== 1) (map (gcd x) [2.. (x-1)]), x/=1] parse s = unfoldr (\x- case x of []- Nothing _- Just (head (reads x))) s ---Code ends-- -- (BTW: I'm new to this mailling list also, forgive my rudeness if I am, and forgive my poor English) ___ 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
Re: [Haskell-cafe] Type level functions (type of decreasing list)
Here's an attempt with GADTs: \begin{code} {-# OPTIONS_GHC -fglasgow-exts #-} data Succ a data Zero data Seq a b where Cons :: a - Seq a b - Seq a (Succ b) Nil :: Seq a Zero \end{code} Seems to work for me. Spencer Janssen On Oct 17, 2006, at 6:37 PM, Greg Buchholz wrote: I'm wondering about creating a data structure that has the type of decreasing numbers. If I want an increasing list, it is easy... {-# OPTIONS -fglasgow-exts #-} data Succ a = S a deriving Show data Zero = Z deriving Show data Seq' a = Cons' a (Seq' (Succ a)) | Nil' deriving Show ...which can be used like... zero = Z one = S zero two = S one three = S two increasing = Cons' zero (Cons' one (Cons' two (Cons' three Nil'))) ...on the other hand, if I want the decreasing list, I can try... class Pre a b | a - b instance Pre (Succ a) a instance Pre Zero Zero data (Pre a b) = Seq a = Cons a (Seq b) | Nil decreasing = Cons three (Cons two (Cons one Nil)) ...but that complains about Not in scope: type variable `b'. Of course that makes perfect sense, but I'd like to know if there is a Haskell idiom that I'm missing in order to get this to work. Thanks, Greg Buchholz ___ 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
Re: [Haskell-cafe] How can we detect and fix memory leak due to lazyness?
On 8/7/06, Ahn, Ki Yung [EMAIL PROTECTED] wrote: I have posted an wiki article including one example of adding a counter to count the number of basic operations in sorting algorithm. http://www.haskell.org/haskellwiki/Physical_equality This was a rather simple situation and we figured out how to cure this by self equality check ( x==x ) forcing evaluation. Forcing evaluation using (==) is a bit of a hack. Luckily, we have a better function to force evaluation: seq (which has type a - b - b). seq x y evaluates x to weak head normal form before returning y. Let's try another feature of Haskell to force evaluation: strict data fields. A ! in front of a field in a data declaration signifies strictness. In the example below, whenever we construct a value with TT, the second argument is evaluated. \begin{code} data TT a b = TT a !b \end{code} Perhaps your instances will work correctly with this data declaration? Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Filtering a big list into the IO monad
This message is literate Haskell source. import System.IO.Unsafe (unsafeInterleaveIO) First off, let's look at the code for 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) The potential for a stack overflow is pretty obvious here. filterM is applied to the tail of the list before any result is returned. Here's a version that reverses the list as it filters. It will run in constant stack space. filterRevM :: (Monad m) = (a - m Bool) - [a] - m [a] filterRevM p = flip go [] where go [] acc = return acc go (x:xs) acc = do flg - p x if flg then go xs $! x:acc else go xs acc And finally, here's a version that uses unsafeInterleaveIO, and if it isn't obvious, it really is unsafe! Please read up on the risks of unsafeInterleaveIO before using this version. unsafeFilterIO :: (a - IO Bool) - [a] - IO [a] unsafeFilterIO p [] = return [] unsafeFilterIO p (x:xs) = do flg - p x ys - unsafeInterleaveIO $ unsafeFilterIO p xs return (if flg then x:ys else ys) Cheers, Spencer Janssen On 8/3/06, Gabriel Sztorc [EMAIL PROTECTED] wrote: | Hello, | | I want to filter a list with a predicate that returns a IO value, | something that filterM is supposed to do. The problem is, filterM | overflows the stack for really big lists and I couldn't come up with a | simple replacement for filterM that would work for lists of any size | (the truth is, I can't come up with anything at all :). | | The question is: how to do it? Any help is appreciated. | ___ | 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
Re: [Haskell-cafe] heap issues
ghci keeps the value of your last computation in a special variable called it. Therefore, the value of your last run can't be garbage collected until the current run is finished. Try print run or type in a dummy expression in between runs. Cheers, Spencer Janssen On 7/27/06, Jeff Polakow [EMAIL PROTECTED] wrote: Hello, Why would ghci run out of heap space (and crash) the second time I run a computation? More specifically, I have a ghci session which goes something like this: *Analysisrun [ ... print out of a very long list ...] *Analysisrun [ ... partial print out GHC's heap exhausted: current limit is 268435456 bytes; Use the `-Msize' option to increase the total heap size. Shouldn't the garbage collector free up everything in between my top-level function executions? Also, there doesn't appear to be a '-Msize' flag for ghc (I'm using 6.4.2 on windows xp). thanks, 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. ___ 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
Re: Re[2]: [Haskell-cafe] Re: ANN: System.FilePath 0.9
I've been writing a Stringable class for my SoC project. You can check out the code at http://darcs.haskell.org/SoC/fps-soc/Data/Stringable.hs. Spencer Janssen On 7/23/06, Bulat Ziganshin [EMAIL PROTECTED] wrote: Hello Brian, Sunday, July 23, 2006, 1:20:36 AM, you wrote: instance IString ByteString.Char8 ... instance IString String ... i think that we should ask Donald Stewart who is patronized SoC project involving development of such type class. If he will say that such type class is not developed, i feel himself enough interested to start developing such class. i can add this module to ByteString lib, if there is no better variants i propose something like this: class ListLike ce e | ce-e instance ListLike [a] a instance ListLike Data.ByteString.ByteString Word8 instance ListLike Data.ByteString.Lazy.ByteString Word8 instance ListLike Data.ByteString.Char8.ByteString Char instance ListLike Data.ByteString.Lazy.Char8.ByteString Char -- Best regards, Bulatmailto:[EMAIL PROTECTED] ___ 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
Re: [Haskell-cafe] Why Haskell?
On 7/22/06, Matthew Bromberg [EMAIL PROTECTED] wrote: I used what I thought, initially was an elegant contruction technique in Haskell. Something like this do ... sequence $ [ reffill b s | s - [0..(fi temits)-1], b - [0..(fi nc)-1]] ...(push list on to matrix stack) Try the sequence_ (note the underscore) function, it should be a big win here. Cheers, Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] lists as instances of a class?
The problem isn't with lists specifically, but with any instance that applies types (rather than type variables) to a type constructor From section 4.3.2 of The Haskell 98 Report: The type (T u1 ... uk) must take the form of a type constructor T applied to simple type variables u1, ... uk. I've run into this restriction several times myself, and I'm also curious whether this will change in Haskell'. Spencer Janssen On 7/10/06, David Roundy [EMAIL PROTECTED] wrote: (This email is a literate haskell program that fails to compile without -fglasgow-exts.) I'm sure I'm missing something lame here, but can someone tell me why we apparently can't declare a list to be an instance of a class in Haskell 98? Or is there perhaps some other syntax by which I'd declare this instance? If so, is this slated for fixing in Haskell'? $ ghc Test.lhs Test.lhs:6:1: Illegal instance declaration for `Vec [Double]' (The instance type must be of form (T a b c) where T is not a synonym, and a,b,c are distinct type variables) In the instance declaration for `Vec [Double]' module Vec where class Vec v where (.+.) :: v - v - v instance Vec [Double] where xs .+. ys = zipWith (+) xs ys instance Vec Double where x .+. y = x + y feeling very stupid, David P.S. This is with ghc 6.4.1. And oddly enough, if you make the instance instance Num a = Vec [a] where xs .+. ys = zipWith (+) xs ys it works fine, but this strikes me as quite an ugly hack. I really want only Doubles to be instances of this class (which I've abbreviated for this email). ___ 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
Re: [Haskell-cafe] Fibonacci numbers generator in Haskell
Here's some code I wrote a while back for computing the nth Fibonacci number. It has O(log n) time complexity rather than O(n). It isn't the most elegant example, but it should be one of the fastest approaches. import Data.Bits (shiftR, xor, (.|.), (..)) import Data.Word (Word32) fibo :: Word32 - Integer fibo n = loop (highestBitMask n) 1 0 where loop :: Word32 - Integer - Integer - Integer loop i a b | i == 0 = b | n .. i /= 0 = (loop (shiftR i 1) $! a*(2*b + a)) $! a*a + b*b | otherwise= (loop (shiftR i 1) $! a*a + b*b) $! b*(2*a - b) highestBitMask :: Word32 - Word32 highestBitMask x = case (x .|. shiftR x 1) of x - case (x .|. shiftR x 2) of x - case (x .|. shiftR x 4) of x - case (x .|. shiftR x 8) of x - case (x .|. shiftR x 16) of x - (x `xor` (shiftR x 1)) Cheers, Spencer Janssen On 6/15/06, Vladimir Portnykh [EMAIL PROTECTED] wrote: Fibonacci numbers implementations in Haskell one of the classical examples. An example I found is the following: fibs :: [Int] fibs = 0 : 1 : [ a + b | (a, b) - zip fibs (tail fibs)] To get the k-th number you do the following: Result = fibs !! k It is elegant but creates a list of all Fibonacci numbers less than k-th, and the code is not very readable :). I wrote my own Fibonacci numbers generator: fib :: Int - [Int] fib 0 = [0,0] fib 1 = [1,0] fib n = [sum prevFib, head prevFib] where a = fib (n - 1) To get the k-th number you do the following: result = head (fib k) It does not generate full list of Fibonacci numbers, but keeps only 2 previous numbers, and has only one recursive call. Because the list always has only 2 elements using the functions head and sum is a bit overkill. Can we do better? _ Are you using the latest version of MSN Messenger? Download MSN Messenger 7.5 today! http://join.msn.com/messenger/overview ___ 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
[Haskell-cafe] Re: Am I lazy enough?
ByteString's are strict in their contents, so when you do an hGetContents you'll read the entire file into memory! This negates any laziness benefits right off the bat. The trickiest part is the lazy IO, you have to use unsafeInterleaveIO or something similar. Below is a program that does approximately the same as yours. Note the getLinesLazily function. I've only tested that it typechecks, I haven't run it yet. Spencer Janssen -- Program begins here import System.IO import System.IO.Unsafe (unsafeInterleaveIO) import qualified Data.ByteString.Char8 as B import Data.ByteString.Char8 (ByteString) main = getLinesLazily stdin = mapM B.putStrLn . relines 8 relines :: Int - [ByteString] - [ByteString] relines n = go . map (\s - (s, B.count ',' s)) where go [] = [] go [(s, _)] = [s] go ((s, x) : (t, y) : ss) | x + y n = s : go ((t, y) : ss) | otherwise = go ((B.append s t, x + y) : ss) getLinesLazily :: Handle - IO [ByteString] getLinesLazily h = do eof - hIsEOF h if eof then return [] else do l - B.hGetLine h ls - unsafeInterleaveIO $ getLinesLazily h return (l:ls) -- Program ends here On 5/3/06, Joel Reymont [EMAIL PROTECTED] wrote: Folks, I'm looking to use the following code to process a multi-GB text file. I am using ByteStrings but there was a discussion today on IRC about tail recursion, laziness and accumulators that made me wonder. Is fixLines below lazy enough? Can it be made lazier? Thanks, Joel --- module Main where import IO import System import Numeric import Data.Char import Data.Word import qualified Data.Map as M import qualified Data.ByteString.Char8 as B import Prelude hiding (lines) grabTableInfo x = (tableId', (tableType, tableStakes)) where (tableId:tableType:_:tableStakes:_) = B.split ',' x Just (tableId', _) = B.readInt tableId lines = B.split '\n' --- My Oracle ascii dump is 80 characters wide so some lines --- are split. I need to skip empty lines and join lines --- containing less than the required number of commas. fixLines 0 lines = lines fixLines _ [] = [] fixLines n (line:lines) = fixLines' lines line [] where fixLines' [] str acc | B.count ',' str == n = acc ++ [str] | otherwise = acc fixLines' (x:xs) str acc | B.null str -- skip = fixLines' xs x acc | B.count ',' str n -- join with next line = fixLines' xs (B.append str x) acc | otherwise = fixLines' xs x (acc ++ [str]) mkMap = M.fromList . map grabTableInfo . fixLines 20 loadTableInfo = do bracket (openFile game_info_tbl.csv ReadMode) (hClose) (\h - do c - B.hGetContents h return $ mkMap $ lines c) -- http://wagerlabs.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
Re: [Haskell-cafe] Bit streams programs in Haskell
I have rewritten the Huffman benchmark (see http://cse.unl.edu/~sjanssen/huffman.hs), resulting in a significant performance increase. On my computer it completes one iteration in about 0.9 seconds. In comparison, the O'Caml version takes around 3.1 seconds. These samples seem to indicate that this Haskell program will compare favorably with Erlang. I'd say the program is written in fairly idiomatic Haskell. Turning the bytes in the buffer into a lazy stream of Bool's (see the bitstream function) is both elegant and surprisingly efficient. There is one infidelity in my implementation: the program writes the output once per iteration, and this IO is included in the measured time. This results in a small time penalty in comparison to the other versions. I am still searching for a solution to this, but for now it seems that printing the output is the cheapest way to force evaluation. Improvements and discussion are solicited. Feel free to include this code in your website, if you'd like. Spencer Janssen On 3/22/06, Per Gustafsson [EMAIL PROTECTED] wrote: Haskell gurus, We have made a proposal to extend the Erlang `binary' data type from being a sequence of bytes (a byte stream) to being a sequence of bits (a bitstream) with the ability to do pattern matching at the bit level. This proposal has now been fully implemented all these at the level of the BEAM virtual machine and in the HiPE compiler. Most probably, they will be part of the next major Erlang/OTP open source release. (We write most probably because we do not really control what Ericsson desides to release as part of its open source system.) We wanted to evaluate the performance of our implementation and the succintness of our syntax, particularly against other `similar' languages. For this reason, we wrote five reasonably representative benchmarks, showing the things that one could employ bit stream pattern matching and bit-level comprehensions for. The benchmarks (drop3, five11, huffman, uudecode, and uuendode) have all been written in Erlang, O'Caml and Haskell. For some of them, C and Java versions exist. They can be found in the following homepage: http://bitbenches.infogami.com/ As you will see there, the Haskell numbers are significantly slower than those of Erlang and O'Caml. We are wondering why this is so. For each language, we have spent a considerable effort in writing the benchmarks in -- at least what we feel -- is the most natural and efficient way one can write them. The only constraint we impose is that for functional languages, data structures without any explicit mutation have to be used in the part of the program for which measurements are taken. Our experience in writing efficient (and beautiful) Haskell programs is close to (if not below) zero. Also, perhaps our mind might be suffering from severe case of strictness and might be completely unable to `think lazily'. So, we request your help in noticing obvious NO-NOs and stupid mistakes that we might have made. We even welcome completely different Haskell programs provided they adhere to the constraint mentioned above -- no mutation. Best regards, Kostis Sagonas and Per Gustafsson ___ 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
Re: [Haskell-cafe] Bit streams programs in Haskell
It seems I have spoken too soon! There is one infidelity in my implementation: the program writes the output once per iteration, and this IO is included in the measured time. Due to a few changes, this caveat no longer applies. As a result Haskell performs just a bit better. The code is still at http://cse.unl.edu/~sjanssen/huffman.hs. The old main is left for reference, renamed to main'. Run time (in seconds) for 10 iterations: O'Caml: 35.9 Old Haskell: 25.6 New Haskell: 8.8 Spencer Janssen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Performance Timing
I've written two versions of a prime number sieve, and I'm trying to figure out how to performance test them. I've found functions to get the current date and time, and to subtract them, but when I put them in a do notation, I guess the laziness or something, makes the calculation happen first, then the two times are called, so I get almost 0 difference between the two. I guess I'm looking for something like this: timer :: (a - b) - a - IO TimeDiff Spencer Janssen ___ Haskell mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell