Re: [Haskell-cafe] ANNOUNCE: cinvoke 0.1 released
On Wed, Mar 09, 2011 at 05:50:12PM +0100, Gábor Lehel wrote: On Wed, Mar 9, 2011 at 5:26 PM, Remi Turk rt...@science.uva.nl wrote: Count on it having at least an order of magnitude more overhead. I did some simple test of calling the following three trivial functions (with constant arguments, and ignoring the return values, 2M times) and got the following timings: int blub0() { return 42; } int blub1(int a) { return 42; } int blub5(int a, int b, int c, int d, int e) { return 42; } Unsafe FFI Safe FFI Safe dynamic FFI CInvoke blub0 0.03 0.19 0.20 1.62 blub1 0.03 0.20 0.20 2.44 blub5 0.04 0.20 0.20 4.35 It's not that bad for functions that actually (try to) do something though. For example, trying to remove a non-existent file: unlink 3.06 3.04 3.27 7.15 If I remember correctly, libffi was slightly faster, but mostly thanks to the fact that I didn't make it exception safe yet. So if you care about performance and are able to directly use the FFI, you clearly should. That describes my situation. Thanks! For the record, what units were your measurements in? (I notice that the overhead of safe FFI calls seems to be pretty smallish, which is also quite heartening.) Everything is in seconds. So for example, 2 million unsafe calls to blub0 take 0.03 seconds: ~15ns or ~42 cycles per call (including replicateM_ overhead). I just noticed in my little non-scientific benchmark that the overhead for safe calls is significantly higher when compiling with -threaded: Unsafe FFI Safe FFI Safe dynamic FFI CInvoke blub0 0.04 0.36 0.35 2.27 blub1 0.05 0.36 0.36 3.52 blub5 0.05 0.37 0.37 5.72 unlink 3.26 3.21 3.56 8.41 Groeten, Remi ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] ANNOUNCE: cinvoke 0.1 released
On Tue, Mar 08, 2011 at 01:01:58PM +0100, Gábor Lehel wrote: On Sun, Mar 6, 2011 at 2:38 PM, Remi Turk rt...@science.uva.nl wrote: Where? Hackage: http://hackage.haskell.org/package/cinvoke Cheers, Remi [1] http://www.nongnu.org/cinvoke/ Is there any information on how this (and libffi I guess) compare to GHC's FFI in terms of performance? Is it equivalent? Once you've loaded a function with loadSymbol and are cinvoking it with various arguments, versus a plain foreign import of the same. Count on it having at least an order of magnitude more overhead. I did some simple test of calling the following three trivial functions (with constant arguments, and ignoring the return values, 2M times) and got the following timings: int blub0() { return 42; } int blub1(int a) { return 42; } int blub5(int a, int b, int c, int d, int e) { return 42; } Unsafe FFI Safe FFI Safe dynamic FFI CInvoke blub0 0.03 0.19 0.20 1.62 blub1 0.03 0.20 0.20 2.44 blub5 0.04 0.20 0.20 4.35 It's not that bad for functions that actually (try to) do something though. For example, trying to remove a non-existent file: unlink 3.06 3.04 3.27 7.15 If I remember correctly, libffi was slightly faster, but mostly thanks to the fact that I didn't make it exception safe yet. So if you care about performance and are able to directly use the FFI, you clearly should. (Also, I assume cinvoke corresponds to the FFI's 'unsafe' calls, i.e. if the function tries to call back into the GHC runtime then Bad Things will happen, and it'll block threads on the same 'Capability' if it runs too long?) Actually, it doesn't: Considering the rather large overhead of CInvoke itself, I just import everything 'safe'. Though to be honest I didn't actually test any callbacks into Haskell. Cheers, Remi ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] ANNOUNCE: cinvoke 0.1 released
On Tue, Mar 08, 2011 at 01:15:26AM +, Felipe Almeida Lessa wrote: On Mon, Mar 7, 2011 at 6:32 PM, Remi Turk rt...@science.uva.nl wrote: - If you need to pass C structs (by value), you'll have to use libffi: cinvoke doesn't support them at all. What about CInvStructure[1]? I was just glancing at the documentation when I saw this. That's a part of cinvoke I have not implemented (and probably won't, just like callbacks and a few other things, at least until there is some demand for them). However, the CInvStructure functions are used to construct descriptions and instances of C structures at run-time. (think alignment issues...) Passing structures to functions using cinvoke can only be done using pointers though.[1] Cheers, Remi [1] http://www.nongnu.org/cinvoke/doc/cinvoke_8h.html#4d288cacc9bde484cad7d8ed1b76c1a5 ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] ANNOUNCE: cinvoke 0.1 released
On Mon, Mar 07, 2011 at 09:41:27AM +, Max Bolingbroke wrote: Hi Remi, On 6 March 2011 13:38, Remi Turk rt...@science.uva.nl wrote: I am happy to finally announce cinvoke 0.1, a binding to the C library cinvoke[1], allowing functions to be loaded and called whose names and types are not known before run-time. As the author of the libffi package (http://hackage.haskell.org/package/libffi-0.1) which does a similar thing, could you say when it would be appropriate to use one or the other package? Cheers, Max Of course: - libffi doesn't do library/function loading; you'll need to use System.Posix.DynamicLinker or System.Win32.DLL for that. cinvoke will not only load your libraries and functions, but even collect the garbage afterwards. - Things seem to have changed, but back when I first looked at cinvoke, getting libffi to run under windows didn't seem too realistic. - If you need to pass C structs (by value), you'll have to use libffi: cinvoke doesn't support them at all. - The current version of libffi is not exception safe (I do have some code lying around here though...) - cinvoke is actually haddockized (although hackage still hasn't generated the docs, apparently). Groeten, Remi ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] ANNOUNCE: cinvoke 0.1 released
On Mon, Mar 07, 2011 at 10:00:47PM +0100, Daniel Fischer wrote: On Monday 07 March 2011 21:42:16, Gábor Lehel wrote: It's reporting a build failure. Missing C library. cinvoke (the C library) is obviously not installed on the testing machine. Does that really mean no library with uncommon C dependencies gets documentation on hackage? Remi ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] ANNOUNCE: cinvoke 0.1 released
On Mon, Mar 07, 2011 at 10:31:25PM +0100, Daniel Fischer wrote: On Monday 07 March 2011 22:14:38, Remi Turk wrote: cinvoke (the C library) is obviously not installed on the testing machine. Does that really mean no library with uncommon C dependencies gets documentation on hackage? Remi Basically, yes. As far as I know, documentation is only built for libraries that build on hackage. Maybe it would be a good idea to have the opportunity to upload haddock bundles to hackage too for such libraries. That sucks :( Uploading haddock bundles could solve the problem, though I don't currently understand why being able to successfully configure a package is a prerequisite to generating the docs. Anyway, I just put the docs online somewhere else with a link from the homepage: http://haskell.org/haskellwiki/Library/cinvoke ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] ANNOUNCE: cinvoke 0.1 released
I am happy to finally announce cinvoke 0.1, a binding to the C library cinvoke[1], allowing functions to be loaded and called whose names and types are not known before run-time. Why? Sometimes you can't use the Haskell foreign function interface because you parse the type of the function from somewhere else, i.e. you're writing an interpreter for a language that has an FFI itself. What? The main function it exports is: cinvoke :: Symbol - RetType b - [Arg] - IO b And because code is worth a thousand words, here's a small program that uses libc to write a 1Gb buffer of random garbage to a file: module Main where import Foreign.CInvoke main = do cxt - newContext libc - loadLibrary cxt libc.so.6 malloc - loadSymbol libc malloc creat - loadSymbol libc creat write - loadSymbol libc write free - loadSymbol libc free let sz = 2^30 buf - cinvoke malloc (retPtr retVoid) [argCSize sz] fd - cinvoke creat retCInt [argString /tmp/test, argCUInt 0o644] n - cinvoke write retCSize [argCInt fd, argPtr buf, argCSize sz] cinvoke free (retPtr retVoid) [argPtr buf] It hopefully works on any machine on which cinvoke works, but has only been tested on linux x86_64. As the current version of cinvoke only installs a static library, it does not work from GHCi at the moment (without hacking cinvoke to build a shared library). More interesting examples are included in examples/ in the package. Where? Hackage: http://hackage.haskell.org/package/cinvoke Cheers, Remi [1] http://www.nongnu.org/cinvoke/ ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] ANNOUNCE: libffi 0.1 released
I am happy to announce libffi 0.1, binding to the C library libffi, allowing C functions to be called whose types are not known before run-time. Why? Sometimes you can't use the haskell foreign function interface because you parse the type of the function from somewhere else, i.e. you're writing an interpreter for a language that has an FFI itself. What? The main function it exports is: callFFI :: FunPtr a - RetType b - [Arg] - IO b And because code is worth a thousand words, here a small program that uses C to write a 1Gb buffer of random garbage to a file: import System.Posix.DynamicLinker import Foreign.LibFFI main = do malloc - dlsym Default malloc creat - dlsym Default creat write - dlsym Default write let sz = 2 ^ 30 buf - callFFI malloc (retPtr retVoid) [argCSize sz] fd - callFFI creat retCInt [argString /tmp/test, argCUInt 0o644] n - callFFI write retCSize [argCInt fd, argPtr buf, argCSize sz] putStrLn $ show n ++ bytes written It should work on any 32/64bits machine on which libffi works, but has been primarily tested on linux x86_64. The current libffi is not exception-safe (exception = memory leak) and callFFI has quite some overhead that would be unnecessary with another api. It is, however, very easy to use :) More interesting examples are included in examples/ in the package. Where? Hackage: http://hackage.haskell.org/cgi-bin/hackage-scripts/package/libffi Module docs: http://www.science.uva.nl/~rturk/doc/libffi-0.1 Cheers, Remi ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Re: (flawed?) benchmark : sort
On Tue, Mar 11, 2008 at 01:43:36AM -0400, Brandon S. Allbery KF8NH wrote: On Mar 11, 2008, at 0:20 , Chaddaï Fouché wrote: 2008/3/11, David Menendez [EMAIL PROTECTED]: I think Adrian is just arguing that a == b should imply f a == f b, for all definable f, in which case it doesn't *matter* which of two equal elements you choose, because there's no semantic difference. I completely agree that this propriety should be true for all Eq instance exported by a public module. I don't care if it is not the case in a isolated code, but libraries shouldn't break expected invariant (or at least be very cautious and warn the user). Even Eq Double respects this propriety as far as I know. I wouldn't want to bet on that (Eq Double, that is). Floating point's just *evil*. I wouldn't bet on it either: Prelude 0.0 == -0.0 True Prelude isNegativeZero 0.0 == isNegativeZero (-0.0) False Although isNegativeZero might be considered a ``private, internal interface that exposes implementation details.'' Groeten, Remi ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] ANNOUNCE / POST MORTEM: hswm, version ()
Hi everyone, HSWM was my attempt at a Haskell Window Manager, mostly written during the first half of 2006 as a personal research project, and out of frustration with some not to be named other window managers. Although I have been running it myself for almost two years, I never got around to polishing it into something releasable due to lack of time. [1] Since, as of today, its number of users is officially back to zero [2], this seems like a good moment to release version () of HSWM: The first and last version of my own window manager. Features are: - includes a lambda mouse cursor - multiple desktops - sticky windows - about 2300 lines, about half of which is X boilerplate and user configuration - somewhat based on evilwm - still regularly dies due to unhandled X errors, so a script to automatically restart in that case is included - my first Xlib program ever The basic idea is an event loop inside an X monad providing three services to plugins: - registering X Event handlers - registering X Error handlers - registering/requesting services, to be used by other plugins (a global registry of named Dynamics, basically) Compared to XMonad: - no tiling - much less stable - no extensions - needs no external libs So you might want to look at it, but even _I_ don't use it anymore. HSWM only was its working name, so if anybody ever feels like writing another window manager and calling it HSWM, I certainly won't mind. The BSD-licensed code: darcs get http://student.science.uva.nl/~rturk/hswm/ `make' compiles, and that's it. Greetings, Remi [1] Technical detail: The one feature I really wanted before releasing it, but never got around to implementing, is having the WM add a frame for each managed window and reparenting the window below that frame. This way, focusing windows can go right even when the WM dies, among others. [2] It once had 3 users: Me at home, me at the University of Amsterdam and me at Utrecht University. Utrecht now runs KDE and the rest xmonad. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] forall and a parse error
Probably unrelated, but this thread is what triggered it for me. There is a minor bug in showing impredicative types without -fglasgow-exts: *hope I got that right* Prelude let x = [] :: [forall a. a] interactive:1:23: Warning: Accepting non-standard infix type constructor `.' Use -fglasgow-exts to avoid this warning Prelude :t x x :: [. (forall a) a] When -fglasgow-exts is set it shows what it should: Prelude :t x x :: [forall a. a] Groetjes, Remi On Tue, Jul 04, 2006 at 04:55:49PM +0100, Simon Peyton-Jones wrote: It's a parsing infelicity. (Inside square brackets the parser knows not to expect a forall, whereas inside round parens it might.) Perhaps it should be more accepting in square brackets, and reject later. Which the current HEAD does -- actually [forall a. a-a] is ok in the HEAD, see our ICFP06 paper. Simon | -Original Message- | From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Neil | Mitchell | Sent: 03 July 2006 19:44 | To: Haskell Cafe | Subject: [Haskell-cafe] forall and a parse error | | Hi, | | I was experimenting with forall and higher rank types briefly, in particular: | | x :: [forall a . a] | | This is illegal because of: | http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions. html#universal-quantification | | Which is fine, however its surprising to compare the error messages: | | [forall a . a] | parse error on input `forall' | | [(forall a . a)] | Illegal polymorphic or qualified type: forall a. a | In the type signature: lst :: [(forall a. a)] | | In normal Haskell, I tend to view [x] as equivalent to [(x)] (provided | that x is not a tuple) but in this case it has a different meaning - | albeit both are erronous meanings. | | When running the example with Hugs, they both come out as syntax | errors - the first on the forall, the second on the closing square | bracket. | | Thanks | | Neil | ___ | 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 mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] RE: module names
On Fri, Dec 16, 2005 at 07:55:50AM -0800, Scherrer, Chad wrote: From: S Koray Can [mailto:[EMAIL PROTECTED] Why not do this: name none of those modules Main.hs, and have an empty module Main.hs with only import MainDeJour and main = MainDeJour.main so you can just edit just that file. Cheers, Koray -- Yeah, I like that approach. That saves me from having to remember which file I most recent used as main. Seems easy enough to even set it up so that load MainDuJour writes the file Main.hs with import MainDuJour main = MainDuJour.main A rather late reply I realize, but this slightly less verbose version also works: module Main where import MainDuJour Remi ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] wxHaskell: getting a checkbox state
On Fri, Sep 16, 2005 at 12:12:50AM +0200, Sebastian Sylvan wrote: On 9/14/05, Mark Carter [EMAIL PROTECTED] wrote: The problem I was having before was that I was trying to create a separate function onCbEdit, thus: cbEdit - checkBox p1 [text := Edit Mode, on command := onCbEdit textlog ] This had the problem that onCbEdit basically needed to have its control passed in (i.e. cbEdit) as a parameter in order to inspect its state. So I wanted to do something like: cbEdit - checkBox p1 [text := Edit Mode, on command := onCbEdit textlog cbEdit ] Except you can't do that, because cbEdit isn't yet defined. But your suggestion gets 'round that. In the main loop, I now do: cbEdit - checkBox p1 [text := Edit Mode ] set cbEdit [ on command := onCbEdit textlog cbEdit ] Some extension (I think) to GHC allows mdo-notation (recursive do). So you can do this: mdo -- yadayada cbEdit - checBox p1 [text := Edit Mode, on comand := onCbEdit textlog cbEdit] -- yadayada... No extensions are needed, actually: cbEdit - checBox p1 [text := Edit Mode, on comand ::= onCbEdit textlog] ^^^ Note the double colon. Prelude Graphics.UI.WX :t (:=) (:=) :: Attr w a - a - Prop w Prelude Graphics.UI.WX :t (::=) (::=) :: Attr w a - (w - a) - Prop w Prelude Graphics.UI.WX :t (:~) (:~) :: Attr w a - (a - a) - Prop w Prelude Graphics.UI.WX :t (::~) (::~) :: Attr w a - (w - a - a) - Prop w Happy hacking, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] How to use STArray?
On Fri, Aug 26, 2005 at 08:27:43PM -0400, ChrisK wrote: to figure out since there was no Data.Array.ST.Lazy. Does anyone know why it was left out? I'll put a note on the HaskellTwo page about that... Some time ago when I wanted a lazy hashtable I came up with this, which, after minimal testing, seemed to work: (Lazy STRef's are implemented in exactly the same way, btw) \begin{code} {-# OPTIONS -fglasgow-exts #-} module MArrayLazyST ( STArray, module Data.Array.MArray ) where import Control.Monad.ST.Lazy import Data.Array.Base import Data.Array.ST import Data.Array.MArray instance MArray (STArray s) e (ST s) where newArray range e = strictToLazyST (newArray range e) newArray_ range = strictToLazyST (newArray_ range) unsafeRead arr i = strictToLazyST (unsafeRead arr i) unsafeWrite arr i e = strictToLazyST (unsafeWrite arr i e) \end{code} Cheers, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Proposal: deriving ShallowEq?
On Tue, Jul 19, 2005 at 08:16:35PM +1000, Ben Lippmeier wrote: Bulat Ziganshin wrote: reading GHC sources is always very interesting :) that is from GHC/Base.hs : getTag :: a - Int# getTag x = x `seq` dataToTag# x ! This is just what I was looking for, thankyou. My shallowEq function is now simply: shallowEq :: a - a - Bool shallowEq a b = getTag a ==# getTag b My project is already totally reliant on GHC, and this will save me the heartache of hacking DrIFT (which I was in the process of setting up when I saw this mail) into my makefile. Portability be damned! Ben. You might increase portability a bit by using import Data.Generics shallowEq :: Data a = a - a - Bool shallowEq x y = toConstr x == toConstr y it does introduce a dependency on Data though Groeten, Remi -- Nobody can be exactly like me. Even I have trouble doing it. pgpyTyB9kylSx.pgp Description: PGP signature ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] tuples and Show in GHC
On Mon, Mar 07, 2005 at 12:05:41AM +, Keean Schupke wrote: Daniel Fischer wrote: The Show instances for tuples aren't automatically derived, they are defined in GHC.Show. So somewhere there must be an end, probably the author(s) thought that larger tuples than quintuples aren't used often enough to bother. That's not a principled reason but a practical one, but it's good enough for me. If you need them frequently and don't want to define your own instances, complain. BTW, tuples are defined in Data.Tuple up to 62-tuples and Eq and Ord instances are derived up to 15-tuples. In Hugs, apparently they are only provided up to quintuples. Has there been any work done on declaring instances over all tuples? It seems the pattern occurs fairly often, and is quite simple to abstract. Keean. Which almost sounds like a hint to replace the current tuples by HLists in Haskell 2? ;) Something like: infixr 5 :*: data HNil = HNil data HList b = a :*: b = a :*: !b deriving (Eq, Ord) -- type () = HNil type (a,b) = a :*: b :*: HNil type (a,b,c) = a :*: b :*: c :*: HNil fst :: HList b = (a :*: b) - a fst (a:*:b) = a Where (x,y,z) is syntactic sugar for x :*: y :*: z :*: HNil in much the same way [x,y,z] is syntactic sugar for x:y:z:[]... It might even be (almost?) backward compatible AFAICS. Groeten, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] Showable mutually recursive (fixed-point) datatypes
[WARNING: braindamag(ed|ing) experience following] Hi all, a few days ago I decided I desperately needed a set which could contain (among others) itself. My first idea was module Main where import List import Monad data Elem s a = V a | R (s (Elem s a)) Now, a self-containing list can be defined as l :: [Elem [] Integer] l = [V 42, R [V 6, V 7], R l] As my brain could handle that, and I noticed quite some similiarity between Elem and Either, I decided to try to abstract the thing a little. This is what I ultimately came up with newtype Comp f g x = Comp (f (g x)) newtype Rec f = In (f (Rec f)) The idea is that `Elem s a' is basically just `Either a (s SELF)'. Then, instead of defining a special-purpose mutually-recursive fixed-point type, another type `Comp' is defined to compose two types into one, to enable the standard Fix/Mu/Rec type to be used. type RecCont s a= s (Either a (RecElem s a)) A recursive container is a container with simple elements (Left a) and recursive container-elements (Right (RecElem s a)) type RecElem s a= Rec (Comp s (Either a)) And a recursive container-element is, err, a slightly obscured recursive container. (s (Either a SELF)) el :: a - Either a (RecElem s a) el = Left rec :: RecCont s a - Either a (RecElem s a) rec = Right . In . Comp unRec :: RecElem s a - RecCont s a unRec (In (Comp f)) = f And indeed, a list (or set, or whatever) which contains itself is easily defined. s :: RecCont [] Integer s = [el 42, rec [el 6, el 7], rec s] The next step was to try to get it an instance of Show. Funny enough, around that time, Shin-Cheng Mu posed the question of how to make Rec an instance of Show[1], the (Haskell98) solution of which I had just found on the HaWiki.[2] class RecShow f where recShow :: Show a = f a - String instance RecShow f = Show (Rec f) where show (In f) = (In ( ++ recShow f ++ )) instance Show a = RecShow (Either a) where recShow = show However, I didn't just want some `Rec f' to be an instance of Show, I wanted `Rec (Comp f g)' to be an instance of Show. Which turned out not to be all that easy. My best solution works, but I hope someone has a better idea...? class CompShow f where compShow :: (Show a, RecShow g) = f (g a) - String instance (CompShow f, RecShow g, Show a) = Show (Comp f g a) where show (Comp f)= (Comp ( ++ compShow f ++ )) instance CompShow [] where compShow l = [ ++ (concat $ intersperse , $ map recShow l) ++ ] instance (CompShow f, RecShow g) = RecShow (Comp f g) where recShow = show Anyway, once this worked I just had to find some use for it ;) flatten :: (Monad s, Functor s) = RecCont s a - s a flatten = join . fmap (either return (flatten . unRec)) noI'mNotEvil:: Num a = a - RecCont IO a noI'mNotEvil n = do putStrLn $ showString Attempt # $ shows n $ : Hi, what's The Answer? s - getLine return $ if s == 42 then el n else rec (noI'mNotEvil (n+1)) main = do n - flatten (noI'mNotEvil 1) if n 1 then putStrLn Did that really have to take so long? else putStrLn Well done! [1] http://www.haskell.org//pipermail/haskell/2005-February/015325.html [2] http://www.haskell.org/hawiki/PreludeExts -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Point-free style
On Mon, Feb 14, 2005 at 03:55:01PM +0100, Lennart Augustsson wrote: Any definition can be made point free if you have a complete combinator base at your disposal, e.g., S and K. Haskell has K (called const), but lacks S. S could be defined as spread f g x = f x (g x) Given that large set of Haskell prelude functions I would not be surprised if spread could already be defined point free in Haskell. :) -- Lennart I hope this won't be considered cheating... import Control.Monad.Reader k :: a - b - a k = return s :: (a - r - b) - (a - r) - a - b s = flip (=) . flip Greetings, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] What is MonadPlus good for?
On Sun, Feb 13, 2005 at 08:58:29AM -0500, David Roundy wrote: I've been working on a typeclass that derives from MonadPlus which will encapsulate certain kinds of IO. With MonadPlus, you can write monadic code with exceptions and everything that may not be executed in the IO monad. You just use fail to throw exceptions, and mplus to catch them. class MonadPlus m = ReadableDirectory m where mInCurrentDirectory :: FilePath - m a - m a mGetDirectoryContents :: m [FilePath] mReadFilePS :: FilePath - m PackedString mReadFilePSs :: FilePath - m [PackedString] mReadFilePSs f = linesPS `liftM` mReadFilePS f One instance of this class is IO, but I can also have instances for in-memory data structures (outside the IO monad) or (or example) for reading a tarball from disk--which would be a monad that acts within the IO monad. According to http://www.haskell.org/hawiki/MonadPlus (see also the recent thread about MonadPlus) a MonadPlus instance should obey m mzero === mzero, which IO doesn't. IOW, the MonadPlus instance for IO (defined in Control.Monad.Error) probably shouldn't be there. Groeten, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] What is MonadPlus good for?
On Sun, Feb 13, 2005 at 01:31:56PM -0500, David Roundy wrote: On Sun, Feb 13, 2005 at 04:57:46PM +0100, Remi Turk wrote: According to http://www.haskell.org/hawiki/MonadPlus (see also the recent thread about MonadPlus) a MonadPlus instance should obey m mzero === mzero, which IO doesn't. IOW, the MonadPlus instance for IO (defined in Control.Monad.Error) probably shouldn't be there. True. In the IO monad there are side effects that don't get erased when a later action raises an exception as that law would suggest. But any IO-like monad that I'm likely to implement will have the same discrepancy, and in any IO code that catches enough exceptions to be bug-free will be immune to this issue. Basically, the issue is that do { writeFile foo bar; writeFile bar foo } `catch` \_ - putStr Couldn't create file\m may reach the putStr with or without the file foo existing, and there's no way to know whether or not it was created. But that just means the code was written sloppily--that is, if the existence of that foo file is important. In my uses of MonadPlus, I'd have other schemes essentially immitating IO, so they'd duplicate this behavior (later errors don't undo earlier actions), and well-written functions would depend on that. But what if `instance MonadPlus IO' disappears from the libraries some day? (which it should, IMO) It might be interesting to write a backtracking IO-like monad which obeyed m mzero === mzero. I imagine you could do it for something like an ACID database, if you define === as meaning has the same final result on the database, which of course would only be useful if the database had sufficient locking that it couldn't have been read between the original m and the later mzero. You might be interested in the recent STM monad then (Control.Concurrent.STM in GHC-6.4): `T' for Transactional. However, though it supports both MonadPlus and exceptions, it doesn't use MonadPlus for exceptions: It's used for blocking/retrying a thread/transaction. I never used it, so I'm not sure whether it makes any sense, but wouldn't MonadError be a better candidate class to base it upon? Greetings, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] What is MonadPlus good for?
On Sun, Feb 13, 2005 at 09:28:18PM +0100, Tomasz Zielonka wrote: On Sun, Feb 13, 2005 at 08:06:36PM +0100, Remi Turk wrote: You might be interested in the recent STM monad then (Control.Concurrent.STM in GHC-6.4): `T' for Transactional. However, though it supports both MonadPlus and exceptions, it doesn't use MonadPlus for exceptions: It's used for blocking/retrying a thread/transaction. And for non-deterministic choice. BTW, I have an implementation of STM based entirely on old concurrency primitives, which means that it will work in older GHC and probably in other Haskell compilers. I am going to put it on my web site, when I get one. Best regards Tomasz Cool :) Is it actually race/deadlock/othergeneralnastiness-free? (as the paper claims that e.g. mergeIO :: [IO a] - IO a is unimplementable in anything built on mutexes and condition variables.) -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] What is MonadPlus good for?
On Sun, Feb 13, 2005 at 10:33:06PM +0100, Tomasz Zielonka wrote: On Sun, Feb 13, 2005 at 10:25:49PM +0100, Remi Turk wrote: BTW, I have an implementation of STM based entirely on old concurrency primitives, which means that it will work in older GHC and probably in other Haskell compilers. I am going to put it on my web site, when I get one. Cool :) Is it actually race/deadlock/othergeneralnastiness-free? It should be, but there may be bugs of course. I know there are some possible space leaks, but that's also fixable. (as the paper claims that e.g. mergeIO :: [IO a] - IO a is unimplementable in anything built on mutexes and condition variables.) My STM monad is not IO, it has the same restrictions as STM in the paper. The paper doesn't claim you can't implement mergeSTM :: [STM a] - STM a mergeSTM = msum Ugh, I should've read what I copied... *nitpick* in the paper merge is defined using foldr1, which errors when given an empty list, as opposed to msum, which merely retries. Also, the STM in GHC 6.4 is written in C. Do you think that Haskell's IO monad lacks some things needed to write this thing? I can tell you there are some problems with types, but they can be solved in a more or less standard way. Best regards Tomasz I don't, though I'm probably not qualified to vote ;) Groeten, Remi P.S. And don't forget to post a link when you put it online. -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] What is MonadPlus good for?
On Sat, Feb 12, 2005 at 01:08:59PM -0500, Benjamin Pierce wrote: I have seen lots of examples that show how it's useful to make some type constructor into an instance of Monad. Where can I find examples showing why it's good to take the trouble to show that something is also a MonadPlus? (I know there are many examples of things that *are* MonadPluses; what I want to know is why this is interesting. :-) Thanks, - Benjamin As a start, free access to countless general functions as soon as you define a MonadPlus instance for your datatype. (Errr, `guard' and `msum', as long as one stays within the Haskell98 standard libraries ;) Groeten, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] What is MonadPlus good for?
On Sat, Feb 12, 2005 at 01:47:06PM -0500, Benjamin Pierce wrote: As a start, free access to countless general functions as soon as you define a MonadPlus instance for your datatype. (Errr, `guard' and `msum', as long as one stays within the Haskell98 standard libraries ;) Yes, those are good examples. (But I'd still be interested to see some of the countless others... :-) Thanks, - Benjamin Network.URI and Data.Generics also define a few functions which require MonadPlus instances. Can't find anything else right now. Nor do I know of the (countless? ;)) more theoretical reasons to define instances. -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Things to avoid (Was: Top 20 ``things'' to know in Haskell)
On Fri, Feb 11, 2005 at 11:14:40AM +0100, Henning Thielemann wrote: On Fri, 11 Feb 2005, Remi Turk wrote: 1) It's talking about the compiler having difficulty with some warnings when using guards. http://www.haskell.org//pipermail/haskell-cafe/2005-January/008290.html Simon Peyton-Jones wrote in http://www.haskell.org//pipermail/haskell-cafe/2005-January/008290.html GHC has -fwarn-incomplete-patterns and -fwarn-overlapped-patterns. But the code implementing these checks is old and crufty, and the warnings are sometimes a bit wrong -- at least when guards and numeric literals are involved. I think they are accurate when you are just using ordinary pattern matching. Does anyone know nice examples where it goes wrong? (And which could be added to the wiki.) I found the following case where GHC wrongly gives two warnings, but 1) it's a rather convoluted example and 2) it's - in general - probably undecidable anyway (fromInteger might execute arbitrary code): data Foo = Foo | Bar deriving (Eq, Show) instance Num Foo where fromInteger _ = Foo f :: Foo - Bool f 0 = True f Bar = False foo.hs:14: Warning: Pattern match(es) are overlapped In the definition of `f': f Bar = ... foo.hs:14: Warning: Pattern match(es) are non-exhaustive In the definition of `f': Patterns not matched: #x with #x `notElem` [0] BTW, what exactly does this mean? f x | odd x = ... | even x = ... GHC does complain. I would also call it Bad Code, but if it's what you mean, _this_ example should be in the wiki. Yes, your example is better. If no-one complains I'll remove the isPrime-part (which IMO doesn't demonstrate any guard-problems) and collapse it with the factorial-example (which does). 2) foo xs | length xs == 1 = bar (head xs) As already said in Don't ask for the length of a list, if you don't need it, this usage of length is bad in itself, and doesn't really help the argument against patterns IMO. I have seen it similarly in the example I give below at that page. So I found it worth noting that some guards can nicely be replaced by simple patterns. More examples are welcome. May be we should replace it by foo xs | not (null xs) = bar (head xs) vs. foo (x:_) = bar x Done. This example might be useful, too: foo x | x == 0 = blub x /= 0 = bla vs. foo 0 = blub foo _ = bla I agree, and so did Stephan Hohe, who added the factorial example ;) 3) the pattern guards extension. I have two objections against this one. First, I don't think it's a good idea to talk about a non-standard extension like pattern guards in a wiki about newbie-problems. It was given to me as a good example why Guards are invaluable: http://www.haskell.org//pipermail/haskell-cafe/2005-January/008320.html Ouch, that hurts. Though I hope I'm not blaspheming when I say I'd rather do without if-then-else (which I'm not using all that often and could easily replace by a function `if') than without guards. P.P.S. Does a piece about Avoid explicit lambda's stand any chance of not being removed? (Basically about \x y - x + y vs (+), and when it gets more complicated it probably deserves a name.) Nice! Done too. -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Things to avoid (Was: Top 20 ``things'' to know in Haskell)
On Wed, Feb 09, 2005 at 02:54:12PM +0100, Henning Thielemann wrote: On Wed, 9 Feb 2005, Henning Thielemann wrote: Is there also a Wiki page about things you should avoid? Since I couldn't find one, I started one on my own: http://www.haskell.org/hawiki/ThingsToAvoid I consider 'length', guards and proper recursion anchors. Oops, I just forgot a comment to my latest update: I added an example to illustrate the fromInteger-in-a-pattern case. -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Things to avoid (Was: Top 20 ``things'' to know in Haskell)
On Wed, Feb 09, 2005 at 02:54:12PM +0100, Henning Thielemann wrote: On Wed, 9 Feb 2005, Henning Thielemann wrote: Is there also a Wiki page about things you should avoid? Since I couldn't find one, I started one on my own: http://www.haskell.org/hawiki/ThingsToAvoid I consider 'length', guards and proper recursion anchors. Okay, I still definitely have some problems with the part about guards, and I'm going on bothering you about it because it's The HaWiki, and not just your site ;) First of all, I rarely combine multiple-defs with guards, and even more rarely omit an otherwise- or all-variables-and-no-guard case, so I may just have avoided all stated problems that way. Second, I don't have much experience with Haskell-newbies (besides my own (hopefully) past and the ones on the mailing lists), so my assumptions about common pitfalls may well be wrong. That said, the points I don't agree with: 1) It's talking about the compiler having difficulty with some warnings when using guards. In none of the examples given (the primes) I got any warnings, and from a quick made up example it appears that at least GHC is quite capable of detecting non-exhaustive patterns even when combining patterns and guards. In case you're talking about something like this: f x | odd x = ... | even x = ... GHC does complain. I would also call it Bad Code, but if it's what you mean, _this_ example should be in the wiki. (As in: blahblah, it actually _is_ exhaustive, but in general requires solving the halting-problem to prove or something like that ;) Also, when compiling them (even _without_ optimizations) the three examples yield _exactly_ the same code, except for the fact that the if-then-else example moves the n == 2 comparision to the RHS of the expression. This move can just as easy be done on the guarded version, which removes any difference in generated code/warnings. 2) foo xs | length xs == 1 = bar (head xs) As already said in Don't ask for the length of a list, if you don't need it, this usage of length is bad in itself, and doesn't really help the argument against patterns IMO. 3) the pattern guards extension. I have two objections against this one. First, I don't think it's a good idea to talk about a non-standard extension like pattern guards in a wiki about newbie-problems. (Unless in the sense of there are some compiler extensions which you probably won't need anytime soon.) Second, it's just horrible code: A useless violation of DRY (Don't Repeat Yourself). Groeten, Remi P.S. I _do_ agree with most of the other points ;) P.P.S. Does a piece about Avoid explicit lambda's stand any chance of not being removed? (Basically about \x y - x + y vs (+), and when it gets more complicated it probably deserves a name.) -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] FiniteMap-like module for unordered keys?
Ugh, replying to myself... Obviously, the following contains a few mistakes...: On Wed, Nov 10, 2004 at 11:34:32AM +0100, R. Turk wrote: {-# OPTIONS -fglasgow-exts #-} {- I want a Hashable instance for String ;) -} import Data.FiniteMap import Data.HashTable (hashInt, hashString) import Data.Int (Int32) class Hashable a where hash :: a - Hash instance Hashable Int where hash = hashInt instance Hashable String where hash = hashString type Hash = Int32 newtype HashTable a b = HT (FiniteMap Hash [b]) newtype HashTable a b = HT (FiniteMap Hash [(a,b)]) emptyHT :: HashTable a b emptyHT = HT emptyFM addToHT :: (Hashable a) = HashTable a b - a - b - HashTable a b addToHT (HT m) k v = HT $ addToFM_C (flip (++)) m (hash k) [v] addToHT (HT m) k v = HT $ addToFM_C (flip (++)) m (hash k) [(k,v)] -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Re: Arrows and Haskell
On Sat, Nov 06, 2004 at 11:49:45PM +0100, Peter Simons wrote: Plus, powerful abstractions that make the code look simple and elegant _always_ come at a price. An Arrow-based stream processor that performs the same task as my monadic BlockIO library does, for instance, results in a module that has half the size the StateT version does. Which is cool. But it is, as of now, also 10 times slower than the monadic version is. Which is not cool at all. That's indeed a rather high cost. Although I suspect that a lot more effort has gone into optimizing Monads than into optimizing Arrows... Cheers, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Making MVar and Chan Instances of Typeable
On Fri, Nov 05, 2004 at 01:57:53PM +0100, Benjamin Franksen wrote: Hello Experts, I need MVar and Chan to be instances of Typeable. Any hint on how this is most easily done would be greatly appreciated. I could change the libraries and add 'deriving Typeable' but I hesitate to do so. Cheers, Ben It can be done in Haskell 98 the same way `asTypeOf' is defined in the Report: instance Typeable a = Typeable (MVar a) where typeOf v= mkAppTy (mkTyCon Control.Concurrent.MVar.MVar) [typeOf (t v)] where t :: a b - b t = undefined Groetjes, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Are handles garbage-collected?
On Mon, Oct 25, 2004 at 08:46:41AM +0200, Ketil Malde wrote: Remi Turk [EMAIL PROTECTED] writes: IMO, [bracket] does indeed have those same drawbacks. (Although the traditional explicit memory management model is alloc/free, which is much worse than bracket/withFile) Isn't bracket more like stack allocated memory? And most problems with explicit memory management related to heap (as you indicate)? I think you're right. (WRT usage (only): AFAICS even Foreign.Marshal.Alloc.alloca doesn't actually use the stack.) The theoretical solution (and probably _only_ theoretical) is implementing a lot of garbage collectors: one for memory, one for open files, one for sockets, one for 3D polygon meshes etc etc... ...or have a number of available file handles that is limited by memory? :-) Would be nice if OSes actually worked that way. Then again, I don't think _everything_ can be made dependent only on available memory. Groetjes, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Are handles garbage-collected?
On Mon, Oct 25, 2004 at 02:14:28PM +0100, Simon Marlow wrote: On 24 October 2004 20:51, Sven Panne wrote: IMHO it would be best to use explicit bracketing where possible, and hope for the RTS/GC to try its best when one runs out of a given resource. Admittedly the current Haskell implementations could be improved a little bit in the last respect. Indeed, GHC could/should try to free up file descriptors when they run out. It's a bit tricky though. Hm, I'm not sure about the should. Garbage collection is meant for memory, and anything making that less clear makes people more likely to depend on incorrect assumptions. And redefining GC to be a collection of _all_ garbage, instead of just memory doesn't sound so fantastic either. At the moment performGC doesn't actually run any finalizers. It schedules a thread to run the finalizers, and you hope the thread runs soon. So if you're running performGC for the purposes of finalization, then almost certainly (performGC yield) is better. I've been wondering whether having a more synchronous kind of finalizer would be a good thing. Synchronous finalizers seem to be difficult to implement in e.g. the JVM, so may make a JVM-backend more difficult. (I'm thinking about how CPython vs Jython go about closing file-handles... CPython uses (primarily) reference-counting, so files get closed as soon as they aren't referenced anymore, which lots of people now depend on. Jython uses Java-GC, so some CPython programs may suddenly fail...) Nevertheless, I agree with the general sentiment on this thread that file descriptors shouldn't be treated as a resource in the same way as memory. Cheers, Simon Groeten, Remi P.S. Why do so many people (including me) seem to come to Haskell from Python? It can't be just the indentation, can it? ;) -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Are handles garbage-collected?
On Mon, Oct 25, 2004 at 09:28:23PM +0200, Tomasz Zielonka wrote: On Mon, Oct 25, 2004 at 08:55:46PM +0200, Remi Turk wrote: P.S. Why do so many people (including me) seem to come to Haskell from Python? It can't be just the indentation, can it? ;) How many? I don't. Best regards, Tom At least one. (Me) And, judging from the amount of references to Python in these mailing-lists, I really doubt I'm the only one. I actually met Haskell mostly by reading about it in the python mailinglist/newsgroup. (in e.g. Alex Martelli's posts) Someone else (who shall remain anonymous. SCNR) wrote: Speculation I'm afraid to post: People are drawn to Python because they hear it is a clean language, but slowly find that it's really pretty messy internally. Haskell is beautiful on the outside and the inside. :-) The last sentence I can definitely agree with, but I'm not so sure Python really is that messy. (Messier-than-Haskell sure, but messy? ;o) Groetjes, Remi P.S. Hm, it _is_ haskell-cafe, but maybe it's about time for a [Off-topic] note? ;) -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Are handles garbage-collected?
On Sun, Oct 24, 2004 at 12:19:59PM -0700, Conal Elliott wrote: I'm puzzled why explicit bracketing is seen as an acceptable solution. It seems to me that bracketing has the same drawbacks as explicit memory management, namely that it sometimes retains the resource (e.g., memory or file descriptor) longer than necessary (resource leak) and sometimes not long enough (potentially disastrous programmer error). Whether the resource is system RAM, file descriptors, video memory, fonts, brushes, bitmaps, graphics contexts, 3D polygon meshes, or whatever, I'd like GC to track the resource use and free unused resources correctly and efficiently. Cheers, - Conal IMO, it does indeed have those same drawbacks. (Although the traditional explicit memory management model is alloc/free, which is much worse than bracket/withFile) However, Garbage Collection is usually based only on memory. Using GC for file-handle-closing therefore means that one will close garbage file-handles when memory is getting low, instead of when file-handles are almost used up... The theoretical solution (and probably _only_ theoretical) is implementing a lot of garbage collectors: one for memory, one for open files, one for sockets, one for 3D polygon meshes etc etc... Greetings, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Subsequence near solved hopefully
On Sun, Oct 17, 2004 at 07:16:51AM -0700, Peter Stranney wrote: equalString :: String - String - Bool equalString [] [] = True equalString [] (c':s') = False equalString(c:s) [] = False equalString(c:s)(c':s') = equalChar c c'^ equalString s s' ^^ this function is to see if one string is equal to another. but when i compile this i get the error; - Instance of Integral Bool required for definition of equalString You are using the raise-to-the-power-of operator, which requires it's second parameter to be Integral... (^) :: (Integral b, Num a) = a - b - a You might also want to look at the earlier `any prefix of tails' suggestion, as it makes the solution a rather simple one-liner. Good luck, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Subsequence near solved hopefully
On Sun, Oct 17, 2004 at 08:05:09PM +0200, Ketil Malde wrote: Remi Turk [EMAIL PROTECTED] writes: You might also want to look at the earlier `any prefix of tails' suggestion, as it makes the solution a rather simple one-liner. Wouldn't that be looking for a sub*string*, and not a (general) sub*sequence* (which I think does not have to be contigous?) Hm, not substring as in String at least, but that solution does give the following results: Prelude List sub ell hello True Prelude List sub [3..5] [1..10] True Prelude List sub [2,4] [1..5] False Prelude List sub [2..6] [1..5] False Do you mean subset with subsequence? Groetjes, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Subsequence near solved hopefully
On Sun, Oct 17, 2004 at 11:41:59AM -0700, Peter Stranney wrote: Thanks guys for all your help, finally through code, sweat and tears i have found the solution; isSubStrand:: String - String - Bool isSubStrand [] [] = True isSubStrand [] (y:ys) = False isSubStrand (x:xs) [] = False isSubStrand (x:xs) (y:ys) | length(x:xs)length(y:ys) = False | take (length (x:xs)) (y:ys)==(x:xs) = True | otherwise = isSubStrand (x:xs) ys thanks again Peter Stranney Now that you found it, we might as well tell you the other solution: import List -- Point-free (beware of the monomorphism-restriction) isSubStrand' :: Eq a = [a] - [a] - Bool isSubStrand' = flip (.) tails . any . isPrefixOf -- and point-full isSubStrand'' x y = any (x`isPrefixOf`) (tails y) Groetjes, Remi feeling mean Turk -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Subsequence near solved hopefully
On Sun, Oct 17, 2004 at 10:10:44PM +0200, Ketil Malde wrote: Remi Turk [EMAIL PROTECTED] writes: Do you mean subset with subsequence? No, since a set isn't ordered. I would say a subset needs to contain some of the elements of the superset, a subsequence needs to contain some elements of the supersequence in the same order, and a substring (for lack of a better term) is a contigous subsequence. But I may be wrong. Agreeing on terminology is always nice :D at least http://en.wikipedia.org/wiki/Subsequence seems to agree with you. In which case both Peter Stranney's and my solutions fail. Groetjes, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Re: Subsequence near solved hopefully
On Sun, Oct 17, 2004 at 10:53:37PM +0100, Sam Mason wrote: Peter Simons wrote: This version should do it: isSubSeq :: (Eq a) = [a] - [a] - Bool isSubSeq [] _= True isSubSeq _ []= False isSubSeq (x:xs) (y:ys) | x == y= isSubSeq xs ys I think you want to refer to List.isPrefixOf here - your version is a sort of ordered subset test. I.e. I get: abc `isSubSeq` .a.b.c. === True as Ketil pointed out, this subsequence test may be exactly what the OP meant. My version would've been: isSubSeq x = any (isPrefixOf x) . tails But Remi beat me to it (and for that I'll never forgive him! :-). Sam But I only gave the point-free and the point-wise version: You did the half-of-a-point version ;) (which I would actually have used myself too) *ducks and runs*[1] Groetjes, Remi [1] and falls asleep -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] puzzle: prove this floorSqrt correct
On Thu, Aug 12, 2004 at 06:59:26PM +0200, Christian Sievers wrote: [EMAIL PROTECTED] wrote: -- Here's the discrete version of Newton's method for finding -- the square root. Does it always work? Any literature? I recently used, without range check, sqrtInt n = help n where help x = let y = ((x + (n `div` x)) `div` 2) in if yx then help y else x I usually (each time I urgently need to calculate primes ;)) use a simple intSqrt = floor . sqrt . fromIntegral (which will indeed give wrong answers for big numbers) following p. 38f of Henri Cohen, A Course in Computational Algebraic Number Theory, where a proof and a suggestion for improvement (choose a better start value) is given. Your version should be correct as well. As far as I know, ghc uses gmp, so I wonder if there is access to functions like mpz_sqrt or mpz_perfect_square_p. there isn't. And on glasgow-haskell-users there is a thread about (a.o.) that subject right now :) Greetings, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] puzzle: prove this floorSqrt correct
On Thu, Aug 12, 2004 at 09:01:03PM +0200, Henning Thielemann wrote: On Thu, 12 Aug 2004, Remi Turk wrote: I usually (each time I urgently need to calculate primes ;)) use a simple intSqrt = floor . sqrt . fromIntegral (which will indeed give wrong answers for big numbers) If I urgently need factors of an integer I check factor*factor n rather than factor intSqrt n. :-] but you'll have to (^2) once every iteration. The following code only has to sqrt once. Oh, the joy of premature optimization. Or even premature coding ;) -- Will lie when given stupid questions isPrime 1 = False isPrime 2 = True isPrime n = not $ any (n`isDivBy`) (2:[3,5..intSqrt n]) where n `isDivBy` d = n `rem` d == 0 intSqrt = floor . sqrt . fromIntegral -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Sets and Monads and comprehensions
On Tue, Jul 20, 2004 at 04:42:24PM +0100, Graham Klyne wrote: I found myself treading a path which led me to asking the same question as [1]. Given the answer [2], I'd like to stand back a little and ask if there's another way to tackle my niggle: what I'm interested in is a set comprehension expression that is analogous to a list comprehension expression; e.g. in: Though I do not have an answer for you, I do occasionally feel the need (ehm, need is a bit too strong a word) for some-kind-of-collection-comprehensions too. Also, GHC has the parallel array extension which adds array-comprehensions; although I think it's impossible to fit in haskell 98, it would be nice to have some general mechanism on which collection-comprehensions (and enumerations: [1..5], [:1..5:], ...) could be based. Groetjes, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] In relation to shuffling
On Thu, Jul 08, 2004 at 11:44:38PM +0100, Alastair Reid wrote: [snip] We can do better though. Using two functions in System.Random, it's easy to get an infinite list of random numbers: randomRsIO :: IO [Int] randomRsIO = do g - getStdGen return (randoms g) [snip] Except that AFAICS, getStdGen gives you _the_ standard PRNG which means that you shouldn't use it (the standard PRNG) anymore afterwards, or you'll get repeated numbers: (getStdGen returns the current state without changing it) -- Return the current state and use it Prelude Random getStdGen = print . take 10 . randomRs (0,9::Int) [4,5,9,0,9,5,6,3,5,3] -- Return use it again and you'll get the _same answers_ Prelude Random getStdGen = print . take 10 . randomRs (0,9::Int) [4,5,9,0,9,5,6,3,5,3] -- getStdRandom is a special use-and-consume function Prelude Random (sequence $ replicate 10 $ getStdRandom $ randomR (0,9::Int)) = print [4,5,9,0,9,5,6,3,5,3] -- Finally: the last getStdRandom _did_ change the PRNG state Prelude Random (sequence $ replicate 10 $ getStdRandom $ randomR (0,9::Int)) = print [1,5,0,7,8,6,6,4,4,1] newStdGen splits the current state (using one as the new stdGen and returning the other), which probably _is_ what you want. Except that I have no idea what hidden costs splitting random number generators have :) (anyone?) Prelude Random newStdGen = print . take 10 . randomRs (0,9::Int) [4,9,9,2,3,2,9,6,9,3] Prelude Random newStdGen = print . take 10 . randomRs (0,9::Int) [5,1,5,5,9,0,8,6,2,1] Prelude Random (sequence $ replicate 10 $ getStdRandom $ randomR (0,9::Int)) = print [2,0,1,5,2,5,6,0,4,7] Prelude Random (sequence $ replicate 10 $ getStdRandom $ randomR (0,9::Int)) = print [9,9,2,7,2,5,3,4,0,0] Prelude Random Groeten, Remi -- Nobody can be exactly like me. Even I have trouble doing it. ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: More type design questions
On Mon, Aug 18, 2003 at 07:33:47PM +0200, Konrad Hinsen wrote: Well, yes, because my original example was cut down to illustrate the problem I had. The full version of the class Vect is class Vect v a where (+) :: Floating a = v a - v a - v a (-) :: Floating a = v a - v a - v a (*) :: Floating a = a - v a - v a I need the parametrization on a in order to be able to define the type of scalar multiplication. Would this suffice? module Foo where class Vect v a | v - a where (+), (-):: Floating a = v - v - v (*) :: Floating a = a - v - v data Vector a = Vector a a a deriving (Show) instance Vect (Vector a) a where (+) = fzipWith (+) (-) = fzipWith (-) (*) = fmap . (*) instance Vect [Vector a] a where (+) = zipWith (+) (-) = zipWith (-) (*) = fmap . (*) instance Functor Vector where fmap f (Vector x y z) = Vector (f x) (f y) (f z) class Functor z = Ziptor z where fzipWith:: (a - b - c) - z a - z b - z c instance Ziptor Vector where fzipWith f (Vector x1 y1 z1) (Vector x2 y2 z2) = Vector (f x1 x2) (f y1 y2) (f z1 z2) Hm, did anyone else ever want a Ziptor class? (I didn't, until now ;)) Happy hacking, Remi -- Nobody can be exactly like me. Even I have trouble doing it. pgp0.pgp Description: PGP signature
Re: Case expressions, matching, and constants
On Thu, Jul 17, 2003 at 12:03:19PM +0100, Bayley, Alistair wrote: This is what I've turned it into to get it to work. It seems a bit clumsy; is there a better way to write this? test n = case True of _ | n == one - one | n == two - two | otherwise - three Or you might want to use something like this: (depending on how much your example resembles the actual code and the number of variables you want to match) module Main where one = 1 two = 2 test n = maybe d id (n `lookup` m) where m = [(one,one) ,(two,two) ] d = three -- Nobody can be exactly like me. Even I have trouble doing it. pgp0.pgp Description: PGP signature
Re: Lazy streams and unsafeInterleaveIO
On Mon, Dec 23, 2002 at 09:05:00AM +, Glynn Clements wrote: Jyrinx wrote: So is this lazy-stream-via-unsafeInterleaveIO not so nasty, then, so long as a few precautions (not reading too far into the stream, accounting for buffering, etc.) are taken? I like the idiom Hudak uses (passing a stream of I/O results to the purely functional part of the program), so if it's kosher enough I'd like to get hacking elsewhere ... It depends upon the amount and the complexity of the program's I/O, and the degree of control which you require. For a simple stream filter (read stdin, write stdout), lazy I/O is fine; for a program which has more complex I/O behaviour, lazy I/O may become a nuisance as the program grows more complex or as you need finer control. Hi, just for fun I wrote a slightly-enhanced version of my previous one-liner ;o) It needs to be compiled with GHC's -package util as it uses GNU Readline. I guess it demonstrates why lazy io may not always be a good idea when doing more complex things with IO. Happy hacking, Remi P.S. Have fun with forward-references as program-input ;-D P.P.S. GNU Readline implements history-functions itself of course. Who talked about reinventing the wheel? :D module Main where import Monad (liftM, zipWithM_) import Maybe (catMaybes, isJust) import Readline (readline) import System.IO.Unsafe (unsafeInterleaveIO) -- Like the prelude-function sequence, but lazy lazySequenceIO :: [IO a] - IO [a] lazySequenceIO [] = return [] lazySequenceIO (p:ps) = do x - unsafeInterleaveIO p unsafeInterleaveIO $ liftM (x:) (lazySequenceIO ps) {- Given a list of prompts, read lines with GNU Readline until either we've had all prompts or the users presses ^D -} readLines :: [String] - IO [String] readLines = liftM (catMaybes . takeWhile isJust) . lazySequenceIO . map (unsafeInterleaveIO . readline) main= do putStrLn NAdd the number N putStrLn enter Again putStrLn !N Repeat input N putStrLn ?N Enter result N as input input - readLines $ map (\n - show n ++ ) [0..] let output = scanl1 (+) $ zipWith (parse input output) [0..] input zipWithM_ printRes [0..] output where printResult :: Integer - Integer - IO () printResult nr res = putStrLn $ show nr ++ : ++ show res parse :: [String] - [Integer] - Int - String - Integer parse input output nr s = let p nr s -- last number again | null s= p (nr-1) (input !! nr) -- repeat input N | head s == '!' = let index = read (tail s) in p index (input !! index) -- enter result N | head s == '?' = let index = read (tail s) in output !! index -- just a number | otherwise = read s in p nr s -- Diese Augen haben es gesehen Doch diese Augen schliessen sich Und ungehindert fliesst das Blut Und das Schweigen wird unerträglich laut ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: Lazy streams and unsafeInterleaveIO
On Sun, Dec 22, 2002 at 04:00:45AM -0800, Jyrinx wrote: As an experiment for a bigger project, I cooked up a simple program: It asks for integers interactively, and after each input, it spits out the running total. The wrinkle is that the function for calculating the total should be a non-monadic stream function (that is, type [Integer] - [Integer] so that runningTotals [1,2,3,4,5] == [1,3,6,10,15]). The task is then to write a function to return a stream of integers, grabbing them from IO-land lazily (a la getContents). Hi, what about module Main where main= getContents = mapM_ print . scanl1 (+) . map read . lines Happy hacking, Remi -- Diese Augen haben es gesehen Doch diese Augen schliessen sich Und ungehindert fliesst das Blut Und das Schweigen wird unerträglich laut ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: how to debug?
On Sun, Oct 06, 2002 at 07:57:18PM +, Zdenek Dvorak wrote: Hello, How does one debug in haskell? I have a function that I could swear should behave differently than it does, and after tracking down bugs for many hours, I'm wondering if there's any way to step through the evaluation of a haskell function? -- other way (safer, but slower to learn and use) is to use Hood library Which can be found at http://haskell.cs.yale.edu/hood/ I have not really used it but it looks cool ;) It is tested with 4.08 and needed a few changes to work with 5.04 but nothing really difficult. Happy hacking Remi -- Diese Augen haben es gesehen Doch diese Augen schliessen sich Und ungehindert fliesst das Blut Und das Schweigen wird unerträglich laut msg02057/pgp0.pgp Description: PGP signature