From stephen.tetley at gmail.com Tue Dec 1 04:50:12 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Tue Dec 1 04:25:02 2009 Subject: [Haskell-beginners] Tips for a FFI-wrapped C library? In-Reply-To: <5fdc56d70912010146w5ce911e6kb9b83986a28485f1@mail.gmail.com> References: <5fdc56d70912010146w5ce911e6kb9b83986a28485f1@mail.gmail.com> Message-ID: <5fdc56d70912010150m75edfc99oe5613738d4200066@mail.gmail.com> Apologies - typo in copy pasted code - the last line should have been else funAction thing withNewThing :: Init_param1 -> Init_param2 -> (Thing -> IO a) -> IO a withNewThing param1 param2 funAction = bracket (newThing param1 param2) destroyThing (\thing -> do { check_null <- isNullThing thing ; if check_null then do -- SOME FAILURE -- else funAction thing }) 2009/12/1 Stephen Tetley : > withNewThing :: Init_param1 -> Init_param2 -> (Thing -> IO a) -> IO a > withNewThing param1 param2 funAction = > bracket (newThing param1 param2) destroyThing > (\thing -> do { check_null <- isNullThing thing > ; if check_null > then do -- SOME FAILURE -- > else funAction face }) From stephen.tetley at gmail.com Tue Dec 1 04:46:10 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Tue Dec 1 04:26:59 2009 Subject: [Haskell-beginners] Tips for a FFI-wrapped C library? In-Reply-To: References: Message-ID: <5fdc56d70912010146w5ce911e6kb9b83986a28485f1@mail.gmail.com> Hi Patrick One thing you can do is use `bracket` to manage the lifetime of objects created on the C side: withNewThing :: Init_param1 -> Init_param2 -> (Thing -> IO a) -> IO a withNewThing param1 param2 funAction = bracket (newThing param1 param2) destroyThing (\thing -> do { check_null <- isNullThing thing ; if check_null then do -- SOME FAILURE -- else funAction face }) -- newThing destroyThing isNullThing are defined somewhere. This might be appropriate for the Context, Language etc. objects in your library. For the documentation on bracket see Control.Exception.Base. Best wishes Stephen From patrick.leboutillier at gmail.com Tue Dec 1 10:48:50 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Tue Dec 1 10:23:36 2009 Subject: [Haskell-beginners] Typeclass question Message-ID: Hi all, I want to make all types that are instances of Integral instances of another type class, i.e: {-# LANGUAGE FlexibleInstances #-} class Intable a where toInt :: a -> Int instance (Integral a) => Intable a where toInt l = fromIntegral l However this gives the following error that I don't understand: q.hs:6:0: Constraint is no smaller than the instance head in the constraint: Integral a (Use -XUndecidableInstances to permit this) In the instance declaration for `Intable a' Can anyone offer insight on thie error? Also, is there perhaps a different way to do what I want to do? Thanks, Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From stephen.tetley at gmail.com Tue Dec 1 11:40:21 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Tue Dec 1 11:15:07 2009 Subject: [Haskell-beginners] Typeclass question In-Reply-To: References: Message-ID: <5fdc56d70912010840p269b32d1va0478f0e8f52cb25@mail.gmail.com> Hi Patrick As you guessed, adding UndecidableInstances pragma would make it work. Loosely speaking, the type of your instance 'contains' all the types that the class can use anyway. Hopefully, someone more learned than me will give a proper definition and add an explanation of the Paterson Conditions. http://www.haskell.org/ghc/docs/latest/html/users_guide/type-class-extensions.html#undecidable-instances But why not just a function: toInt :: Integral a => a -> Int toInt = fromIntegral Of course just a function won't be ideal if you were wanting to have a special instance say for Integer and all other instances to use the general version. There's more to say about this in the context of Generics, but that's a somewhat advanced topic... Best wishes Stephen From k.srikanth.opensource at gmail.com Tue Dec 1 12:08:43 2009 From: k.srikanth.opensource at gmail.com (Srikanth K) Date: Tue Dec 1 11:43:29 2009 Subject: [Haskell-beginners] how to define records containing finite length lists. Message-ID: Hi, I want to define a record say "Student". The 'C' equvivalent for the same could be struct Person { char name[10] int age } The closest I can find for doing such a thing in haskell appears to be data Person = Person{ name :: [char] age :: Int } I have not yet been able to find a suitable way to specify the constraint on the length of list(name in this case). So can someone let me know how we can impose this length constratint on the list and derive a new type. If standard haskell doesn't give this flexibility, are there any extensions in ghc to achieve the same. - Srikanth -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091201/26f62c2c/attachment.html From stephen.tetley at gmail.com Tue Dec 1 13:26:45 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Tue Dec 1 13:01:30 2009 Subject: [Haskell-beginners] how to define records containing finite length lists. In-Reply-To: References: Message-ID: <5fdc56d70912011026q6b9a9447rf4f900a52123ad80@mail.gmail.com> Choices, choices... Firstly, C uses an array not a list so you can too: > data Person = Person{ > name :: UArray Int Char, > age :: Int > } > deriving (Show) Of course there is no bound on the type to be of length 10, the length would be bound at creation time: > stephen = Person { name = array (0,9) (zip [0..] "stephen") > , age = 0 > } Quite horrible - but not significantly worse than C unless you believe the array size declator is defining the array type rather than just its storage size. Hmm. Sized types are a possibility but are quite advanced, certainly they give more 'static guarantees' than C provides (or just about anything else except dependent-types...). One example is here e.g: http://hackage.haskell.org/package/sized-types Tuples are another possibility but quite unwieldy: no special syntax, you would need to write conversion functions: > type Name = (Char,Char,Char,Char,Char,Char,Char,Char,Char,Char) You could wrap a String inside a newtype and provide a special constructor, hiding the Name10 constructor via a module: > newtype Name10 = Name10 { getName10 :: String } > makeName10 :: String -> Name10 > makeName10 s | length s > 10 = Name10 $ take 10 s > | otherwise = Name10 s -- pad if you like here Essentially it depends what you want to do with the sized string - generally you will loose string syntax[*] and all the list processing functions that work on strings as they are just lists of Char. This might not be a good balance for the safety you want. Best wishes Stephen [*] But you can overload string syntax for nefarious purposes (adding more complexity): http://www.haskell.org/ghc/docs/latest/html/users_guide/type-class-extensions.html#overloaded-strings 2009/12/1 Srikanth K : > Hi, > ?? I want to define a record say "Student".? The?'C' equvivalent for the > same could be > > struct Person { > ???? char name[10] > ???? int age } > > The closest I can find for doing such a thing in haskell appears to be > > data Person = Person{ > ???? name :: [char] > ???? age :: Int > } > > I have not yet been able to find a suitable way to specify the constraint on > the length of list(name in this case). > So can?someone let me know how we can impose this?length constratint?on the > list ?and derive a new type. > > If standard haskell doesn't give this flexibility, are?there any extensions > in ghc to achieve the same. > - Srikanth > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > From byorgey at seas.upenn.edu Tue Dec 1 14:24:17 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Tue Dec 1 13:59:03 2009 Subject: [Haskell-beginners] Typeclass question In-Reply-To: References: Message-ID: <20091201192417.GA22621@seas.upenn.edu> On Tue, Dec 01, 2009 at 10:48:50AM -0500, Patrick LeBoutillier wrote: > Hi all, > > I want to make all types that are instances of Integral instances of > another type class, i.e: > > > {-# LANGUAGE FlexibleInstances #-} > > class Intable a where > toInt :: a -> Int > > instance (Integral a) => Intable a where > toInt l = fromIntegral l This doesn't mean what you think it means. To do instance selection, (GHC at least) only looks at the part AFTER the =>. So instead of meaning "every type which is an instance of Integral should also be an instance of Intable", it actually means "every type is an instance of Intable; and oh yes, they had better be an instance of Integral too". This can make a big difference. For example, this may look fine, but it is not legal: instance (Integral a) => Intable a where toInt l = fromIntegral l instance (Fractional a) => Intable a where toInt l = round l This looks like it should be OK as long as we never use a type which is an instance of both Integral and Fractional (which is not likely). However, these instances are actually overlapping since the part before the => is not considered when deciding which instance to pick for a particular type. This also hints at an explanation for the error you got. When resolving the use of a type class method, GHC looks at the structure of the type in order to pick a type class instances to use. Once it has chosen an instance (by comparing the type to the part of the instance declaration to the right of the =>), it then considers any additional constraints generated by the left-hand side of the =>, and needs to choose a type class instance for each of those, and so on recursively. The danger is that this process might not terminate; in order to (conservatively) guard against this, GHC requires that any types mentioned on the left-hand side of the => are structurally smaller than types on the right-hand side; this ensures that the process will eventually terminate since types are finite. If you want to disable this check (and therefore introduce the possibility of an inifnitely recursing type checker) you can enable UndecidableInstances --- which isn't really as bad as some people make it out to be, but best avoided unless you really understand why you want it. It's hard to suggest what to do instead without knowing more about what you are specifically trying to do (it seems that your example was just a toy example to illustrate the problem), but you might consider using newtype wrappers. -Brent From Christian.Maeder at dfki.de Wed Dec 2 13:43:36 2009 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Wed Dec 2 13:18:18 2009 Subject: [Haskell-beginners] Re: how to define records containing finite length lists. In-Reply-To: References: Message-ID: <4B16B558.4020504@dfki.de> Srikanth K schrieb: > Hi, > I want to define a record say "Student". The 'C' equvivalent for the > same could be > > struct Person { > char name[10] > int age } > > The closest I can find for doing such a thing in haskell appears to be > > data Person = Person{ > name :: [char] > age :: Int > } you would use: data Person = Person { name :: String , age :: Int } Note the "," and the capital first letter for types. > I have not yet been able to find a suitable way to specify the > constraint on the length of list(name in this case). > So can someone let me know how we can impose this length constratint on > the list and derive a new type. > > If standard haskell doesn't give this flexibility, are there any > extensions in ghc to achieve the same. The flexibility lies in not fixing the maximal size! HTH Christian From jack at realmode.com Wed Dec 2 19:47:54 2009 From: jack at realmode.com (I. J. Kennedy) Date: Wed Dec 2 19:22:36 2009 Subject: [Haskell-beginners] Eq a => [a]->[a] Message-ID: <1008bfc90912021647i44d12cdev4aae486794a713ba@mail.gmail.com> I am looking for a function f::Eq a => [a]->[a] that takes a list and returns the longest initial segment of the list for which all the elements are distinct. For example f [2,3,6,4,3,5] = [2,3,6,4]. I didn't see anything that matched using Hoogle, but I thought this might be a common enough operation that this function might exists somewhere in the standard packages. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091202/901cb706/attachment.html From byorgey at seas.upenn.edu Wed Dec 2 21:46:43 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Wed Dec 2 21:21:23 2009 Subject: [Haskell-beginners] Eq a => [a]->[a] In-Reply-To: <1008bfc90912021647i44d12cdev4aae486794a713ba@mail.gmail.com> References: <1008bfc90912021647i44d12cdev4aae486794a713ba@mail.gmail.com> Message-ID: <20091203024643.GA28582@seas.upenn.edu> On Wed, Dec 02, 2009 at 06:47:54PM -0600, I. J. Kennedy wrote: > I am looking for a function > f::Eq a => [a]->[a] > that takes a list and returns the longest > initial segment of the list for which all > the elements are distinct. > > For example f [2,3,6,4,3,5] = [2,3,6,4]. > > I didn't see anything that matched using Hoogle, > but I thought this might be a common enough > operation that this function might exists somewhere > in the standard packages. Not that I know of. Here's how I would implement it (although you may enjoy trying to implement it yourself): import qualified Data.Set as S f xs = map fst $ takeWhile (uncurry S.notMember) (zip xs cums) where cums = scanl (flip S.insert) S.empty xs It works by incrementally building up a list of sets of the elements found in prefixes of the list (with scanl), then goes down the list (takeWhile) checking that each element isn't already in the corresponding set of elements. -Brent From builes.adolfo at googlemail.com Wed Dec 2 22:06:43 2009 From: builes.adolfo at googlemail.com (Adolfo Builes) Date: Wed Dec 2 21:41:24 2009 Subject: [Haskell-beginners] From Functional Dependencies to Type Families In-Reply-To: References: Message-ID: > {-# OPTIONS -fglasgow-exts #-} > > module VarArg where > import Data.FiniteMap -- for an example below > > class BuildList a r | r-> a where > build' :: [a] -> a -> r > > instance BuildList a [a] where > build' l x = reverse$ x:l > > instance BuildList a r => BuildList a (a->r) where > build' l x y = build'(x:l) y > > --build :: forall r a. (BuildList a r) => a -> r > build x = build' [] x I'm trying to replace the code below to work with type families, I started out replacing the definition of class with : class BuildList r where type Build r build' :: [Build r] -> Build r -> r follow by the instance for [a] resulting in instance BuildList [a] where type Build [a] = a build' l x = reverse $ x:l Until here, everything is working, and I'm able to do > build' [2,3,4] 1 :: [Integer] > [4,3,2,1] then I move on to the next instance (a -> r) with instance BuildList r => BuildList (a-> r) where type Build (a -> r) = a build' l x = \ y -> build'(x:l) y But I get the following error Couldn't match expected type `Build r' against inferred type `a' `a' is a rigid type variable bound by the instance declaration at /home/adolfo/foo.hs:347:35 In the first argument of `(:)', namely `x' In the first argument of `build'', namely `(x : l)' In the expression: build' (x : l) y then I try with : instance BuildList r => BuildList (a-> r) where type Build (a -> r) = Build r build' l x = \ y -> build'(x:l) y And I get Couldn't match expected type `a' against inferred type `Build r' `a' is a rigid type variable bound by the instance declaration at /home/adolfo/foo.hs:347:35 Expected type: [Build r] Inferred type: [Build (a -> r)] In the second argument of `(:)', namely `l' In the first argument of `build'', namely `(x : l)' I have been trying to figure out, which type should it be, but I haven't found the correct one, any ideas ? Thanks - Adolfo Builes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091202/f4eb7a3c/attachment.html From stephen.tetley at gmail.com Thu Dec 3 04:38:48 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Thu Dec 3 04:13:32 2009 Subject: [Haskell-beginners] From Functional Dependencies to Type Families In-Reply-To: References: Message-ID: <5fdc56d70912030138r3e70e1adw757e90e8768d74d3@mail.gmail.com> Hi Adolfo This is quite a tricky one and I haven't got a proper answer (hopefully someone will come along with one soon). But I've an initial observation: Longhand (i.e. without the type class - but relying on previously defined instances) the type family version of buildlist on functions is: buildList_fun l x = \y -> build' (x:l) y Asking for the type at the GHCi prompt gives: buildList_fun :: (BuildList r) => [Build r] -> Build r -> Build r -> r Whereas for the fun dep version build_fun l x y = build' (x:l) y The type is: build_fun :: (BuildList a r) => [a] -> a -> a -> r Crucially the last part of the type is r. Why you can't type your TF version seems to be because the answer type of the continuation is fixed to a not r. (the fun dep version is also a multi parameter class so you are allowed a different answer type). [I'm calling out to the gallery for help at this point!]. Best wishes Stephen From daniel.is.fischer at web.de Thu Dec 3 06:30:08 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Dec 3 06:06:16 2009 Subject: [Haskell-beginners] From Functional Dependencies to Type Families In-Reply-To: References: Message-ID: <200912031230.08486.daniel.is.fischer@web.de> Am Donnerstag 03 Dezember 2009 04:06:43 schrieb Adolfo Builes: > > {-# OPTIONS -fglasgow-exts #-} > > > > module VarArg where > > import Data.FiniteMap -- for an example below > > > > class BuildList a r | r-> a where > > build' :: [a] -> a -> r > > > > instance BuildList a [a] where > > build' l x = reverse$ x:l > > > > instance BuildList a r => BuildList a (a->r) where > > build' l x y = build'(x:l) y > > > > --build :: forall r a. (BuildList a r) => a -> r > > build x = build' [] x > > I'm trying to replace the code below to work with type families, I started > out replacing the definition of class with : > > class BuildList r where > type Build r > build' :: [Build r] -> Build r -> r > > follow by the instance for [a] resulting in > > instance BuildList [a] where > type Build [a] = a > build' l x = reverse $ x:l > > Until here, everything is working, and I'm able to do > > > build' [2,3,4] 1 :: [Integer] > > [4,3,2,1] > > then I move on to the next instance (a -> r) with > > instance BuildList r => BuildList (a-> r) where > type Build (a -> r) = a > build' l x = \ y -> build'(x:l) y > > > But I get the following error > > Couldn't match expected type `Build r' against inferred type `a' > `a' is a rigid type variable bound by > the instance declaration at /home/adolfo/foo.hs:347:35 > In the first argument of `(:)', namely `x' > In the first argument of `build'', namely `(x : l)' > In the expression: build' (x : l) y > > then I try with : > > instance BuildList r => BuildList (a-> r) where > type Build (a -> r) = Build r > build' l x = \ y -> build'(x:l) y > > > And I get > > Couldn't match expected type `a' against inferred type `Build r' > `a' is a rigid type variable bound by > the instance declaration at /home/adolfo/foo.hs:347:35 > Expected type: [Build r] > Inferred type: [Build (a -> r)] > In the second argument of `(:)', namely `l' > In the first argument of `build'', namely `(x : l)' > > I have been trying to figure out, which type should it be, but I haven't > found the correct one, any ideas ? I think instance (BuildList r, Build r ~ a) => BuildList (a -> r) where type Build (a -> r) = a build' l x = \y -> build' (x:l) y should work. You need to tell the compiler explicitly that a and Build r should be the same type. > > > Thanks > > - > Adolfo Builes From jack at realmode.com Thu Dec 3 11:38:50 2009 From: jack at realmode.com (I. J. Kennedy) Date: Thu Dec 3 11:13:29 2009 Subject: [Haskell-beginners] Eq a => [a]->[a] In-Reply-To: <20091203024643.GA28582@seas.upenn.edu> References: <1008bfc90912021647i44d12cdev4aae486794a713ba@mail.gmail.com> <20091203024643.GA28582@seas.upenn.edu> Message-ID: <1008bfc90912030838j7e79c23j5e4e4832164eb8d5@mail.gmail.com> Thanks for the response and thanks for the implementation. ?f xs = map fst $ takeWhile (uncurry S.notMember) (zip xs cums) ?? where cums = scanl (flip S.insert) S.empty xs I absolutely love (what I know so far) Haskell, but I must say when I see this kind of function, or write it myself, I am strongly reminded of programming in Forth thirty years ago. On Wed, Dec 2, 2009 at 8:46 PM, Brent Yorgey wrote: > > On Wed, Dec 02, 2009 at 06:47:54PM -0600, I. J. Kennedy wrote: > > I am looking for a function > > ?f::Eq a => [a]->[a] > > that takes a list and returns the longest > > initial segment of the list for which all > > the elements are distinct. > > > > For example f [2,3,6,4,3,5] = [2,3,6,4]. > > > > I didn't see anything that matched using Hoogle, > > but I thought this might be a common enough > > operation that this function might exists somewhere > > in the standard packages. > > Not that I know of. ?Here's how I would implement it (although you may > enjoy trying to implement it yourself): > > ?import qualified Data.Set as S > > ?f xs = map fst $ takeWhile (uncurry S.notMember) (zip xs cums) > ? ?where cums = scanl (flip S.insert) S.empty xs > > It works by incrementally building up a list of sets of the elements > found in prefixes of the list (with scanl), then goes down the list > (takeWhile) checking that each element isn't already in the > corresponding set of elements. > > -Brent > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From patrick.leboutillier at gmail.com Thu Dec 3 13:16:56 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Thu Dec 3 12:51:35 2009 Subject: [Haskell-beginners] Eq a => [a]->[a] In-Reply-To: <1008bfc90912030838j7e79c23j5e4e4832164eb8d5@mail.gmail.com> References: <1008bfc90912021647i44d12cdev4aae486794a713ba@mail.gmail.com> <20091203024643.GA28582@seas.upenn.edu> <1008bfc90912030838j7e79c23j5e4e4832164eb8d5@mail.gmail.com> Message-ID: On Thu, Dec 3, 2009 at 11:38 AM, I. J. Kennedy wrote: > Thanks for the response and thanks for the implementation. > > ?f xs = map fst $ takeWhile (uncurry S.notMember) (zip xs cums) > ?? where cums = scanl (flip S.insert) S.empty xs When I first saw this function I thought it looked complicated, and in a naive attempt to simplify it I came up with this: import Data.List f :: (Eq a) => [a] -> [a] f = last . takeWhile (\l -> nub l == l) . inits This worked well for short lists, but started to drag for large lists, especially if the result was long, i.e. for input like ([1 .. 1000] ++ [1]). Brent's version seems very fast no matter the list length. Maybe someone can provide a O() analysis? Patrick > > I absolutely love (what I know so far) Haskell, but I must say > when I see this kind of function, or write it myself, I am strongly > reminded of programming in Forth thirty years ago. > > > On Wed, Dec 2, 2009 at 8:46 PM, Brent Yorgey wrote: >> >> On Wed, Dec 02, 2009 at 06:47:54PM -0600, I. J. Kennedy wrote: >> > I am looking for a function >> > ?f::Eq a => [a]->[a] >> > that takes a list and returns the longest >> > initial segment of the list for which all >> > the elements are distinct. >> > >> > For example f [2,3,6,4,3,5] = [2,3,6,4]. >> > >> > I didn't see anything that matched using Hoogle, >> > but I thought this might be a common enough >> > operation that this function might exists somewhere >> > in the standard packages. >> >> Not that I know of. ?Here's how I would implement it (although you may >> enjoy trying to implement it yourself): >> >> ?import qualified Data.Set as S >> >> ?f xs = map fst $ takeWhile (uncurry S.notMember) (zip xs cums) >> ? ?where cums = scanl (flip S.insert) S.empty xs >> >> It works by incrementally building up a list of sets of the elements >> found in prefixes of the list (with scanl), then goes down the list >> (takeWhile) checking that each element isn't already in the >> corresponding set of elements. >> >> -Brent >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From builes.adolfo at googlemail.com Thu Dec 3 13:51:31 2009 From: builes.adolfo at googlemail.com (builes.adolfo@googlemail.com) Date: Thu Dec 3 13:26:12 2009 Subject: [Haskell-beginners] From Functional Dependencies to Type Families In-Reply-To: <200912031230.08486.daniel.is.fischer@web.de> Message-ID: <000e0cd6c808ca2e460479d77a46@google.com> > You need to tell the compiler explicitly that a and Build r should be the > same type. Thanks Daniel :). That was the trick . It's the first time that I see "~", is that from -XUndecidableInstances ? . Also, thanks to Stephen. - Adolfo On Dec 3, 2009 6:30am, Daniel Fischer wrote: > Am Donnerstag 03 Dezember 2009 04:06:43 schrieb Adolfo Builes: > > > {-# OPTIONS -fglasgow-exts #-} > > > > > > module VarArg where > > > import Data.FiniteMap -- for an example below > > > > > > class BuildList ar | r-> a where > > > build' :: [a] -> a -> r > > > > > > instance BuildList a [a] where > > > build' lx = reverse$ x:l > > > > > > instance BuildList ar => BuildList a (a->r) where > > > build' lxy = build'(x:l) y > > > > > > --build :: forall r a. (BuildList ar) => a -> r > > > build x = build' [] x > > > > I'm trying to replace the code below to work with type families, I > started > > out replacing the definition of class with : > > > > class BuildList r where > > type Build r > > build' :: [Build r] -> Build r -> r > > > > follow by the instance for [a] resulting in > > > > instance BuildList [a] where > > type Build [a] = a > > build' lx = reverse $ x:l > > > > Until here, everything is working, and I'm able to do > > > > > build' [2,3,4] 1 :: [Integer] > > > [4,3,2,1] > > > > then I move on to the next instance (a -> r) with > > > > instance BuildList r => BuildList (a-> r) where > > type Build (a -> r) = a > > build' lx = \ y -> build'(x:l) y > > > > > > But I get the following error > > > > Couldn't match expected type `Build r' against inferred type `a' > > `a' is a rigid type variable bound by > > the instance declaration at /home/adolfo/foo.hs:347:35 > > In the first argument of `(:)', namely `x' > > In the first argument of `build'', namely `(x : l)' > > In the expression: build' (x : l) y > > > > then I try with : > > > > instance BuildList r => BuildList (a-> r) where > > type Build (a -> r) = Build r > > build' lx = \ y -> build'(x:l) y > > > > > > And I get > > > > Couldn't match expected type `a' against inferred type `Build r' > > `a' is a rigid type variable bound by > > the instance declaration at /home/adolfo/foo.hs:347:35 > > Expected type: [Build r] > > Inferred type: [Build (a -> r)] > > In the second argument of `(:)', namely `l' > > In the first argument of `build'', namely `(x : l)' > > > > I have been trying to figure out, which type should it be, but I haven't > > found the correct one, any ideas ? > I think > instance (BuildList r, Build r ~ a) => BuildList (a -> r) where > type Build (a -> r) = a > build' lx = \y -> build' (x:l) y > should work. > You need to tell the compiler explicitly that a and Build r should be the > same type. > > > > > > Thanks > > > > - > > Adolfo Builes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091203/1838b533/attachment.html From daniel.is.fischer at web.de Thu Dec 3 14:00:00 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Dec 3 13:36:08 2009 Subject: [Haskell-beginners] Eq a => [a]->[a] In-Reply-To: References: <1008bfc90912021647i44d12cdev4aae486794a713ba@mail.gmail.com> <1008bfc90912030838j7e79c23j5e4e4832164eb8d5@mail.gmail.com> Message-ID: <200912032000.00948.daniel.is.fischer@web.de> Am Donnerstag 03 Dezember 2009 19:16:56 schrieb Patrick LeBoutillier: > On Thu, Dec 3, 2009 at 11:38 AM, I. J. Kennedy wrote: > > Thanks for the response and thanks for the implementation. > > > > ?f xs = map fst $ takeWhile (uncurry S.notMember) (zip xs cums) > > ?? where cums = scanl (flip S.insert) S.empty xs > > When I first saw this function I thought it looked complicated, and in > a naive attempt > to simplify it I came up with this: > > import Data.List > > f :: (Eq a) => [a] -> [a] > f = last . takeWhile (\l -> nub l == l) . inits > > This worked well for short lists, but started to drag for large lists, > especially if the result was long, i.e. for input like ([1 .. 1000] ++ > [1]). > > Brent's version seems very fast no matter the list length. Maybe > someone can provide a O() analysis? nub is O((length l)^2), thus nubbing all initial segments of l up to length k is O(k^3). Data.Set.insert is O(log size), so calculating the first k elements of scanl (flip insert) empty l is O(log (k!)) = O(k log k). The membership test is again O(log size), zipping is O(k), so altogether O(k*(log k)^2). You can remove one factor (log k) by checking the size instead of membership: f xs = map fst . takeWhile snd . zip xs . zipWith ((. S.size) . (==)) [1 .. ] $ cums where cums = tail $ scanl (flip S.insert) S.empty xs I think for *short* nubbed prefixes, Brent's version is faster, but I've no idea yet when short stops (10, 100, 1000?). A quadratic (I think) version if the type of elements doesn't belong to Ord: f (x:xs) = x:f (takeWhile (/= x) xs) f [] = [] > > Patrick > > > I absolutely love (what I know so far) Haskell, but I must say > > when I see this kind of function, or write it myself, I am strongly > > reminded of programming in Forth thirty years ago. > > > > On Wed, Dec 2, 2009 at 8:46 PM, Brent Yorgey wrote: > >> On Wed, Dec 02, 2009 at 06:47:54PM -0600, I. J. Kennedy wrote: > >> > I am looking for a function > >> > ?f::Eq a => [a]->[a] > >> > that takes a list and returns the longest > >> > initial segment of the list for which all > >> > the elements are distinct. > >> > > >> > For example f [2,3,6,4,3,5] = [2,3,6,4]. > >> > > >> > I didn't see anything that matched using Hoogle, > >> > but I thought this might be a common enough > >> > operation that this function might exists somewhere > >> > in the standard packages. > >> > >> Not that I know of. ?Here's how I would implement it (although you may > >> enjoy trying to implement it yourself): > >> > >> ?import qualified Data.Set as S > >> > >> ?f xs = map fst $ takeWhile (uncurry S.notMember) (zip xs cums) > >> ? ?where cums = scanl (flip S.insert) S.empty xs > >> > >> It works by incrementally building up a list of sets of the elements > >> found in prefixes of the list (with scanl), then goes down the list > >> (takeWhile) checking that each element isn't already in the > >> corresponding set of elements. > >> > >> -Brent From daniel.is.fischer at web.de Thu Dec 3 14:13:18 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Dec 3 13:49:25 2009 Subject: [Haskell-beginners] From Functional Dependencies to Type Families In-Reply-To: <000e0cd6c808ca2e460479d77a46@google.com> References: <000e0cd6c808ca2e460479d77a46@google.com> Message-ID: <200912032013.18904.daniel.is.fischer@web.de> Am Donnerstag 03 Dezember 2009 19:51:31 schrieb builes.adolfo@googlemail.com: > > You need to tell the compiler explicitly that a and Build r should be the > > same type. > > Thanks Daniel :). That was the trick . > > It's the first time that I see "~", is that from -XUndecidableInstances ? . No, it's part of the TypeFamilies extension. http://www.haskell.org/haskellwiki/GHC/Type_families#Equality_constraints and http://www.haskell.org/ghc/docs/latest/html/users_guide/type-families.html (much overlap). It requires UndecidableInstances ( http://www.haskell.org/ghc/docs/latest/html/users_guide/type-class- extensions.html#undecidable-instances ) because both type variables from the instance head appear in the constraints, so the compiler can't prove that type inference will terminate. You tell it that you think it will terminate, and it goes forth. Which reminds me: > {-# OPTIONS -fglasgow-exts #-} is deprecated. Use LANGUAGE pragmas, in this case {-# LANGUAGE TypeFamilies, UndecidableInstances #-} ({-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} for the FunDep version). From korpios at korpios.com Thu Dec 3 15:33:53 2009 From: korpios at korpios.com (Tom Tobin) Date: Thu Dec 3 15:08:31 2009 Subject: [Haskell-beginners] partitionM Message-ID: While working on some filesystem traversal code, I found myself wanting to use the 'partition' function from Data.List, but with the function 'doesDirectoryExist' in System.Directory (with type Filepath -> IO Bool). I noticed that there was no 'partitionM' in Control.Monad, so I set out to write one. Here's what I ended up with: > import Control.Monad (foldM) > partitionMHelper :: Monad m => (a -> m Bool) -> ([a],[a]) -> a -> m ([a],[a]) > partitionMHelper p (ts,fs) x = do > b <- p x > return (if b then (x:ts,fs) else (ts,x:fs)) > partitionM :: (Monad m) => (a -> m Bool) -> [a] -> m ([a], [a]) > partitionM p xs = foldM (partitionMHelper p) ([],[]) $ reverse xs This works for my trivial cases, but can fail with extremely large lists (not to mention being unable to take an infinite list and work properly when passed to something like 'take 5'). Is there a way to change the function to avoid having to traverse to the end of the list (via reverse) just to get the output in the proper order? I started trying to write a "foldrM", but haven't gotten anywhere useful yet. Can someone point me in the right direction? From daniel.is.fischer at web.de Thu Dec 3 16:06:19 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Dec 3 15:42:24 2009 Subject: [Haskell-beginners] partitionM In-Reply-To: References: Message-ID: <200912032206.19454.daniel.is.fischer@web.de> Am Donnerstag 03 Dezember 2009 21:33:53 schrieb Tom Tobin: > While working on some filesystem traversal code, I found myself > wanting to use the 'partition' function from Data.List, but with the > function 'doesDirectoryExist' in System.Directory (with type Filepath > -> IO Bool). I noticed that there was no 'partitionM' in > Control.Monad, so I set out to write one. > > Here's what I ended up with: > > import Control.Monad (foldM) > > > > partitionMHelper :: Monad m => (a -> m Bool) -> ([a],[a]) -> a -> m ([a],[a]) Before thinking much about it, I believe, a lazy pattern would help: partitionHelper p ~(ts,fs) x = do ... The reverse in partitionM still forbids infinite lists, I'll come to that later. > > partitionMHelper p (ts,fs) x = do > > b <- p x > > return (if b then (x:ts,fs) else (ts,x:fs)) > > > > partitionM :: (Monad m) => (a -> m Bool) -> [a] -> m ([a], [a]) > > partitionM p xs = foldM (partitionMHelper p) ([],[]) $ reverse xs > > This works for my trivial cases, but can fail with extremely large > lists (not to mention being unable to take an infinite list and work > properly when passed to something like 'take 5'). Is there a way to > change the function to avoid having to traverse to the end of the list > (via reverse) just to get the output in the proper order? I started > trying to write a "foldrM", but haven't gotten anywhere useful yet. > > Can someone point me in the right direction? From josh.bronson at gmail.com Thu Dec 3 18:20:28 2009 From: josh.bronson at gmail.com (Josh Bronson) Date: Thu Dec 3 17:55:06 2009 Subject: [Haskell-beginners] fail: wxhaskell with cabal In-Reply-To: <200911272318.55725.daniel.is.fischer@web.de> References: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> <200911272007.40932.daniel.is.fischer@web.de> <9c9cf8a00911271322u680d5580ydaa87582be4f092c@mail.gmail.com> <200911272318.55725.daniel.is.fischer@web.de> Message-ID: <9c9cf8a00912031520mc063395g441b26c523fee431@mail.gmail.com> I think the Ubuntu 9.10 packages are up-to-date, so I'll try using gtk2hs with the Ubuntu packages next time I have some free time. Thanks for the help! Josh On Fri, Nov 27, 2009 at 4:18 PM, Daniel Fischer wrote: > Am Freitag 27 November 2009 22:22:03 schrieb Josh Bronson: >> Ah. Is there a better GUI library to work with? > > I don't know which one is 'better' for what purposes, but gtk2hs is much used. > It is unfortunately, as far as I know, not cabalised, so you'd have to manually install > it. > >> Is cabal along with >> the Haskell Platform a good idea? Or is it better to just stick with >> libraries that install natively using APT on Ubuntu? I'm just trying > > Don't know if it's still true, but the debian packages used to lag far behind hackage, so > that used to not be a serious option. If nowadays the debian-haskell packagers are up to > speed, apt-get has advantages over cabal install. > >> to write a little GUI application (John Conway's Game of Life) to >> learn Haskell. >> >> Thanks, >> Josh >> >> On Fri, Nov 27, 2009 at 1:07 PM, Daniel Fischer >> >> wrote: >> > Which reminds me, I've *never* succeeded building wxhaskell, I wonder how >> > many managed. > > This is now no longer true. I read the header "dialup.h" and replaced the "undeclared" > macros wxEVT_DIALUP_(DIS)CONNECTED with the appropriate values in eljevent.cpp, then > wxcore built and afterwards also wx. I haven't tested it, so it may be broken, but if it > is, that shouldn't be the cause, I think. > From daniel.is.fischer at web.de Thu Dec 3 18:53:17 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Dec 3 18:29:36 2009 Subject: [Haskell-beginners] partitionM In-Reply-To: <200912032206.19454.daniel.is.fischer@web.de> References: <200912032206.19454.daniel.is.fischer@web.de> Message-ID: <200912040053.19880.daniel.is.fischer@web.de> Am Donnerstag 03 Dezember 2009 22:06:19 schrieb Daniel Fischer: > Am Donnerstag 03 Dezember 2009 21:33:53 schrieb Tom Tobin: > > While working on some filesystem traversal code, I found myself > > wanting to use the 'partition' function from Data.List, but with the > > function 'doesDirectoryExist' in System.Directory (with type Filepath > > -> IO Bool). I noticed that there was no 'partitionM' in > > Control.Monad, so I set out to write one. > > > > Here's what I ended up with: > > > import Control.Monad (foldM) > > > > > > partitionMHelper :: Monad m => (a -> m Bool) -> ([a],[a]) -> a -> m > > > ([a],[a]) > > Before thinking much about it, I believe, a lazy pattern would help: > > partitionHelper p ~(ts,fs) x = do ... First, typo, bad me. Second, no it won't, we're doing a left fold (sort of), so it's already a good pair. > > The reverse in partitionM still forbids infinite lists, I'll come to that > later. > > > > partitionMHelper p (ts,fs) x = do > > > b <- p x > > > return (if b then (x:ts,fs) else (ts,x:fs)) > > > > > > partitionM :: (Monad m) => (a -> m Bool) -> [a] -> m ([a], [a]) > > > partitionM p xs = foldM (partitionMHelper p) ([],[]) $ reverse xs > > > > This works for my trivial cases, but can fail with extremely large > > lists (not to mention being unable to take an infinite list and work > > properly when passed to something like 'take 5'). Can't, in general. What if some test at the end fails (p x = [], resp Nothing, ioError (userError "too bad"))? Then, for many monads the whole computation must fail, so you can't start returning anything before you know there is something to return. > > Is there a way to change the function to avoid having to > > traverse to the end of the list (via reverse) just to get the > > output in the proper order? Yes, partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a],[a]) partitionM p xs = do (f,g) <- pMHelper p xs return (f [], g []) pMHelper :: Monad m => (a -> m Bool) -> [a] -> m ([a] -> [a],[a] -> [a]) pMHelper p xs = foldM help (id,id) xs where help (f,g) x = do b <- p x return (if b then (f . (x:),g) else (f,g . (x:))) It's a little slower than yours for my test, though and I don't see how to speed it up. > > I started trying to write a "foldrM", > > but haven't gotten anywhere useful yet. > > > > Can someone point me in the right direction? From daniel.is.fischer at web.de Thu Dec 3 20:37:11 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Dec 3 20:13:20 2009 Subject: [Haskell-beginners] Eq a => [a]->[a] In-Reply-To: <200912032000.00948.daniel.is.fischer@web.de> References: <1008bfc90912021647i44d12cdev4aae486794a713ba@mail.gmail.com> <200912032000.00948.daniel.is.fischer@web.de> Message-ID: <200912040237.13864.daniel.is.fischer@web.de> Am Donnerstag 03 Dezember 2009 20:00:00 schrieb Daniel Fischer: > You can remove one factor (log k) by checking the size instead of > membership: > > f xs = map fst . takeWhile snd . zip xs . zipWith ((. S.size) . (==)) [1 .. > ] $ cums where > ? ? ? cums = tail $ scanl (flip S.insert) S.empty xs > > I think for *short* nubbed prefixes, Brent's version is faster, but I've no > idea yet when short stops (10, 100, 1000?). Couldn't measure a difference for short lists, starts to become faster than Brent's between 10^5 and 10^6. The manual loop f :: Ord a => [a] -> [a] f xs = go 1 S.empty xs where go i s (y:ys) | i == S.size s' = y:go (i+1) s' ys | otherwise = [] where s' = S.insert y s go _ _ _ = [] is ~15% faster. From velman at cox.net Thu Dec 3 22:52:49 2009 From: velman at cox.net (John Velman) Date: Thu Dec 3 22:27:27 2009 Subject: [Haskell-beginners] "reusable" data in Haskell Message-ID: <20091204035249.GA246@cox.net> In prolog, one can create a database of facts and predicates, which, depending on the prolog (AFAIK) can be 'compiled' and loaded quickly. How does one do something comparable in Haskell? I guess I have in mind something like a function that accesses the data with a key. And ideally, the data should itself be able to contain functions. I know there is a hash table library, and interfaces to databases like postgresql. If using hash table, is there a way to 'pickle' the hash table, and unpickle it? I'd be happy to have some pointers to someplace that this has been done (or some documentation on how to do it. Thanks, John Velman From stephen.tetley at gmail.com Fri Dec 4 03:42:11 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Dec 4 03:16:48 2009 Subject: [Haskell-beginners] "reusable" data in Haskell In-Reply-To: <20091204035249.GA246@cox.net> References: <20091204035249.GA246@cox.net> Message-ID: <5fdc56d70912040042s757c1bd4t8e7988a002b20464@mail.gmail.com> Hello John Data-Binary is the commonly used serialization library, it could well be adequate for your purposes: http://hackage.haskell.org/package/binary >From the blurb: "Serialisation speeds of over 1 G/sec have been observed, so this library should be suitable for high performance scenarios." It really depends how you choose to represent the database, if you have cycles serialization could be tricky, but if you just have atoms of strings for the predicates and facts it should be fine(*). Best wishes Stephen (*) Converting to and from Strings and ByteStrings will take _some_ time in the serialization layer, but it would take some time from a real database or other format. From velman at cox.net Fri Dec 4 11:34:14 2009 From: velman at cox.net (John Velman) Date: Fri Dec 4 11:08:50 2009 Subject: [Haskell-beginners] "reusable" data in Haskell In-Reply-To: <5fdc56d70912040042s757c1bd4t8e7988a002b20464@mail.gmail.com> References: <20091204035249.GA246@cox.net> <5fdc56d70912040042s757c1bd4t8e7988a002b20464@mail.gmail.com> Message-ID: <20091204163414.GA246@cox.net> Thanks, Stephen. Looks like this is pretty much what I'm looking for. Best, John V. On Fri, Dec 04, 2009 at 08:42:11AM +0000, Stephen Tetley wrote: > Hello John > > Data-Binary is the commonly used serialization library, it could well > be adequate for your purposes: > > http://hackage.haskell.org/package/binary > > >From the blurb: > "Serialisation speeds of over 1 G/sec have been observed, so this > library should be suitable for high performance scenarios." > > It really depends how you choose to represent the database, if you > have cycles serialization could be tricky, but if you just have atoms > of strings for the predicates and facts it should be fine(*). > > > > Best wishes > > Stephen > > (*) Converting to and from Strings and ByteStrings will take _some_ > time in the serialization layer, but it would take some time from a > real database or other format. From john.moore54 at gmail.com Fri Dec 4 15:26:52 2009 From: john.moore54 at gmail.com (John Moore) Date: Fri Dec 4 15:01:29 2009 Subject: [Haskell-beginners] Indenting Message-ID: <4f7ad1ad0912041226w55c93c1ds19fb1ca59cc6db4f@mail.gmail.com> Hi, I'm a bit stuck. I want to indent my answer by using a count function to indent my answer. Say for example I want to show the levels in a simple arithmethic expression. like 3*(4+5) I want to be able to print out : 4+5 = 9 3*9 = 27 (notice the indentation as I go through an expression. I tried this but it a mess, I tried to use prettyprint but this seemed very complicated. Any suggestions greatly appreciated type Indent = (Int) spacing :: Int -> Indent spacing n = Nothing spacing n (x:xs) = if (n==1) then (Just n) else spacing n xs where (n > 1) John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091204/433a6e49/attachment-0001.html From chaddai.fouche at gmail.com Sat Dec 5 03:34:56 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Sat Dec 5 03:09:30 2009 Subject: [Haskell-beginners] Indenting In-Reply-To: <4f7ad1ad0912041226w55c93c1ds19fb1ca59cc6db4f@mail.gmail.com> References: <4f7ad1ad0912041226w55c93c1ds19fb1ca59cc6db4f@mail.gmail.com> Message-ID: On Fri, Dec 4, 2009 at 9:26 PM, John Moore wrote: > Hi, > ???? I'm a bit stuck. I want to indent my answer by using a count function > to indent my answer. Say for example I want to show the levels in a simple > arithmethic expression. > like 3*(4+5) > I want to be able to print out : > ?4+5 = 9 > ??? 3*9 = 27 (notice the indentation as I go through an expression. > > I tried this but it a mess, I tried to use prettyprint but this seemed very > complicated. I'm not sure I really understand what your problem is... If you just want to indent a String, it is easy to do with : > indent :: Int -> String -> String > indent n s = replicate n ' ' ++ s If you want to use this with your evaluation of a small arithmetic language, I would suggest making your evaluator returns a list of its reductions (with the Writer Monad maybe) and use : > zipWith indent [2,4..] reductionsList -- Jeda? From byorgey at seas.upenn.edu Sat Dec 5 11:35:03 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sat Dec 5 11:09:35 2009 Subject: [Haskell-beginners] Indenting In-Reply-To: <4f7ad1ad0912041226w55c93c1ds19fb1ca59cc6db4f@mail.gmail.com> References: <4f7ad1ad0912041226w55c93c1ds19fb1ca59cc6db4f@mail.gmail.com> Message-ID: <20091205163503.GA21699@seas.upenn.edu> On Fri, Dec 04, 2009 at 08:26:52PM +0000, John Moore wrote: > > type Indent = (Int) > spacing :: Int -> Indent > spacing n = Nothing > spacing n (x:xs) = if (n==1) > then (Just n) > else spacing n xs > where (n > 1) Hmm, you seem to be a bit confused. What exactly is spacing supposed to do? What is its type? Your type signature says that it has type Int -> Int, but the second equation spacing n (x:xs) = ... suggests that it takes TWO arguments, with the second being a list of some sort; also, it seems to be returning things of type Maybe Int (Nothing, Just n). So, what is it supposed to do? Is it computing an *amount* of indentation? Is it supposed to take a String and put spaces on the front? or...? -Brent From byorgey at seas.upenn.edu Sat Dec 5 15:09:01 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sat Dec 5 14:43:34 2009 Subject: [Haskell-beginners] Indenting In-Reply-To: <4f7ad1ad0912050958q74478982y8261178c0d2e4f1a@mail.gmail.com> References: <4f7ad1ad0912041226w55c93c1ds19fb1ca59cc6db4f@mail.gmail.com> <20091205163503.GA21699@seas.upenn.edu> <4f7ad1ad0912050958q74478982y8261178c0d2e4f1a@mail.gmail.com> Message-ID: <20091205200901.GA13054@seas.upenn.edu> On Sat, Dec 05, 2009 at 05:58:25PM +0000, John Moore wrote: > Hi Brent, > Sorry about the confusion below is the whole program, which may help or not? > What i want to do is when the program prints out the answers , I would like > it to be able to automatically by use of a function indent the answers > depending how far down the answer goes. OK, I think I understand what you want to do, although I'm not exactly clear on how you want the indentation to work. Anyway, I've interspersed my comments in the code below. > import Maybe Just FYI, "Maybe" is the old Haskell-98 name for the module, but nowadays the standard name is "Data.Maybe". > data Expression = Val Float > | Add Expression Expression > | Subtract Expression Expression > | Multiply Expression Expression > | Divide Expression Expression > | Let String Expression Expression > | Var String > deriving Show > type Dict =[(String,Expression)] > emptyDict :: Dict > emptyDict = [] > addEntry :: String->Expression ->Dict -> Dict > addEntry n e d = (n,e): d > lookupEntry :: String -> Dict -> Maybe Expression > lookupEntry n [] = Nothing > lookupEntry n (x:xs) = if (n == k) > then (Just v) > else lookupEntry n xs > where (k,v) = x I would write lookupEntry as follows: lookupEntry _ [] = Nothing lookupEntry n ((k,v):xs) | n == k = Just v | otherwise = lookupEntry n xs Note that you can do a nested pattern match ((k,v):xs), and the use of guards instead of if...then...else. But actually, lookupEntry is already in the standard Prelude, it is called 'lookup'! So no need to reimplement it yourself. > evalIO :: Dict -> Expression -> IO Float This function is rather poor Haskell style, because it mixes up two separate things: evaluating the expression, and printing the result. Instead, I would do something like this: eval :: Dict -> Expression -> ([String], Double) where the output is the result paired with a "trace". (Note I have used Double, a double-precision floating point number, instead of Float, which is single-precision; there's usually very little reason to use Float instead of Double.) Given eval, you can recover evalIO as follows: evalIO :: Dict -> Expression -> IO Double evalIO d e = do let (trace, result) = eval d e mapM_ putStrLn trace return result But this is a lot nicer because it cleanly separates the evaluation from the IO, and you can now do anything you like with the trace --- print it to a file, process it further, etc; you are not tied down to printing it on the screen. Now, if you just want the indentation to increase at each step, like so xxxxx xxxxx xxxxx xxxxx xxxxx ... then you can also separate this out: just return a trace with no indentation, and then apply a function to the trace to indent successive lines, something like zipWith (++) (map (flip replicate ' ') [0..]) trace If, on the other hand, you want the indentation to correspond to how "deep" within the expression the evaluation is taking place, then you can recursively pass along an extra parameter to your evaluation function, like so: eval :: Dict -> Expression -> ([String], Double) eval d e = evalIndented 0 d e where evalIndented i d (Val x) = ([], x) evalIndented i d (Add x y) = let (tx, vx) = evalIndented (i+1) d x (ty, vy) = evalIndented (i+1) d y in (replicate i ' ' ++ "Add " ++ show vx ++ " and " ++ show vy, vx + vy) ...and so on. I hope this is helpful! -Brent From daniel.is.fischer at web.de Sat Dec 5 16:09:42 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Dec 5 15:45:42 2009 Subject: [Haskell-beginners] Indenting In-Reply-To: <20091205200901.GA13054@seas.upenn.edu> References: <4f7ad1ad0912041226w55c93c1ds19fb1ca59cc6db4f@mail.gmail.com> <4f7ad1ad0912050958q74478982y8261178c0d2e4f1a@mail.gmail.com> <20091205200901.GA13054@seas.upenn.edu> Message-ID: <200912052209.42696.daniel.is.fischer@web.de> Am Samstag 05 Dezember 2009 21:09:01 schrieb Brent Yorgey: > If, on the other hand, you want the indentation to correspond to how > "deep" within the expression the evaluation is taking place, then you > can recursively pass along an extra parameter to your evaluation > function, like so: > > ? eval :: Dict -> Expression -> ([String], Double) > ? eval d e = evalIndented 0 d e where > ? ? evalIndented i d (Val x) = ([], x) > ? ? evalIndented i d (Add x y) = > ? ? ? let (tx, vx) = evalIndented (i+1) d x > ? ? ? ? ? (ty, vy) = evalIndented (i+1) d y > ? ? ? in ?(replicate i ' ' ++ "Add " ++ show vx ++ " and " ++ show vy, vx + > vy) > > ...and so on. I would even suggest eval :: Dict -> Expression -> ([(Int,String)],Double) eval d e = evalIndented 0 d e where evalIndented _ _ (Val x) = ([],x) evalIndented i d (Add x y) = let ... in ((i,"Add " ++ show vx ++ " and " ++ show vy):tx ++ ty, vx + vy) ... then you can easily extract the traces of subexpressions at a given depth and print those with adjusted indentation and change indentation schemes (indent two/four spaces further per level). From legajid at free.fr Sat Dec 5 17:20:22 2009 From: legajid at free.fr (legajid) Date: Sat Dec 5 16:51:06 2009 Subject: [Haskell-beginners] Keyboard input Message-ID: <4B1ADCA6.5090607@free.fr> Hello, in order to get familiar with keyboard data entry, i'm writing a program for the well-known Hangman game. Each entry must change several lists (letters found and remaining letters). I have three main difficulties with data entry : First When i enter a letter (A) , i get a good response (displaying old word and letters, message "guess ok") and an unattended one that says "guess false", thus displaying the result from my entry. I don't understand why the process seems to execute twice, the fisrt one being correct, the second not. Second difficulty : the "procedure" for data entry is written twice ("guess a letter ..." prompt). I think it would be a good idea to write it once as a "function" that would display the prompt then get a character from the keyboard. Third difficulty : in both cases (guess ok or false), i have to ask for a new entry; to avoid writing this twice again, i write it before the recursive calls of process_guess. Writing a function would perhaps allow to call it directly as a parameter of process_guess ? Being new to haskell, recursive functions now seem clear to me but i feel that IOs make writing a program more difficult. And i've not yet tried data base access... Please, say me if the way i wrote my program is a good or bad approach. Below an example of a run : Here's my program. Could you help me. Thanks, Didier solution="HANGMAN" word="H-----N" letters=['A'..'Z'] hangman = do -- enter a letter putStrLn "Guess a letter (9 to end):" guess <- getChar -- process process_guess guess letters word process_guess pg pletters pword =do let pguess = toUpper pg putStrLn pword putStrLn pletters if pguess == '9' then do putStrLn "Done" else do if pguess `elem` pletters then do putStrLn "Guess OK \n" else do putStrLn "Guess false \n" -- Enter a new letter before going on, in both cases putStrLn "Guess a letter (9 to end):" guess <- getChar if pguess `elem` pletters -- guess ok -> remove guess from available letters then add guess to word then do process_guess guess (newletters pletters pguess) (newword pword pguess solution) -- guess false -> remove guess from available letters, leave word unchanged else do process_guess guess (newletters pletters pguess) pword newletters l g = filter (/= g) l newword [] _ _ = [] newword (w:ws) g (s:ss) = if w == '-' then if s == g then g : newword ws g ss else w : newword ws g ss else w : newword ws g ss toUpper c | isLower c = toEnum (fromEnum c - fromEnum 'a' + fromEnum 'A') | otherwise = c isLower c = c >= 'a' && c <= 'z' From daniel.is.fischer at web.de Sat Dec 5 18:24:48 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Dec 5 18:00:55 2009 Subject: [Haskell-beginners] Keyboard input In-Reply-To: <4B1ADCA6.5090607@free.fr> References: <4B1ADCA6.5090607@free.fr> Message-ID: <200912060024.49163.daniel.is.fischer@web.de> Am Samstag 05 Dezember 2009 23:20:22 schrieb legajid: > Hello, > in order to get familiar with keyboard data entry, i'm writing a program > for the well-known Hangman game. > Each entry must change several lists (letters found and remaining letters). > I have three main difficulties with data entry : > > First When i enter a letter (A) , i get a good response (displaying old > word and letters, message "guess ok") and an unattended one that says > "guess false", thus displaying the result from my entry. > I don't understand why the process seems to execute twice, the fisrt one > being correct, the second not. I don't get that behaviour, for me, after each guess, it displays only one message. > > Second difficulty : the "procedure" for data entry is written twice > ("guess a letter ..." prompt). I think it would be a good idea to write > it once as a "function" that would display the prompt then get a > character from the keyboard. Also, the entered letter appears before the word, which is not nice. You can either import System.IO and at the beginning of hangman hSetEcho stdin False and at the end do putStrLn "Done" hSetEcho stdin True or, without futzing with the echo setting: import Data.Char (toUpper) import Data.List (delete) guessLetter :: IO Char guessLetter = do putStrLn "Guess a letter (9 to end): " c <- getChar putChar '\b' return (toUpper c) > > Third difficulty : in both cases (guess ok or false), i have to ask for > a new entry; to avoid writing this twice again, i write it before the > recursive calls of process_guess. Writing a function would perhaps allow > to call it directly as a parameter of process_guess ? It would be cleaner to not have the guess as a parameter for the game loop. > > Being new to haskell, recursive functions now seem clear to me but i > feel that IOs make writing a program more difficult. And i've not yet > tried data base access... > > Please, say me if the way i wrote my program is a good or bad approach. > > Below an example of a run : Forgot that, didn't you? > > > Here's my program. > Could you help me. > Thanks, > Didier > > solution="HANGMAN" > word="H-----N" > letters=['A'..'Z'] It would be good to have a list of letters to be guessed, wletters = "AGMN" and check whether the guess appears there (-> Guess OK) or not (-> Guess false :() and remove correctly guessed letters from this, so when there are no more letters to be guessed you can detect it and putStrLn "Congratulations" to end the game. The list of letters as allowed guesses is unnecessary, just check whether 'A' <= g && g <= 'Z' where g is toUpper (entered letter), or don't care whether what is entered is a letter or something else. > > hangman = do > -- enter a letter > putStrLn "Guess a letter (9 to end):" > guess <- getChar > -- process > process_guess guess letters word hangman = hangloop wletters word > > process_guess pg pletters pword =do hangloop "" pword = do putStrLn pword putStrLn "Congratulations, you've solved it!" hangloop pletters pword = do -- best to display the word first putStrLn pword g <- guessLetter if g == '9' then putStrLn "Bye" else do -- check whether the guess is good if g `notElem` pletters then do putStrLn "Wrong guess" hangloop pletters pword else do putStrLn "Good guess" let nletters = delete g pletters nword = newword pword g solution hangloop nletters nword > let pguess = toUpper pg > putStrLn pword > putStrLn pletters > if pguess == '9' > then do putStrLn "Done" > else do > if pguess `elem` pletters > then do putStrLn "Guess OK \n" > else do putStrLn "Guess false \n" > > -- Enter a new letter before going on, in both cases > putStrLn "Guess a letter (9 to end):" > guess <- getChar > > if pguess `elem` pletters > -- guess ok -> remove guess from available letters then add > guess to word > then do process_guess guess (newletters pletters pguess) > (newword pword pguess solution) > > -- guess false -> remove guess from available letters, leave > word unchanged > else do process_guess guess (newletters pletters pguess) pword > > > newletters l g = > filter (/= g) l if every letter appears only once in l, Data.List.delete g l is perhaps better. > > > newword [] _ _ = [] > newword (w:ws) g (s:ss) = > if w == '-' > then > if s == g > then g : newword ws g ss > else w : newword ws g ss > else > w : newword ws g ss better pattern-match: newword "" _ _ = "" newword ('-':ws) g (s:ss) | g == s = g:newword ws g ss newword (w:ws) g (s:ss) = w:newword ws g ss or, for the nonempty case: newword (w:ws) g (s:ss) | w == '-' && s == g = g:newword ws g ss | otherwise = w:newword ws g ss > > -- these are in Data.Char > toUpper c > > | isLower c = toEnum (fromEnum c - fromEnum 'a' + fromEnum 'A') > | otherwise = c > > isLower c = c >= 'a' && c <= 'z' From vinnytryclyst at gmail.com Sun Dec 6 04:46:29 2009 From: vinnytryclyst at gmail.com (Vinod Parthasarathy) Date: Sun Dec 6 04:21:00 2009 Subject: [Haskell-beginners] freelancing jobs in haskell Message-ID: <8d315ecd0912060146k66df3db7v63d4304ee84aa625@mail.gmail.com> Hi, I recently learnt Haskell as part of my post graduate course work in Computer Science. I am looking for freelancing websites which offer online jobs in Haskell. If any of you know any such website where I could look for freelancing jobs, could you please let me know? I am from India, and am also looking for jobs in India in Haskell programming. Any help in that direction would also be helpful. Vinod. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091206/3592f03d/attachment.html From legajid at free.fr Mon Dec 7 16:52:42 2009 From: legajid at free.fr (legajid) Date: Mon Dec 7 16:23:19 2009 Subject: [Haskell-beginners] Keyboard input In-Reply-To: <200912060024.49163.daniel.is.fischer@web.de> References: <4B1ADCA6.5090607@free.fr> <200912060024.49163.daniel.is.fischer@web.de> Message-ID: <4B1D792A.7020603@free.fr> Hello, ok for the responses. However, about the strange behaviour of getChar, i forgot to say i'm running on Windows XP with GHci 6.10.4 It seems that getChar buffers all characters, including newline; so, typing A + enter is equivalent to typing 2 characters successively. To successfully solve the problem, i did the following : guessLetter :: IO Char guessLetter = do putStrLn "Guess a letter (9 to end): " cl <- getLine let c= extr cl -- c <- getChar -- putChar '\b' return (toUpper c) extr :: String -> Char extr (c:cs)=c Notice that, on my system, putChar has no visible effect. Seeking for info, i found this mail : http://old.nabble.com/How-to-getCh-on-MS-Windows-command-line--td20414545.html that talks about a similar issue on Windows Didier. Daniel Fischer a ?crit : > Am Samstag 05 Dezember 2009 23:20:22 schrieb legajid: > >> Hello, >> in order to get familiar with keyboard data entry, i'm writing a program >> for the well-known Hangman game. >> Each entry must change several lists (letters found and remaining letters). >> I have three main difficulties with data entry : >> >> First When i enter a letter (A) , i get a good response (displaying old >> word and letters, message "guess ok") and an unattended one that says >> "guess false", thus displaying the result from my entry. >> I don't understand why the process seems to execute twice, the fisrt one >> being correct, the second not. >> > > I don't get that behaviour, for me, after each guess, it displays only one message. > > >> Second difficulty : the "procedure" for data entry is written twice >> ("guess a letter ..." prompt). I think it would be a good idea to write >> it once as a "function" that would display the prompt then get a >> character from the keyboard. >> > > Also, the entered letter appears before the word, which is not nice. > You can either > > import System.IO > > and at the beginning of hangman > > hSetEcho stdin False > > and at the end > > do putStrLn "Done" > hSetEcho stdin True > > or, without futzing with the echo setting: > > import Data.Char (toUpper) > import Data.List (delete) > > guessLetter :: IO Char > guessLetter = do > putStrLn "Guess a letter (9 to end): " > c <- getChar > putChar '\b' > return (toUpper c) > > >> Third difficulty : in both cases (guess ok or false), i have to ask for >> a new entry; to avoid writing this twice again, i write it before the >> recursive calls of process_guess. Writing a function would perhaps allow >> to call it directly as a parameter of process_guess ? >> > > It would be cleaner to not have the guess as a parameter for the game loop. > > >> Being new to haskell, recursive functions now seem clear to me but i >> feel that IOs make writing a program more difficult. And i've not yet >> tried data base access... >> >> Please, say me if the way i wrote my program is a good or bad approach. >> >> Below an example of a run : >> > > Forgot that, didn't you? > > >> Here's my program. >> Could you help me. >> Thanks, >> Didier >> >> solution="HANGMAN" >> word="H-----N" >> letters=['A'..'Z'] >> > > It would be good to have a list of letters to be guessed, > > wletters = "AGMN" > > and check whether the guess appears there (-> Guess OK) > or not (-> Guess false :() > and remove correctly guessed letters from this, so when there are no more letters to be > guessed you can detect it and > > putStrLn "Congratulations" > > to end the game. > > The list of letters as allowed guesses is unnecessary, just check whether > > 'A' <= g && g <= 'Z' > > where g is toUpper (entered letter), or don't care whether what is entered is a letter or > something else. > > >> hangman = do >> -- enter a letter >> putStrLn "Guess a letter (9 to end):" >> guess <- getChar >> -- process >> process_guess guess letters word >> > > hangman = hangloop wletters word > > >> process_guess pg pletters pword =do >> > > hangloop "" pword = do > putStrLn pword > putStrLn "Congratulations, you've solved it!" > hangloop pletters pword = do > -- best to display the word first > putStrLn pword > g <- guessLetter > if g == '9' > then putStrLn "Bye" > else do > -- check whether the guess is good > if g `notElem` pletters > then do > putStrLn "Wrong guess" > hangloop pletters pword > else do > putStrLn "Good guess" > let nletters = delete g pletters > nword = newword pword g solution > hangloop nletters nword > > >> let pguess = toUpper pg >> putStrLn pword >> putStrLn pletters >> if pguess == '9' >> then do putStrLn "Done" >> else do >> if pguess `elem` pletters >> then do putStrLn "Guess OK \n" >> else do putStrLn "Guess false \n" >> >> -- Enter a new letter before going on, in both cases >> putStrLn "Guess a letter (9 to end):" >> guess <- getChar >> >> if pguess `elem` pletters >> -- guess ok -> remove guess from available letters then add >> guess to word >> then do process_guess guess (newletters pletters pguess) >> (newword pword pguess solution) >> >> -- guess false -> remove guess from available letters, leave >> word unchanged >> else do process_guess guess (newletters pletters pguess) pword >> >> >> newletters l g = >> filter (/= g) l >> > > if every letter appears only once in l, Data.List.delete g l is perhaps better. > > >> newword [] _ _ = [] >> newword (w:ws) g (s:ss) = >> if w == '-' >> then >> if s == g >> then g : newword ws g ss >> else w : newword ws g ss >> else >> w : newword ws g ss >> > > better pattern-match: > > newword "" _ _ = "" > newword ('-':ws) g (s:ss) > | g == s = g:newword ws g ss > newword (w:ws) g (s:ss) = w:newword ws g ss > > or, for the nonempty case: > > newword (w:ws) g (s:ss) > | w == '-' && s == g = g:newword ws g ss > | otherwise = w:newword ws g ss > > >> > > -- these are in Data.Char > > >> toUpper c >> >> | isLower c = toEnum (fromEnum c - fromEnum 'a' + fromEnum 'A') >> | otherwise = c >> >> isLower c = c >= 'a' && c <= 'z' >> > > > From daniel.is.fischer at web.de Mon Dec 7 17:36:10 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 7 17:12:05 2009 Subject: [Haskell-beginners] Keyboard input In-Reply-To: <4B1D792A.7020603@free.fr> References: <4B1ADCA6.5090607@free.fr> <200912060024.49163.daniel.is.fischer@web.de> <4B1D792A.7020603@free.fr> Message-ID: <200912072336.10804.daniel.is.fischer@web.de> Am Montag 07 Dezember 2009 22:52:42 schrieb legajid: > Hello, > ok for the responses. > However, about the strange behaviour of getChar, i forgot to say i'm > running on Windows XP with GHci 6.10.4 Voil?, c'est ton probl?me ;) Somehow, buffering (or rather not buffering) doesn't work properly on Windows. Ordinarily, in ghci, stdin is unbuffered, meaning each character you type is immediately passed to the application (for binaries, you'd have to "hSetBuffering stdin NoBuffering"), that seems not to be the case on Windows (http://hackage.haskell.org/trac/ghc/ticket/2189). > It seems that getChar buffers all characters, including newline; so, > typing A + enter is equivalent to typing 2 characters successively. > To successfully solve the problem, i did the following : > > guessLetter :: IO Char > guessLetter = do > putStrLn "Guess a letter (9 to end): " > cl <- getLine > let c= extr cl > -- c <- getChar > -- putChar '\b' > return (toUpper c) > > extr :: String -> Char > extr (c:cs)=c > > > Notice that, on my system, putChar has no visible effect. Buffering again. Just to test what works, you can try a) ghci> :m +System.IO ghci> hSetBuffering stdout NoBuffering ghci> putChar 'A' (turning off buffering for stdout *may* work, even if it doesn't for stdin) if the next line you see is Aghci> it worked b) explicitly flush stdout do ... putChar 'X' hFlush stdout > > Seeking for info, i found this mail : > http://old.nabble.com/How-to-getCh-on-MS-Windows-command-line--td20414545.h >tml that talks about a similar issue on Windows > > Didier. > From bpederse at gmail.com Mon Dec 7 22:43:04 2009 From: bpederse at gmail.com (Brent Pedersen) Date: Mon Dec 7 22:17:29 2009 Subject: [Haskell-beginners] text file to data type Message-ID: hi, i have files with lots (millions of rows) of data like this: chr6 chr10 96.96 3392 101 2 79030508 79033899 4160024 4163413 0.0 5894 chr6 chr10 93.19 4098 228 13 117152751 117156826 11355389 11359457 0.0 5886 chr6 chr10 95.82 3445 130 5 112422073 112425513 7785396 7788830 0.0 5666 and i'd like to read it into a type like this: data Blast = Blast { query :: S.ByteString , subject :: S.ByteString , hitlen :: Int , mismatch :: Int , gaps :: Int , qstart :: Int , qstop :: Int , sstart :: Int , sstop :: Int , pctid :: Double , evalue :: Double , bitscore :: Double } deriving (Show) where each of those fields corresponds to a column in the file. in python, i do something like: >>> line = [fn(col) for fn, col in zip([str, str, int, int, int, int, int, int, int, float, float], sline.split("\t")] what's a fast, simple way to do this in haskell? is it something like: instance Read Blast where readsPrec s = ????? any pointers on where to look for simple examples of this type of parsing would be much appreciated. thanks, -brentp From jfredett at gmail.com Mon Dec 7 22:52:47 2009 From: jfredett at gmail.com (Joe Fredette) Date: Mon Dec 7 22:27:15 2009 Subject: [Haskell-beginners] text file to data type In-Reply-To: References: Message-ID: <1DAEE45C-4C94-4CEF-8448-5548963076F5@gmail.com> My suggestion would be to look into writing a parser (via parsec) to handle this. Parsec is fairly easy to learn, and since your data is a pretty simple format, the parser won't be hard to write. Parsec will then give you a parser which you can run on the file, it'll catch parse errors, it's all around very lovely to use. There is a chapter of Real World Haskell on the subject, and I'm sure we'll be happy to help with whatever isn't covered. /Joe On Dec 7, 2009, at 10:43 PM, Brent Pedersen wrote: > hi, i have files with lots (millions of rows) of data like this: > chr6 chr10 96.96 3392 101 2 79030508 79033899 4160024 > 4163413 0.0 5894 > chr6 chr10 93.19 4098 228 13 117152751 117156826 > 11355389 11359457 0.0 5886 > chr6 chr10 95.82 3445 130 5 112422073 112425513 7785396 > 7788830 0.0 5666 > > and i'd like to read it into a type like this: > > data Blast = Blast { query :: S.ByteString > , subject :: S.ByteString > , hitlen :: Int > , mismatch :: Int > , gaps :: Int > , qstart :: Int > , qstop :: Int > , sstart :: Int > , sstop :: Int > , pctid :: Double > , evalue :: Double > , bitscore :: Double > } deriving (Show) > > where each of those fields corresponds to a column in the file. > in python, i do something like: > >>>> line = [fn(col) for fn, col in zip([str, str, int, int, int, int, >>>> int, int, int, float, float], sline.split("\t")] > > what's a fast, simple way to do this in haskell? > > is it something like: > > instance Read Blast where > readsPrec s = ????? > > > any pointers on where to look for simple examples of this type of > parsing would > be much appreciated. > thanks, > -brentp > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From apfelmus at quantentunnel.de Tue Dec 8 05:29:39 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Tue Dec 8 05:04:20 2009 Subject: [Haskell-beginners] Re: text file to data type In-Reply-To: <1DAEE45C-4C94-4CEF-8448-5548963076F5@gmail.com> References: <1DAEE45C-4C94-4CEF-8448-5548963076F5@gmail.com> Message-ID: Joe Fredette wrote: > My suggestion would be to look into writing a parser (via parsec) to > handle this. Parsec is fairly easy to learn, and since your data is a > pretty simple format, the parser won't be hard to write. While I'm all for using a proper parser, Brent Pedersen notes that his data will have millions of rows, so that Parsec is likely to run into memory problems. I think something along the lines of import Data.ByteString.Lazy.Char8 as B parse = map (zipWith ($) formats . B.split '\t') . B.lines where formats = [str, str, int, int, int, int, int, int, int, float, float] int = fst . fromJust . readInt float = \s -> read (unpack s) :: Double str = id will do just fine. (The implementation of float is a kludge, I think there's something on hackage for that, though?) Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From patrick.leboutillier at gmail.com Tue Dec 8 09:38:43 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Tue Dec 8 09:13:07 2009 Subject: [Haskell-beginners] Re: text file to data type In-Reply-To: References: <1DAEE45C-4C94-4CEF-8448-5548963076F5@gmail.com> Message-ID: Hi all, On Tue, Dec 8, 2009 at 5:29 AM, Heinrich Apfelmus wrote: > Joe Fredette wrote: >> My suggestion would be to look into writing a parser (via parsec) to >> handle this. Parsec is fairly easy to learn, and since your data is a >> pretty simple format, the parser won't be hard to write. > > While I'm all for using a proper parser, Brent Pedersen notes that his > data will have millions of rows, so that Parsec is likely to run into > memory problems. > > I think something along the lines of > > ? import Data.ByteString.Lazy.Char8 as B > > ? parse = map (zipWith ($) formats . B.split '\t') . B.lines > ? ? ? where > ? ? ? formats = [str, str, int, int, int, int, int, > ? ? ? ? ? ? ? ? ?int, int, float, float] > ? ? ? int ? = fst . fromJust . readInt > ? ? ? float = \s -> read (unpack s) :: Double > ? ? ? str ? = id > I've been looking at this example and I can't figure it out how it works. Seems to me that "formats" is a list of functions that return different types. How does this work? Patrick > will do just fine. (The implementation of ?float ?is a kludge, I think > there's something on hackage for that, though?) > > > Regards, > Heinrich Apfelmus > > -- > http://apfelmus.nfshost.com > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From jon at ffconsultancy.com Tue Dec 8 15:56:45 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue Dec 8 14:17:27 2009 Subject: [Haskell-beginners] Parallel mutation Message-ID: <200912082056.46077.jon@ffconsultancy.com> Can you mutate different parts of the same array from different threads in parallel using GHC? Someone once told me this was possible but I cannot see how... -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From daniel.is.fischer at web.de Tue Dec 8 16:37:41 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Dec 8 16:13:33 2009 Subject: [Haskell-beginners] Parallel mutation In-Reply-To: <200912082056.46077.jon@ffconsultancy.com> References: <200912082056.46077.jon@ffconsultancy.com> Message-ID: <200912082237.41730.daniel.is.fischer@web.de> Am Dienstag 08 Dezember 2009 21:56:45 schrieb Jon Harrop: > Can you mutate different parts of the same array from different threads in > parallel using GHC? Someone once told me this was possible but I cannot see > how... You can (take a look at Control.Concurrent), but very probably ***You really shouldn't***, so I won't elaborate. What would you want to do that for? From t-otto-news at gmx.de Tue Dec 8 17:34:30 2009 From: t-otto-news at gmx.de (Torsten Otto) Date: Tue Dec 8 17:08:54 2009 Subject: [Haskell-beginners] recursively building lists Message-ID: <1EE8DDB0-BF31-4185-8E80-E20D61A576BB@gmx.de> Hi! While trying to implement "words", we ran into the question of how to build lists of lists. The trouble boils down to this: test = []:[] is no problem, just as Prelude> []:[]:[]:[] [[],[],[]] works fine. Now trying to put the two together _is_ a problem: testlist 1 = []:[] testlist n = []:(testlist n-1) No instance for (Num [[a]]) arising from a use of `testlist' at :1:0-9 Possible fix: add an instance declaration for (Num [[a]]) In the expression: testlist 2 In the definition of `it': it = testlist 2 Can someone please explain, what is going on here? Regards, Torsten From daniel.is.fischer at web.de Tue Dec 8 17:43:07 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Dec 8 17:18:57 2009 Subject: [Haskell-beginners] recursively building lists In-Reply-To: <1EE8DDB0-BF31-4185-8E80-E20D61A576BB@gmx.de> References: <1EE8DDB0-BF31-4185-8E80-E20D61A576BB@gmx.de> Message-ID: <200912082343.07250.daniel.is.fischer@web.de> Am Dienstag 08 Dezember 2009 23:34:30 schrieb Torsten Otto: > Hi! > > While trying to implement "words", we ran into the question of how to build > lists of lists. The trouble boils down to this: > > test = []:[] > > is no problem, just as > > Prelude> []:[]:[]:[] > [[],[],[]] > > works fine. Now trying to put the two together _is_ a problem: > > testlist 1 = []:[] > testlist n = []:(testlist n-1) > > No instance for (Num [[a]]) > arising from a use of `testlist' at :1:0-9 > Possible fix: add an instance declaration for (Num [[a]]) > In the expression: testlist 2 > In the definition of `it': it = testlist 2 > > Can someone please explain, what is going on here? Yes. Function application has higher precedence than aritthmetic operations, so the RHS of testlist n is parsed as [] : ( (testlist n) - 1) So, by the equation for testlist 1, the compiler knows that testlist :: (Num n) => n -> [[a]] In the second equation, you try to subtract 1 from a value of type [[a]], that means you need a Num instance for that type. What you want is testlist n = []:testlist (n-1) HTH, Daniel From ezyang at MIT.EDU Tue Dec 8 17:45:19 2009 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Tue Dec 8 17:19:45 2009 Subject: [Haskell-beginners] recursively building lists In-Reply-To: <1EE8DDB0-BF31-4185-8E80-E20D61A576BB@gmx.de> References: <1EE8DDB0-BF31-4185-8E80-E20D61A576BB@gmx.de> Message-ID: <1260312279-sup-7975@ezyang> Excerpts from Torsten Otto's message of Tue Dec 08 17:34:30 -0500 2009: > testlist 1 = []:[] > testlist n = []:(testlist n-1) Works for me on GHC 6.10.4. What compiler are you using? Cheers, Edward From ezyang at MIT.EDU Tue Dec 8 18:01:14 2009 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Tue Dec 8 17:35:38 2009 Subject: [Haskell-beginners] recursively building lists In-Reply-To: <1260312279-sup-7975@ezyang> References: <1EE8DDB0-BF31-4185-8E80-E20D61A576BB@gmx.de> <1260312279-sup-7975@ezyang> Message-ID: <1260313258-sup-3415@ezyang> Excerpts from Edward Z. Yang's message of Tue Dec 08 17:45:19 -0500 2009: > Excerpts from Torsten Otto's message of Tue Dec 08 17:34:30 -0500 2009: > > testlist 1 = []:[] > > testlist n = []:(testlist n-1) > > Works for me on GHC 6.10.4. What compiler are you using? Ah, it compiles, but refuses to run. Please ignore me. :-) Edward From t-otto-news at gmx.de Tue Dec 8 18:18:54 2009 From: t-otto-news at gmx.de (Torsten Otto) Date: Tue Dec 8 17:53:18 2009 Subject: [Haskell-beginners] using the current time Message-ID: Hi! We are trying to build a chatbot that can among many other things tell the partner what the current time is. Now obviously current time and pure functional programming don't mix well, but Haskell CAN do it. We have played around with it for a while and have figured out quite a bit, but the final icing is missing on the cake. It would be cool to have a dictionary like so > wissen = [ Einfache Begr??ung -> Frage nach dem Wohlbefinden > (["hallo", "hi", "hey"], "Hi, wie geht's?"), > (["guten tag", "tag"], "Wie geht es dir?")] (yes, the bot speaks German!) that could include a line like > (["Uhr","Zeit","sp?t"], time) where time is a function evaluating to a String including the current time. Once we have the time, we can get it translated into German by > formatiereZeit :: ClockTime -> String > formatiereZeit t > | (head(words (calendarTimeToString (toUTCTime t))) == "Mon") = "Montag" > | (head(words (calendarTimeToString (toUTCTime t))) == "Tue") = "Dienstag" > | (head(words (calendarTimeToString (toUTCTime t))) == "Wed") = "Mittwoch" > | (head(words (calendarTimeToString (toUTCTime t))) == "Thu") = "Donnerstag" > | (head(words (calendarTimeToString (toUTCTime t))) == "Fri") = "Freitag" > | (head(words (calendarTimeToString (toUTCTime t))) == "Sat") = "Samstag" > | (head(words (calendarTimeToString (toUTCTime t))) == "Sun") = "Sonntag" > | otherwise ="keine Uhr heute" which results in a string. Now how do we access the system time in a useful way? > time = formatiereZeit (NOW WHAT?) Would the current time step out of the IO monad, please? Regards, Torsten From t-otto-news at gmx.de Tue Dec 8 18:25:00 2009 From: t-otto-news at gmx.de (Torsten Otto) Date: Tue Dec 8 17:59:23 2009 Subject: [Haskell-beginners] recursively building lists In-Reply-To: <200912082343.07250.daniel.is.fischer@web.de> References: <1EE8DDB0-BF31-4185-8E80-E20D61A576BB@gmx.de> <200912082343.07250.daniel.is.fischer@web.de> Message-ID: <7CF39AA5-E1C2-42E1-99A6-5C4569816A1D@gmx.de> Thank you! I'll go hide in a dark corner... Torsten Am 08.12.2009 um 23:43 schrieb Daniel Fischer: > Am Dienstag 08 Dezember 2009 23:34:30 schrieb Torsten Otto: >> Hi! >> >> While trying to implement "words", we ran into the question of how to build >> lists of lists. The trouble boils down to this: >> >> test = []:[] >> >> is no problem, just as >> >> Prelude> []:[]:[]:[] >> [[],[],[]] >> >> works fine. Now trying to put the two together _is_ a problem: >> >> testlist 1 = []:[] >> testlist n = []:(testlist n-1) >> >> No instance for (Num [[a]]) >> arising from a use of `testlist' at :1:0-9 >> Possible fix: add an instance declaration for (Num [[a]]) >> In the expression: testlist 2 >> In the definition of `it': it = testlist 2 >> >> Can someone please explain, what is going on here? > > Yes. Function application has higher precedence than aritthmetic operations, so the RHS of > testlist n is parsed as > > [] : ( (testlist n) - 1) > > So, by the equation for testlist 1, the compiler knows that > > testlist :: (Num n) => n -> [[a]] > > In the second equation, you try to subtract 1 from a value of type [[a]], that means you > need a Num instance for that type. > > What you want is > > testlist n = []:testlist (n-1) > > HTH, > Daniel From ezyang at MIT.EDU Tue Dec 8 18:33:30 2009 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Tue Dec 8 18:07:55 2009 Subject: [Haskell-beginners] using the current time In-Reply-To: References: Message-ID: <1260314942-sup-7345@ezyang> Excerpts from Torsten Otto's message of Tue Dec 08 18:18:54 -0500 2009: > > time = formatiereZeit (NOW WHAT?) > > Would the current time step out of the IO monad, please? Unfortunately, there is no way to "step out" of the IO monad: once in the IO monad, always in the IO monad. However, if you let time be of type IO String instead of String, you can do: time = (liftM formatiereZeit) getClockTime Where liftM :: (a -> b) -> m a -> m b, i.e. it converts your function ClockTime -> String into IO ClockTime -> IO String. Cheers, Edward From daniel.is.fischer at web.de Tue Dec 8 18:39:38 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Dec 8 18:15:37 2009 Subject: [Haskell-beginners] using the current time In-Reply-To: References: Message-ID: <200912090039.39134.daniel.is.fischer@web.de> Am Mittwoch 09 Dezember 2009 00:18:54 schrieb Torsten Otto: > Hi! > > We are trying to build a chatbot that can among many other things tell the > partner what the current time is. Now obviously current time and pure > functional programming don't mix well, but Haskell CAN do it. We have > played around with it for a while and have figured out quite a bit, but the > final icing is missing on the cake. > > It would be cool to have a dictionary like so > > > wissen = [ > > Einfache Begr??ung -> Frage nach dem > Wohlbefinden > > > (["hallo", "hi", "hey"], "Hi, wie > > geht's?"), (["guten tag", "tag"], "Wie geht es dir?")] Unnecessarily verbose!!! (["Moin"], "Und?") > > (yes, the bot speaks German!) that could include a line like > > > (["Uhr","Zeit","sp?t"], time) > > where time is a function evaluating to a String including the current time. > > Once we have the time, we can get it translated into German by > > > formatiereZeit :: ClockTime -> String > > formatiereZeit t > > > > | (head(words (calendarTimeToString (toUTCTime t))) == "Mon") = "Montag" > > | (head(words (calendarTimeToString (toUTCTime t))) == "Tue") = "Dienstag" > > | (head(words (calendarTimeToString (toUTCTime t))) == "Wed") = "Mittwoch" > > | (head(words (calendarTimeToString (toUTCTime t))) == "Thu") = "Donnerstag" > > | (head(words (calendarTimeToString (toUTCTime t))) == "Fri") = "Freitag" > > | (head(words (calendarTimeToString (toUTCTime t))) == "Sat") = "Samstag" But that's wrong, it must be "Sonnabend", otherwise you're speaking Austrian or Bavarian, not German. > > | (head(words (calendarTimeToString (toUTCTime t))) == "Sun") = "Sonntag" > > | otherwise ="keine Uhr heute" > > which results in a string. Now how do we access the system time in a useful > way? > > > time = formatiereZeit (NOW WHAT?) > > Would the current time step out of the IO monad, please? Since the chatbot probably works in IO anyway, is it an option to have the second components of type IO String in general? If that is not possible, sacrifice a few virgins, spit over your left shoulder and contemplate using unsafePerformIO. > > Regards, > Torsten From jon at ffconsultancy.com Tue Dec 8 22:05:45 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue Dec 8 20:26:25 2009 Subject: [Haskell-beginners] Parallel mutation In-Reply-To: <200912082237.41730.daniel.is.fischer@web.de> References: <200912082056.46077.jon@ffconsultancy.com> <200912082237.41730.daniel.is.fischer@web.de> Message-ID: <200912090305.45456.jon@ffconsultancy.com> On Tuesday 08 December 2009 21:37:41 Daniel Fischer wrote: > Am Dienstag 08 Dezember 2009 21:56:45 schrieb Jon Harrop: > > Can you mutate different parts of the same array from different threads > > in parallel using GHC? Someone once told me this was possible but I > > cannot see how... > > You can (take a look at Control.Concurrent), but very probably ***You > really shouldn't***, so I won't elaborate. > > What would you want to do that for? Efficiency, e.g. parallel quicksort. -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From apfelmus at quantentunnel.de Wed Dec 9 05:38:15 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Wed Dec 9 05:13:03 2009 Subject: [Haskell-beginners] Re: text file to data type In-Reply-To: References: <1DAEE45C-4C94-4CEF-8448-5548963076F5@gmail.com> Message-ID: Patrick LeBoutillier wrote: > Heinrich Apfelmus wrote: >> >> import Data.ByteString.Lazy.Char8 as B >> >> parse = map (zipWith ($) formats . B.split '\t') . B.lines >> where >> formats = [str, str, int, int, int, int, int, >> int, int, float, float] >> int = fst . fromJust . readInt >> float = \s -> read (unpack s) :: Double >> str = id >> > > I've been looking at this example and I can't figure it out how it works. > Seems to me that "formats" is a list of functions that return different types. > How does this work? Oops. It doesn't. :D Mea culpa, the functions having different types is indeed a problem. Fortunately, the trick from Oliver Danvy's "Functional Unparsing" http://www.brics.dk/RS/98/12/BRICS-RS-98-12.pdf applies. Here's the code: import qualified Data.ByteString.Lazy.Char8 as B import Data.Maybe parse = map (convert format . B.split '\t') . B.lines where format = str . str . int . int . int . int . int . int . int . float . float int = lift $ fst . fromJust . B.readInt float = lift $ \s -> read (B.unpack s) :: Double str = lift $ id lift :: (a -> b) -> ([a] -> c) -> ([a] -> (b,c)) lift f k (x:xs) = (f x, k xs) convert k = k nil where nil [] = () This time, I've also tested it in GHCi. Try :type parse to see the magic type. Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From legajid at free.fr Wed Dec 9 16:40:51 2009 From: legajid at free.fr (legajid) Date: Wed Dec 9 16:11:17 2009 Subject: [Haskell-beginners] scope for variables Message-ID: <4B201963.7050004@free.fr> Hello, i wrote the following (very simplified) program : word :: [Char] word="initial" letters=['a'..'z'] myloop = do myloop2 myloop2 = do putStrLn word putStrLn letters main = do putStrLn "Enter the word" word <- enter_word myloop enter_word= do return("abcdefghij") "word" is initially binded to the value "initial" myloop, calling myloop2, displays this value "Improving" my program, i add "main" that enters a new value for "word" (here a fix one, ideally a getLine) To display this new value, i must call myloop with this parameter, which is then passed to myloop2. Is there a way to make a "global binding ?", thus changing the value of "word", so that i don't have to modify the code for myloop and myloop2 (now being passed a parameter), that worked fine. This would make the program modular and easy to modify, without modifying all existing functions. Or is it non-sense in Haskell ? Thanks, Didier. From uzytkownik2 at gmail.com Wed Dec 9 17:13:45 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Wed Dec 9 16:48:25 2009 Subject: [Haskell-beginners] Re: scope for variables In-Reply-To: <4B201963.7050004@free.fr> References: <4B201963.7050004@free.fr> Message-ID: <1260396822.2949.53.camel@picard> On Wed, 2009-12-09 at 22:40 +0100, legajid wrote: > Hello, > i wrote the following (very simplified) program : > > word :: [Char] > word="initial" > letters=['a'..'z'] > > myloop = do > myloop2 word from topmost declaration (="initial") if it was used > > myloop2 = do > putStrLn word word from topmost declaration (="initial") > putStrLn letters > > main = do > putStrLn "Enter the word" > word <- enter_word word="abcdefghij" and is local variable/constant. > myloop > > enter_word= do > return("abcdefghij") > > "word" is initially binded to the value "initial" > myloop, calling myloop2, displays this value > "Improving" my program, i add "main" that enters a new value for "word" > (here a fix one, ideally a getLine) > To display this new value, i must call myloop with this parameter, which > is then passed to myloop2. > Is there a way to make a "global binding ?", thus changing the value of > "word", so that i don't have to modify the code for myloop and myloop2 > (now being passed a parameter), that worked fine. This would make the > program modular and easy to modify, without modifying all existing > functions. Or is it non-sense in Haskell ? > It is practically 'non-sense' and would make a program less modular. If function depends on some value make it an argument. Generally you should avoid IO as much as possible. > Thanks, > Didier. Regards PS. Actually it is possible to do it with global variables but: 1. It uses an extentions 2. You should know why in most cases it is not what you want 3. It requires some knoledge about compilation process as 'officially' (w/out extention) it is nondeterministic. From mle+hs at mega-nerd.com Wed Dec 9 19:55:01 2009 From: mle+hs at mega-nerd.com (Erik de Castro Lopo) Date: Wed Dec 9 19:29:24 2009 Subject: [Haskell-beginners] Parallel mutation In-Reply-To: <200912090305.45456.jon@ffconsultancy.com> References: <200912082056.46077.jon@ffconsultancy.com> <200912082237.41730.daniel.is.fischer@web.de> <200912090305.45456.jon@ffconsultancy.com> Message-ID: <20091210115501.fe2e80df.mle+hs@mega-nerd.com> Jon Harrop wrote: > On Tuesday 08 December 2009 21:37:41 Daniel Fischer wrote: > > Am Dienstag 08 Dezember 2009 21:56:45 schrieb Jon Harrop: > > > Can you mutate different parts of the same array from different threads > > > in parallel using GHC? Someone once told me this was possible but I > > > cannot see how... > > > > You can (take a look at Control.Concurrent), but very probably ***You > > really shouldn't***, so I won't elaborate. > > > > What would you want to do that for? > > Efficiency, e.g. parallel quicksort. So why not look at Data Parallel Haskell: http://www.haskell.org/haskellwiki/GHC/Data_Parallel_Haskell Erik -- ---------------------------------------------------------------------- Erik de Castro Lopo http://www.mega-nerd.com/ From mle+hs at mega-nerd.com Wed Dec 9 20:00:55 2009 From: mle+hs at mega-nerd.com (Erik de Castro Lopo) Date: Wed Dec 9 19:35:17 2009 Subject: [Haskell-beginners] Parallel mutation In-Reply-To: <20091210115501.fe2e80df.mle+hs@mega-nerd.com> References: <200912082056.46077.jon@ffconsultancy.com> <200912082237.41730.daniel.is.fischer@web.de> <200912090305.45456.jon@ffconsultancy.com> <20091210115501.fe2e80df.mle+hs@mega-nerd.com> Message-ID: <20091210120055.7341df55.mle+hs@mega-nerd.com> Erik de Castro Lopo wrote: > So why not look at Data Parallel Haskell: > > http://www.haskell.org/haskellwiki/GHC/Data_Parallel_Haskell Quicksort example: http://darcs.haskell.org/ghc-6.10/packages/dph/examples/qsort/ I haven't tested this. Erik -- ---------------------------------------------------------------------- Erik de Castro Lopo http://www.mega-nerd.com/ From dav.vire+haskell at gmail.com Thu Dec 10 03:17:47 2009 From: dav.vire+haskell at gmail.com (David Virebayre) Date: Thu Dec 10 02:52:06 2009 Subject: [Haskell-beginners] scope for variables In-Reply-To: <4B201963.7050004@free.fr> References: <4B201963.7050004@free.fr> Message-ID: <4c88418c0912100017y6c7572c3u6f11a795c25cd651@mail.gmail.com> Forgot to post the list :( On Wed, Dec 9, 2009 at 10:40 PM, legajid wrote: > Hello, > i wrote the following (very simplified) program : > > word :: [Char] > word="initial" > letters=['a'..'z'] > > myloop = do > myloop2 > > myloop2 = do > putStrLn word > putStrLn letters > > main = do > putStrLn "Enter the word" > word <- enter_word > myloop > enter_word= do > return("abcdefghij") > Remind that a haskell function depends only on its parameters. Unless you use an unsafe trick, often frowned upon, mutable global variables don't exist. So normally you have to modify your functions to pass the string as a parameter. While it may seem tedious at first, perhaps you will realise that having the type signature mention that you need a string is a precious information. Also, start by modifying only myloop2, ghc will complain about every function that use the new myloop2 the wrong way, so refactoring is not that hard. In the case you have a more complicated program where state is an important part, you can use the State monad, or more specifically in your example a State transformer that uses IO as the underlying monad. Your program would look like : ( you can copy and paste this in a source file, then play with it in ghci ) module Main where import Control.Monad.State word :: [Char] word="initial" letters=['a'..'z'] myloop = do myloop2 myloop2 = do word <- get -- r?cup?re l'?tat. liftIO $ do putStrLn word putStrLn letters main = runStateT mafonction word mafonction = do liftIO $ putStrLn "Enter the word" w <- enter_word put w -- enregistre l'?tat myloop enter_word= do return("abcdefghij") Note how the myloop function wasn't modified. On the other hand, have a look at the type signatures using ghci. Your function now is in the StateT String IO monad. So that's why every time you use IO you have to use liftIO to reach the underlying IO monad. So there's still some rewriting. David. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091210/7682d3c4/attachment.html From mklklk at hotmail.com Thu Dec 10 05:50:11 2009 From: mklklk at hotmail.com (Kui Ma) Date: Thu Dec 10 05:24:29 2009 Subject: [Haskell-beginners] how to use regex replace In-Reply-To: <4c88418c0912100017y6c7572c3u6f11a795c25cd651@mail.gmail.com> References: <4B201963.7050004@free.fr>, <4c88418c0912100017y6c7572c3u6f11a795c25cd651@mail.gmail.com> Message-ID: Hi, Can anyone introduce me how to use regex replace or give me web page links about this topic? thank you in advance! Regards _________________________________________________________________ Windows Live: Friends get your Flickr, Yelp, and Digg updates when they e-mail you. http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_3:092010 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091210/487039e0/attachment.html From builes.adolfo at googlemail.com Thu Dec 10 12:20:40 2009 From: builes.adolfo at googlemail.com (Adolfo Builes) Date: Thu Dec 10 11:54:58 2009 Subject: [Haskell-beginners] how to use regex replace In-Reply-To: References: <4B201963.7050004@free.fr> <4c88418c0912100017y6c7572c3u6f11a795c25cd651@mail.gmail.com> Message-ID: Hi, Bryan O'Sullivan has an excellent blog post about regex [1]. You could also check Real World Haskell [2]. [1]- http://www.serpentine.com/blog/2007/02/27/a-haskell-regular-expression-tutorial/ [2]- http://book.realworldhaskell.org/read/efficient-file-processing-regular-expressions-and-file-name-matching.html#glob.regex 2009/12/10 Kui Ma > Hi, > > Can anyone introduce me how to use regex replace or give me web page links > about this topic? thank you in advance! > > Regards > > ------------------------------ > Windows Live: Friends get your Flickr, Yelp, and Digg updates when they > e-mail you. > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091210/d28c7f48/attachment.html From korpios at korpios.com Thu Dec 10 12:56:56 2009 From: korpios at korpios.com (Tom Tobin) Date: Thu Dec 10 12:31:15 2009 Subject: [Haskell-beginners] how to use regex replace In-Reply-To: References: <4B201963.7050004@free.fr> <4c88418c0912100017y6c7572c3u6f11a795c25cd651@mail.gmail.com> Message-ID: On Thu, Dec 10, 2009 at 11:20 AM, Adolfo Builes wrote: > Hi, > Bryan O'Sullivan has an excellent blog post about regex [1]. You could also > check Real World Haskell [2]. > > [1]- > http://www.serpentine.com/blog/2007/02/27/a-haskell-regular-expression-tutorial/ > [2]- > http://book.realworldhaskell.org/read/efficient-file-processing-regular-expressions-and-file-name-matching.html#glob.regex I'd actually recommend the pcre-light package: http://hackage.haskell.org/package/pcre-light Not only does it give you Perl-compatible regexes, but it also *doesn't* force you through the IO monad. It's good stuff. From jakubuv at gmail.com Thu Dec 10 12:57:59 2009 From: jakubuv at gmail.com (Jan Jakubuv) Date: Thu Dec 10 12:32:35 2009 Subject: [Haskell-beginners] how to use regex replace In-Reply-To: References: <4c88418c0912100017y6c7572c3u6f11a795c25cd651@mail.gmail.com> Message-ID: <20091210175758.GA25239@lxultra2.macs.hw.ac.uk> Hi, Would Text.Regex.subRegex do? It is in package regex-compat. Usage is easy, see [1]. Sincerely, jan. [1]: http://hackage.haskell.org/packages/archive/regex-compat/0.92/doc/html/Text-Regex.html On Thu, Dec 10, 2009 at 06:50:11PM +0800, Kui Ma wrote: > > Hi, > > Can anyone introduce me how to use regex replace or give me web page links about this topic? thank you in advance! > > Regards > -- Heriot-Watt University is a Scottish charity registered under charity number SC000278. From hyangfji at gmail.com Fri Dec 11 00:25:02 2009 From: hyangfji at gmail.com (Hong Yang) Date: Thu Dec 10 23:59:18 2009 Subject: [Haskell-beginners] Is there a function to determine if a date is a business day? Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091210/064cc6fc/attachment.html From colin at colina.demon.co.uk Fri Dec 11 01:20:46 2009 From: colin at colina.demon.co.uk (Colin Paul Adams) Date: Fri Dec 11 00:55:08 2009 Subject: [Haskell-beginners] Is there a function to determine if a date is a business day? In-Reply-To: (Hong Yang's message of "Thu\, 10 Dec 2009 23\:25\:02 -0600") References: Message-ID: You will need to write it, as it depends upon your definition of what a business day is. This tends to be country-specific (at least). -- Colin Adams Preston Lancashire From andy.elvey at paradise.net.nz Fri Dec 11 01:43:52 2009 From: andy.elvey at paradise.net.nz (Andy Elvey) Date: Fri Dec 11 01:18:04 2009 Subject: [Haskell-beginners] Is there a function to determine if a date is a business day? In-Reply-To: References: Message-ID: <4B21EA28.9000506@paradise.net.nz> Colin Paul Adams wrote: > You will need to write it, as it depends upon your definition of what > a business day is. > This tends to be country-specific (at least). > Agreed. I'm a Haskell-newbie so I can't give the Haskell code for this, but in "pseudo-code" it would be something like this - holidays_list = ["09JAN", "06FEB", ..... ] ( This will vary depending on country ) if myday not in holidays_list and day(myday) in ["Mon", "Tue", "Wed", "Thu", "Fri"] then business_day(myday) = "Yes" else business_day(myday) = "No" Some countries have a "Holidays Act" or similar legislation which specifies the holidays for the current year and the next few years. Hope this helps.... :) - Andy From functionallyharmonious at yahoo.com Fri Dec 11 02:14:06 2009 From: functionallyharmonious at yahoo.com (M Xyz) Date: Fri Dec 11 01:48:20 2009 Subject: [Haskell-beginners] Printing the bits of an Int|Double Message-ID: <111262.47331.qm@web113102.mail.gq1.yahoo.com> I've been trying to play around with binary data, but I haven't made much progress trying to print the bits of a Double. With help from #haskell I've made it this far: -- Printing the bits of an Int main = do putStrLn $ showIntAtBase 2 (chr . (48+)) z "" -- 103 = 1100111, after bit shifting 11001 z = shiftR (103 :: Int64) 2 This is as far as I got with Doubles: import Data.Binary.IEEE754 import qualified Data.ByteString.Lazy as BS main = do BS.putStrLn $ runPut $ putFloat64be 4.123 Instead of playing with ByteStrings, is there just a way to fill an Int64 with the bits of a Double (Similar to Java's long = Double.doubleToLongBits(double))? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091211/4f107c25/attachment.html From deniz.a.m.dogan at gmail.com Fri Dec 11 04:35:14 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Fri Dec 11 04:09:50 2009 Subject: [Haskell-beginners] Is there a function to determine if a date is a business day? In-Reply-To: References: Message-ID: <7b501d5c0912110135j10e002feo455289eb4d2d45de@mail.gmail.com> 2009/12/11 Hong Yang : > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > I don't know, but wouldn't it be nice if there was some package dealing with "cultures"? Something along the lines of: data Culture = Culture { country :: Country, language :: Language, isHoliday :: (Day -> Bool), firstDayOfWeek :: Day, ... } -- Deniz Dogan From Gaius at Gaius.org.UK Fri Dec 11 04:42:20 2009 From: Gaius at Gaius.org.UK (Gaius Hammond) Date: Fri Dec 11 04:17:57 2009 Subject: [Haskell-beginners] Is there a function to determine if a date isa business day? Message-ID: <595676302-1260524619-cardhu_decombobulator_blackberry.rim.net-1618751805-@bda221.bisx.produk.on.blackberry> You can buy this data from companies like Reuters. They collate it by having someone phone every embassy every year. Cheers, G ------Original Message------ From: Deniz Dogan Sender: beginners-bounces@haskell.org To: Hong Yang Cc: beginners@haskell.org Subject: Re: [Haskell-beginners] Is there a function to determine if a date isa business day? Sent: 11 Dec 2009 09:35 2009/12/11 Hong Yang : > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > I don't know, but wouldn't it be nice if there was some package dealing with "cultures"? Something along the lines of: data Culture = Culture { country :: Country, language :: Language, isHoliday :: (Day -> Bool), firstDayOfWeek :: Day, ... } -- Deniz Dogan _______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners ------------------ From Alistair.Bayley at invesco.com Fri Dec 11 04:47:01 2009 From: Alistair.Bayley at invesco.com (Bayley, Alistair) Date: Fri Dec 11 04:21:18 2009 Subject: [Haskell-beginners] Is there a function to determine if a dateisa business day? In-Reply-To: <595676302-1260524619-cardhu_decombobulator_blackberry.rim.net-1618751805-@bda221.bisx.produk.on.blackberry> References: <595676302-1260524619-cardhu_decombobulator_blackberry.rim.net-1618751805-@bda221.bisx.produk.on.blackberry> Message-ID: <125EACD0CAE4D24ABDB4D148C4593DA91102650D@GBLONXMB02.corp.amvescap.net> > From: beginners-bounces@haskell.org > [mailto:beginners-bounces@haskell.org] On Behalf Of Gaius Hammond > > You can buy this data from companies like Reuters. They > collate it by having someone phone every embassy every year. Or: http://en.wikipedia.org/wiki/List_of_holidays_by_country Alistair ***************************************************************** Confidentiality Note: The information contained in this message, and any attachments, may contain confidential and/or privileged material. It is intended solely for the person(s) or entity to which it is addressed. Any review, retransmission, dissemination, or taking of any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you received this in error, please contact the sender and delete the material from any computer. ***************************************************************** From stephen.tetley at gmail.com Fri Dec 11 09:05:07 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Dec 11 08:39:23 2009 Subject: [Haskell-beginners] Printing the bits of an Int|Double In-Reply-To: <111262.47331.qm@web113102.mail.gq1.yahoo.com> References: <111262.47331.qm@web113102.mail.gq1.yahoo.com> Message-ID: <5fdc56d70912110605j1b095c5fk5d00d96fc60a6d48@mail.gmail.com> Hello M Xyz Here's a module[1] that seems to work for single precision floats - you might want to do some checking of random numbers with toAndFro (there's plenty of room for errors). The print functions is printBin uses showIntAtBase which doesn't pad with leading zeros, you might want to add them. Best wishes Stephen [1] I wrote it a while ago but checking this morning it had some nefarious bugs in. module PrintIeeeFloat where import Data.Bits import Data.Char import Data.Word import Numeric const_B :: Int const_B = 127 printBin :: (Fractional a,Ord a) => a -> ShowS printBin a = f s . showChar ' ' . f t . showChar ' ' . f u . showChar ' ' . f v where f = showIntAtBase 2 (chr . (48+)) (s,t,u,v) = packIEEESingle a toAndFro :: (Fractional a, Ord a) => a -> a toAndFro a = let (s,t,u,v) = packIEEESingle a in unpackIEEESingle s t u v unpackIEEESingle :: Fractional a => Word8 -> Word8 -> Word8 -> Word8 -> a unpackIEEESingle b24_31 b16_23 b8_15 b0_7 = sign $ fract * (2 ^^ expo) where sign = if b24_31 `testBit` 7 then negate else id expo = exponent' b24_31 b16_23 fract = fraction b16_23 b8_15 b0_7 exponent' :: Word8 -> Word8 -> Int exponent' a b = (a' `shiftL` 1) + (b' `shiftR` 7) - 127 where a' = fromIntegral $ (a .&. 0x7f) b' = fromIntegral $ (b .&. 0x80) fraction :: Fractional a => Word8 -> Word8 -> Word8 -> a fraction b16_24 b8_15 b0_7 = 1.0 + ((fromIntegral frac) / (2 ^^ 23)) where frac :: Int frac = (shiftL16 (b16_24 .&. 0x7f)) + (shiftL8 b8_15) + fromIntegral b0_7 packIEEESingle :: (Fractional a,Ord a) => a -> (Word8,Word8,Word8,Word8) packIEEESingle a = (flipSign b24_31, exp_part+mant_part, b8_15, b0_7) where k = findPosExpo $ abs a e = k + const_B halfa = (abs a) / (2 ^^ fromIntegral k) f = expand $ halfa - 1 (b24_31, exp_part) = expoWords e (mant_part,b8_15, b0_7) = mantWords f flipSign = if a > 0 then id else (`setBit` 7) findPosExpo :: (Fractional a, Ord a) => a -> Int findPosExpo r | r <= 0 = 0 | otherwise = step r 1 where step r' k | r <= fromIntegral 2 ^^ k = k-1 | otherwise = step r' (k+1) expand :: (Fractional a, Ord a) => a -> Word32 expand n = (`shiftR` 9) $ step n 0 id where step x ix f | x <= 0 = f (0::Word32) | otherwise = let y = 1 / (2 ^^ (ix+1)) in if x >= y then step (x-y) (ix+1) (f . (`setBit` (31-ix))) else step x (ix+1) f -- 7 bits left, 1 bit right expoWords :: Int -> (Word8,Word8) expoWords n = (left, right) where right = if n `testBit` 0 then 128 else 0 left = fromIntegral $ n `shiftR` 1 mantWords :: Word32 -> (Word8,Word8,Word8) mantWords x = (a,b,c) where c = fromIntegral $ x .&. 0xff b = fromIntegral $ (`shiftR` 8) $ x .&. 0xff00 a = fromIntegral $ (`shiftR` 16) $ x .&. 0xff0000 shiftL8 :: (Bits b, Integral b) => Word8 -> b shiftL8 = (`shiftL` 8) . fromIntegral shiftL16 :: (Bits b, Integral b) => Word8 -> b shiftL16 = (`shiftL` 16) . fromIntegral shiftL24 :: (Bits b, Integral b) => Word8 -> b shiftL24 = (`shiftL` 24) . fromIntegral w32be :: Word8 -> Word8 -> Word8 -> Word8 -> Word32 w32be a b c d = (shiftL24 a) + (shiftL16 b) + (shiftL8 c) + fromIntegral d 2009/12/11 M Xyz > > I've been trying to play around with binary data, but I haven't made much progress > trying to print the bits of a Double. With help from #haskell I've made it this far: > > -- Printing the bits of an Int > main = do putStrLn $ showIntAtBase 2 (chr . (48+)) z "" > > -- 103 = 1100111, after bit shifting 11001 > z = shiftR (103 :: Int64) 2 > > This is as far as I got with Doubles: > > import Data.Binary.IEEE754 > import qualified Data.ByteString.Lazy as BS > main = do BS.putStrLn $ runPut $ putFloat64be 4.123 > > Instead of playing with ByteStrings, is there just a way to fill an Int64 with the bits of a Double (Similar to Java's long = Double.doubleToLongBits(double))? > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From stephen.tetley at gmail.com Fri Dec 11 09:29:06 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Dec 11 09:03:22 2009 Subject: [Haskell-beginners] Printing the bits of an Int|Double In-Reply-To: <5fdc56d70912110605j1b095c5fk5d00d96fc60a6d48@mail.gmail.com> References: <111262.47331.qm@web113102.mail.gq1.yahoo.com> <5fdc56d70912110605j1b095c5fk5d00d96fc60a6d48@mail.gmail.com> Message-ID: <5fdc56d70912110629s5bd59d75nca0032554183a530@mail.gmail.com> Further... If you need double precision you might have to do it yourself. In absence of comments in the code I posted, the algorithm I used for single precision is from here: http://www.utdallas.edu/~cantrell/ee6481/lectures/float_comp.pdf Eventually I'll get around to double precision, but not soon. Best wishes Stephen From mklklk at hotmail.com Fri Dec 11 09:40:18 2009 From: mklklk at hotmail.com (Kui Ma) Date: Fri Dec 11 09:14:33 2009 Subject: [Haskell-beginners] how to use regex replace In-Reply-To: <20091210175758.GA25239@lxultra2.macs.hw.ac.uk> References: <4c88418c0912100017y6c7572c3u6f11a795c25cd651@mail.gmail.com> , <20091210175758.GA25239@lxultra2.macs.hw.ac.uk> Message-ID: yes it's very simple but does satisfy my need. Thank you very much! actually I had spent time researching the regex packages on Hackage, it seems they doesn't provide such APIs for replace, but from my point of view the use of *replace* is as imporant as *match* in regular expression. Or I didn't find the right place? Thanks again! > Date: Thu, 10 Dec 2009 17:57:59 +0000 > From: jakubuv@gmail.com > To: mklklk@hotmail.com > CC: beginners@haskell.org > Subject: Re: [Haskell-beginners] how to use regex replace > > Hi, > > Would Text.Regex.subRegex do? It is in package regex-compat. Usage is > easy, see [1]. > > Sincerely, > jan. > > [1]: http://hackage.haskell.org/packages/archive/regex-compat/0.92/doc/html/Text-Regex.html > > On Thu, Dec 10, 2009 at 06:50:11PM +0800, Kui Ma wrote: > > > > Hi, > > > > Can anyone introduce me how to use regex replace or give me web page links about this topic? thank you in advance! > > > > Regards > > > > > -- > Heriot-Watt University is a Scottish charity > registered under charity number SC000278. > _________________________________________________________________ Keep your friends updated?even when you?re not signed in. http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_5:092010 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091211/986a1119/attachment.html From deolivem at gmail.com Fri Dec 11 19:17:38 2009 From: deolivem at gmail.com (Marco De Oliveira) Date: Fri Dec 11 18:51:51 2009 Subject: [Haskell-beginners] How to create a monad instance Message-ID: Hi, Is it possible to create an instance of Monad for IOException? Each time a try I stay blocked by IO monad. with the definition: data IOException a = IOExceptionCons (IO (Exception a)) data Exception a = SuccessCons (Maybe Warning) a | ErrorCons Error data Warning = WarningCons1 | WarningCons2 data Error = ErrorCons1 | ErrorCons2 Regards From vss at 73rus.com Fri Dec 11 19:58:11 2009 From: vss at 73rus.com (Vlad Skvortsov) Date: Fri Dec 11 19:31:45 2009 Subject: [Haskell-beginners] writing many1Till combinator for Parsec Message-ID: <4B22EAA3.1080306@73rus.com> Hi, I'm writing a parser where I find myself in need to use manyTill combinator with an additional constraint that there should be at least one meaningful element before the trailer (say, a word ended with a period: 'abc.'). Here is what I have: many1Till :: Parser a -> Parser end -> Parser [a] many1Till p end = do p1 <- p ps <- manyTill p end return (p1:ps) The problem here is that I want to catch and report a case when 'p1' could be actually parsed by 'end' ('..' is not a word ended by a period). Generally 'p' and 'end' can parse the same subset of strings. Another version a had was: many1Till :: Parser a -> Parser end -> Parser [a] many1Till p end = do try (end >> (unexpected "sequence terminator")) <|> (do { p1 <- p; ps <- manyTill p end; return (p1:ps) }) Here there are two disadvantages: 1) I don't like hardcoding "sequence terminator" here; 2) the error output should say that only 'p' parser is expected, while it says (technically correct) that either 'p' or 'end' is expected: Prelude Main Text.ParserCombinators.Parsec> parseTest (many1Till letter (char '.')) "1" parse error at (line 1, column 1): unexpected "1" expecting "." or letter (What I want here is to say "expecting letter") Any suggestions? Thanks! -- Vlad Skvortsov, vss@73rus.com, http://vss.73rus.com From uzytkownik2 at gmail.com Fri Dec 11 20:38:13 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Fri Dec 11 20:12:49 2009 Subject: [Haskell-beginners] Re: How to create a monad instance In-Reply-To: References: Message-ID: <1260581893.2597.60.camel@picard> On Sat, 2009-12-12 at 01:17 +0100, Marco De Oliveira wrote: > Hi, > > Is it possible to create an instance of Monad for IOException? > Each time a try I stay blocked by IO monad. > > with the definition: > > data IOException a = IOExceptionCons (IO (Exception a)) > > data Exception a = SuccessCons (Maybe Warning) a > | ErrorCons Error > > data Warning = WarningCons1 > | WarningCons2 > > data Error = ErrorCons1 > | ErrorCons2 > > Regards Yes - to begin with: newtype IOException a = IOException {runIOException :: IO (Exception a)} data Exception a = Success (Maybe Warning) a | Exception Error data Warning = Warning1 | Warning2 data Error = Error1 | Error2 instance Monad Exception where return = Success Nothing (Success w v) >>= f = f v -- (Success w v) >>= f = case f v of -- Success _ v' -> Success w v' -- Exception e -> Exception e (Exception e) >>= _ = Exception e instance Monad IOException where return = IOException . return . return m >>= f = IOException $ runIOException m >>= runIOException . f However: 1. What should be the combination of warnings I'd rather threat them as some 'proper' monoid (for ex. List instead of Maybe) 2. It is much easier to use mtl: type IOException = ErrorT (Either Error) (WriterT [Warning] IO) Regards From functionallyharmonious at yahoo.com Fri Dec 11 21:46:22 2009 From: functionallyharmonious at yahoo.com (M Xyz) Date: Fri Dec 11 21:20:36 2009 Subject: [Haskell-beginners] Printing the bits of an Int|Double In-Reply-To: <5fdc56d70912110629s5bd59d75nca0032554183a530@mail.gmail.com> Message-ID: <837490.86131.qm@web113102.mail.gq1.yahoo.com> Thanks Stephen for your response. With the help of #haskell I was actually able to find my answer: import Char import Numeric import Data.Bits import Data.Binary.Put import Data.Binary.IEEE754 import qualified Data.ByteString.Lazy as LBS main = do putStrLn . show $ map getBits (LBS.unpack . runPut $ putFloat64be 4.123) getBits i = showIntAtBase 2 (chr . (48+)) i "" --- On Fri, 12/11/09, Stephen Tetley wrote: From: Stephen Tetley Subject: Re: [Haskell-beginners] Printing the bits of an Int|Double To: "M Xyz" Cc: beginners@haskell.org Date: Friday, December 11, 2009, 9:29 AM Further... If you need double precision you might have to do it yourself. In absence of comments in the code I posted, the algorithm I used for single precision is from here: http://www.utdallas.edu/~cantrell/ee6481/lectures/float_comp.pdf Eventually I'll get around to double precision, but not soon. Best wishes Stephen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091211/611c18ed/attachment.html From deolivem at gmail.com Sat Dec 12 05:18:51 2009 From: deolivem at gmail.com (Marco De Oliveira) Date: Sat Dec 12 04:53:04 2009 Subject: [Haskell-beginners] Re: How to create a monad instance In-Reply-To: <1260581893.2597.60.camel@picard> References: <1260581893.2597.60.camel@picard> Message-ID: 2009/12/12 Maciej Piechotka : > On Sat, 2009-12-12 at 01:17 +0100, Marco De Oliveira wrote: >> Hi, >> >> Is it possible to create an instance of Monad for IOException? >> Each time a try I stay blocked by IO monad. >> >> with the definition: >> >> data IOException a = IOExceptionCons (IO (Exception a)) >> >> data Exception a = SuccessCons (Maybe Warning) a >> ? ? ? ? ? ? ? ? ? ? ? ? ? | ErrorCons Error >> >> data Warning = WarningCons1 >> ? ? ? ? ? ? ? ? ? ? | WarningCons2 >> >> data Error = ErrorCons1 >> ? ? ? ? ? ? ? ? | ErrorCons2 >> >> Regards > > Yes - to begin with: > > newtype IOException a = IOException {runIOException :: IO (Exception a)} > > data Exception a = Success (Maybe Warning) a > ? ? ? ? ? ? ? ? | Exception Error > > data Warning = Warning1 > ? ? ? ? ? ? | Warning2 > data Error = Error1 > ? ? ? ? ? | Error2 > > instance Monad Exception where > ? ?return = Success Nothing > ? ?(Success w v) >>= f = f v > -- ? ?(Success w v) >>= f = case f v of > -- ? ? ? ? ? ? ? ? ? ? ? ? ? ?Success _ v' -> Success w v' > -- ? ? ? ? ? ? ? ? ? ? ? ? ? ?Exception e ?-> Exception e > ? ?(Exception e) >>= _ = Exception e > instance Monad IOException where > ? ?return = IOException . return . return > ? ?m >>= f = IOException $ runIOException m >>= runIOException . f > > However: > 1. What should be the combination of warnings I'd rather threat them as > some 'proper' monoid (for ex. List instead of Maybe) > 2. It is much easier to use mtl: > type IOException = ErrorT (Either Error) (WriterT [Warning] IO) > > Regards > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > Thanks for your help. I have try your code ghci and I think there is a mistake in the definition of (>>=) operator. test1 m f = IOException $ runIOException m >>= runIOException . f :t test1 test1 :: IOException a -> (Exception a -> IOException a) -> IOException a I think the defintion is: test :: IOException a -> ( a -> IOException a) -> IOException a 1. why I am not using monoid? I try to bind C code and the function return only one warning. But if I change i little the structure of IOException, it may have sense to use a List. newtype IOException a = IOException {runIOException :: ([Warning] -> IO (Exception a))} 2. Sorry but I have a lot of difficulties to understand the concept of Monad Transformers From shujinw at gmail.com Tue Dec 8 20:17:25 2009 From: shujinw at gmail.com (Jacob Faren) Date: Sat Dec 12 05:03:30 2009 Subject: [Haskell-beginners] Problem implementing a stack Message-ID: <884667f90912081717u1a3026baxde3ed93c137fb1dd@mail.gmail.com> Hello. I'm implement data structures (a stack, here) to get familiar with Haskell. It's not going very well. I have the following code... -- test.hs data Stack a = Top (Stack a) | Layers [a] deriving (Show) stack :: Stack a stack = Top (Layers []) push :: Stack a -> a -> Stack a push (Top (Layers ls)) value = Top (Layers (value:ls)) And I run the following in ghci... Prelude> :l test [1 of 1] Compiling Main ( test.hs, interpreted ) Ok, modules loaded: Main. *Main> push stack 4 Top (Layers [4]) *Main> let st = stack *Main> push st 4 ^CInterrupted. The output of the last command never resolves. I have to kill it. Might anyone have an idea why the push function is failing with st, but not with stack? I know there are other stack implementations that work, but I really want to know what's going on here. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091208/dbf45886/attachment.html From chaddai.fouche at gmail.com Sat Dec 12 06:03:05 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Sat Dec 12 05:37:17 2009 Subject: [Haskell-beginners] Problem implementing a stack In-Reply-To: <884667f90912081717u1a3026baxde3ed93c137fb1dd@mail.gmail.com> References: <884667f90912081717u1a3026baxde3ed93c137fb1dd@mail.gmail.com> Message-ID: On Wed, Dec 9, 2009 at 2:17 AM, Jacob Faren wrote: > Hello. I'm implement data structures (a stack, here) to get familiar with > Haskell. It's not going very well. I have the following code... > > ??? -- test.hs > ??? data Stack a = Top (Stack a) | Layers [a] deriving (Show) > > ??? stack :: Stack a > ??? stack = Top (Layers []) > > ??? push :: Stack a -> a -> Stack a > ??? push (Top (Layers ls)) value = Top (Layers (value:ls)) > > And I run the following in ghci... > > ??? Prelude> :l test > ??? [1 of 1] Compiling Main???????????? ( test.hs, interpreted ) > ??? Ok, modules loaded: Main. > ??? *Main> push stack 4 > ??? Top (Layers [4]) > ??? *Main> let st = stack > ??? *Main> push st 4 > ??? ^CInterrupted. > > The output of the last command never resolves. I have to kill it. Might > anyone have an idea why the push function is failing with st, but not > with stack? It shouldn't, and it doesn't here, which version of GHC are you using ? By the way, your Stack datatype seems broken to me, what would be the meaning of (Top (Top (Top (Layers []))) ? I do believe that you do not wish to allow anything besides a Layers inside a Top, and your push function supports this interpretation. In this case, your Layers constructor is unnecessary and your datatype declaration should be : > data Stack a = Top [a] deriving (Show) At which point you may realize that this type is isomorphic to the list type (+ one bottom) and thus is better written : - Either as a type synonym : type Stack a = [a] - Or if you wish to ensure some invariants on your type or add some typeclass instances specific to stacks : newtype Stack a = Top [a] deriving (Show) -- Jeda? From daniel.is.fischer at web.de Sat Dec 12 08:16:12 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Dec 12 07:51:54 2009 Subject: [Haskell-beginners] writing many1Till combinator for Parsec In-Reply-To: <4B22EAA3.1080306@73rus.com> References: <4B22EAA3.1080306@73rus.com> Message-ID: <200912121416.12881.daniel.is.fischer@web.de> Am Samstag 12 Dezember 2009 01:58:11 schrieb Vlad Skvortsov: > Hi, > > I'm writing a parser where I find myself in need to use manyTill > combinator with an additional constraint that there should be at least > one meaningful element before the trailer (say, a word ended with a > period: 'abc.'). > > Here is what I have: > > many1Till :: Parser a -> Parser end -> Parser [a] > many1Till p end = do notFollowedBy end > p1 <- p > ps <- manyTill p end > return (p1:ps) > You want a nonempty sequence of 'p's which aren't 'end's, followed by an 'end'. So you could do for example a) many1Till p end = do ps <- manyTill p end guard (not $ null ps) return ps , i.e. check whether the result of manyTill is a nonempty list after the fact, or check whether manyTill p end will return an empty list before manyTill is run, like b) many1Till p end = do notFollowedBy end manyTill p end (i.e. many1Till p end = notFollowedBy end >> manyTill p end). > The problem here is that I want to catch and report a case when 'p1' > could be actually parsed by 'end' ('..' is not a word ended by a > period). Generally 'p' and 'end' can parse the same subset of strings. > > Another version a had was: > > many1Till :: Parser a -> Parser end -> Parser [a] > many1Till p end = do > try (end >> (unexpected "sequence terminator")) > <|> (do { p1 <- p; ps <- manyTill p end; return (p1:ps) }) > > Here there are two disadvantages: > > 1) I don't like hardcoding "sequence terminator" here; > 2) the error output should say that only 'p' parser is expected, while > it says (technically correct) that either 'p' or 'end' is expected: > > Prelude Main Text.ParserCombinators.Parsec> parseTest (many1Till letter > (char '.')) "1" > parse error at (line 1, column 1): > unexpected "1" > expecting "." or letter > > (What I want here is to say "expecting letter") For that, you need the slightly clumsier c) many1Till p end = do notFollowedBy end p1 <- p ps <- manyTill p end return (p1:ps) > > Any suggestions? > > Thanks! From streborg at hotmail.com Sat Dec 12 21:11:28 2009 From: streborg at hotmail.com (Glurk) Date: Sat Dec 12 20:46:03 2009 Subject: [Haskell-beginners] Applicability of FP unchanging things to real world changing things Message-ID: I come from an OO background, but have recently started to see the light and think that functional programming has a lot to offer in real world, general software development - not just some small specific niche. Having the OO background certainly has limited the way I view software development, and I guess in learning something new, I have a tendency to compare it with what I do know, looking for similarities and differences. So, perhaps that's why I am having difficulty in seeing how some functional programming ideas apply. What's got me a little puzzled at the moment is non mutable data. On the one hand, I think it's great that I can mostly forget about errors caused by my variables having unexpected values, and that I can reason about my program much more easily... However, on the other hand, I wonder how it ties in with real world systems that do in fact do deal with objects that change state. For example, if I was building a library system - I might have book objects, and if a book gets borrowed, there remains the same book object, but it now just has a different state - from "on shelf" say, to "borrowed". Now, in Haskell, I might have a function to lend a book :- lend book1 and this is going to return a new book, with the appropriate status change.. ..but what of the old book ? I don't want 2 book objects floating around.. ...to my way of thinking, it's really not a new book, it really is a change of state. How do people see this kind of situation ? Is it just the way of looking at it... ? Do I just accept that I toss out my old library object, and have a new one, which happens to be the same as the old one, except for the "new" book which is now borrowed ? Do I really need to get over thinking of objects in the first place, even though it's what I see exist in the real world ? Is there where we part company with non mutability and venture into the monads where we do have side effects ? Any thoughts appreciated ! :) Thanks ! From ml at isaac.cedarswampstudios.org Sat Dec 12 21:36:37 2009 From: ml at isaac.cedarswampstudios.org (Isaac Dupree) Date: Sat Dec 12 21:11:00 2009 Subject: [Haskell-beginners] Applicability of FP unchanging things to real world changing things In-Reply-To: References: Message-ID: <4B245335.9030501@isaac.cedarswampstudios.org> Computers think discretely. Even the OO book is probably not going to recognize the book's every move as it falls into someone's hands, wanders around the library, perhaps sneaks out of the library or is reshelved somewhere else, is checked out and goes across the globe, has the cover torn and then taped together into pretty-good shape... I prefer FP because it acknowledges that computers fundamentally operate like this. They model and approximate situations. Sometimes pretending to be those situations is not the best way to approximate them. ...[tried to give example but I'm too dizzy at the moment from finals-week] From jli at circularly.org Sun Dec 13 00:04:29 2009 From: jli at circularly.org (John Li) Date: Sat Dec 12 23:38:44 2009 Subject: [Haskell-beginners] Applicability of FP unchanging things to real world changing things In-Reply-To: References: Message-ID: <20091213050429.GA22937@circularly.org> On Sun, Dec 13, 2009 at 02:11:28AM +0000, Glurk wrote: > What's got me a little puzzled at the moment is non mutable data. [...] > How do people see this kind of situation ? > Is it just the way of looking at it... ? > Do I just accept that I toss out my old library object, and have a new one, > which happens to be the same as the old one, except for the "new" book which > is now borrowed ? > > Do I really need to get over thinking of objects in the first place, even > though it's what I see exist in the real world ? Mutability perhaps more directly matches how we look at the world, in which objects have states that change over time. Purely functional programming doesn't allow mutating data in place, so we have the "evolution" of an object through time. We get multiple snapshots. I like to think of it as having 1 dimensional objects instead of having 0 dimensional objects, in direct analogy to thinking of objects in the world as being 4 dimensional: 3 spatial and 1 time dimension. Rich Hickey (the Clojure guy) gave a keynote talk about this kind of thing: http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hickey Here's an interview about the same thing: http://www.artima.com/articles/hickey_on_time.html I've only watched the keynote, which I found really interesting. Maybe these will better help you get a grasp on a "functional" way of thinking? Hope that helps, John From uzytkownik2 at gmail.com Sun Dec 13 04:50:22 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Sun Dec 13 04:24:47 2009 Subject: [Haskell-beginners] Re: Re: How to create a monad instance In-Reply-To: References: <1260581893.2597.60.camel@picard> Message-ID: <1260697822.2847.83.camel@picard> > Thanks for your help. > > I have try your code ghci and I think there is a mistake in the > definition of (>>=) operator. > Hmm. I belive I tested code before (at least type-check) sending but it is possible. > test1 m f = IOException $ runIOException m >>= runIOException . f > :t test1 > test1 :: IOException a > -> (Exception a -> IOException a) > -> IOException a > > I think the defintion is: > test :: IOException a -> ( a -> IOException a) -> IOException a > Ups. You're right. Quick'n'dirty version with do: instance Monad IOException where return = IOException . return . return m >>= f = IOException $ do m' <- runIOException m case m' of Success _ v -> runIOException $ f v Exception e -> return $ Exception e > 1. why I am not using monoid? I try to bind C code and the function > return only one warning. But if I change i little the structure of > IOException, it may have sense to use a List. > newtype IOException a = IOException {runIOException :: ([Warning] -> > IO (Exception a))} > Well. The problem with returning one - what should be combination of warnings. It is of course problem-dependent. Regards From apfelmus at quantentunnel.de Sun Dec 13 05:24:06 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Sun Dec 13 04:58:37 2009 Subject: [Haskell-beginners] Re: Applicability of FP unchanging things to real world changing things In-Reply-To: References: Message-ID: Glurk wrote: > So, perhaps that's why I am having difficulty in seeing how some functional > programming ideas apply. > > What's got me a little puzzled at the moment is non mutable data. > On the one hand, I think it's great that I can mostly forget about errors > caused by my variables having unexpected values, and that I can reason about > my program much more easily... > > However, on the other hand, I wonder how it ties in with real world systems > that do in fact do deal with objects that change state. > > For example, if I was building a library system - I might have book objects, > and if a book gets borrowed, there remains the same book object, but it now > just has a different state - from "on shelf" say, to "borrowed". > > Now, in Haskell, I might have a function to lend a book :- > > lend book1 > > and this is going to return a new book, with the appropriate status change.. > ...but what of the old book ? I don't want 2 book objects floating around.. > ....to my way of thinking, it's really not a new book, it really is a change of > state. > > How do people see this kind of situation ? > Is it just the way of looking at it... ? > Do I just accept that I toss out my old library object, and have a new one, > which happens to be the same as the old one, except for the "new" book which > is now borrowed ? > > Do I really need to get over thinking of objects in the first place, even > though it's what I see exist in the real world ? The point is that the real world doesn't happen inside the computer, only a model of it. The functional paradigm is based on the idea that immutable variables make for great models, even when state changes are involved. In other words, the book in your example is not a real book, it's just a few bytes in the computer that model it for the purpose of tracking whether it's lent out or not. For instance, these few bytes can be a unique ID and a possible lend function is lend :: BookID -> Library -> Library where the data type Library is a giant table of book IDs that keeps track of which ones are lent out and which are not. Together with a notion of "the current library", this is enough to model your example. In the end, even the library example is somewhat special in that it's too much about reality. Most programming problems, like sorting, compressing, type inference, etc. etc. are more abstract in nature and there is no a priori reason why mutable variables would be a good way of describing and modeling them. In fact, physics has been very successful at modeling the real world without mutable variables for centuries. Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From uzytkownik2 at gmail.com Sun Dec 13 05:56:05 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Sun Dec 13 05:30:34 2009 Subject: [Haskell-beginners] Re: Problem implementing a stack In-Reply-To: <884667f90912081717u1a3026baxde3ed93c137fb1dd@mail.gmail.com> References: <884667f90912081717u1a3026baxde3ed93c137fb1dd@mail.gmail.com> Message-ID: <1260701765.2847.155.camel@picard> > data Stack a = Top (Stack a) | Layers [a] deriving (Show) Sorry I'm asking - but why Stack is either a 'Stack or List' - shouldn't it be either plain list or list-lile structure: data Stack a = EmptyStack | Stack a (Stack a) (unless you're training 'data' I'd say newtype Stack a = Stack [a]) Otherwise Top (Top (Layers [])) is a stack (yet it does not fit into rest of the functions) or even fix Top (i.e. Top (Top (Top (Top (...) Unless it have some reason of course. Regards From marco-oweber at gmx.de Sun Dec 13 08:47:10 2009 From: marco-oweber at gmx.de (Marc Weber) Date: Sun Dec 13 08:21:40 2009 Subject: [Haskell-beginners] What about scratch pad for each library Message-ID: <1260709552-sup-6092@nixos> You can read about the complete proposal here: http://haskell.org/haskellwiki/Hackage_wiki_page_per_project_discussion Benefits: If something doesn't work for you should contact the author/ maintainer or the mailinglist. But if you find a workaround you can put it online immediately. You should remove it again after having discussed the issue with maintainers. However they may be on holidays.. So if you've had minor trouble getting started with a package and if you think that some small examples would have helped you in the past you should register at the haskellwiki and write about your experiences so that I get a understanding of whether this idea improves your experience or makes it worse. Of course not all wiki pages will be maintained. So it's very likely that you find outdated information. But I personally think that one tip is worth 10 outdated wiki pages or such (?) Additionally are you interested in helping removing outdated content when you find such ? You'll find a link to the haskell-cafe mailinglist thread on the wiki page as well. Hopefully most wiki pages are empty or contain links to the project pages only because there are no issues and you understand everything immediately :) Thank you for your feedback Marc Weber From byorgey at seas.upenn.edu Sun Dec 13 13:21:10 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Dec 13 12:55:17 2009 Subject: [Haskell-beginners] Re: Applicability of FP unchanging things to real world changing things In-Reply-To: References: Message-ID: <20091213182110.GA18733@seas.upenn.edu> On Sun, Dec 13, 2009 at 11:24:06AM +0100, Heinrich Apfelmus wrote: > > In other words, the book in your example is not a real book, it's just a > few bytes in the computer that model it for the purpose of tracking > whether it's lent out or not. For instance, these few bytes can be a > unique ID and a possible lend function is > > lend :: BookID -> Library -> Library I should also point out that people coming from an OO or imperative background often look at a function like this and think it looks incredibly inefficient --- why throw away the entire *library* and build a new one *from scratch* when all we want to do is modify one little part of it? This seems a huge price to pay for immutability! But this line of thinking confuses abstract semantics with concrete implementation (something that imperative programming unfortunately tends to encourage, in my experience). The runtime is free to implement operations like "lend" any way it likes, as long as the abstract semantics are preserved. In this particular example, most of the "new" Library will probably be shared with the "old" Library, and just the part that is changed needs to be updated (in fact, note that this is only possible because Library is immutable! =) So in terms of actual execution we get the same efficiency that we would have by mutating the Library, but we get the cognitive benefit of being able to *think* of it as if we have produced an entirely new Library. -Brent From magnus at therning.org Mon Dec 14 09:50:59 2009 From: magnus at therning.org (Magnus Therning) Date: Mon Dec 14 09:25:09 2009 Subject: [Haskell-beginners] Re: Applicability of FP unchanging things to real world changing things In-Reply-To: <20091213182110.GA18733@seas.upenn.edu> References: <20091213182110.GA18733@seas.upenn.edu> Message-ID: On Sun, Dec 13, 2009 at 6:21 PM, Brent Yorgey wrote: > On Sun, Dec 13, 2009 at 11:24:06AM +0100, Heinrich Apfelmus wrote: >> >> In other words, the book in your example is not a real book, it's just a >> few bytes in the computer that model it for the purpose of tracking >> whether it's lent out or not. For instance, these few bytes can be a >> unique ID and a possible ?lend ?function is >> >> ? ? lend :: BookID -> Library -> Library > > I should also point out that people coming from an OO or imperative > background often look at a function like this and think it looks > incredibly inefficient --- why throw away the entire *library* and > build a new one *from scratch* when all we want to do is modify one > little part of it? ?This seems a huge price to pay for immutability! > > But this line of thinking confuses abstract semantics with concrete > implementation (something that imperative programming unfortunately > tends to encourage, in my experience). ?The runtime is free to > implement operations like "lend" any way it likes, as long as the > abstract semantics are preserved. ?In this particular example, most of > the "new" Library will probably be shared with the "old" Library, and > just the part that is changed needs to be updated (in fact, note that > this is only possible because Library is immutable! =) So in terms of > actual execution we get the same efficiency that we would have by > mutating the Library, but we get the cognitive benefit of being able > to *think* of it as if we have produced an entirely new Library. Doesn't this immutability make some things very easy to implement? For instance, it ought to be trivial to backup state to disk (for recovery or rollback), one just hands it to a thread asynchronously and then continues handling requests. Doing that sort of thing with mutable state requires a bit more work, I'd say. >From watching a presentation on Happstack, I believe this is how it achieves some of its nice features. /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe From dev at mobileink.com Mon Dec 14 11:54:53 2009 From: dev at mobileink.com (Gregg Reynolds) Date: Mon Dec 14 11:28:57 2009 Subject: [Haskell-beginners] Re: Applicability of FP unchanging things to real world changing things In-Reply-To: <20091213182110.GA18733@seas.upenn.edu> References: <20091213182110.GA18733@seas.upenn.edu> Message-ID: <75cc17ac0912140854o74efeef5vd840a8a2fc7c3579@mail.gmail.com> On Sun, Dec 13, 2009 at 12:21 PM, Brent Yorgey wrote: > On Sun, Dec 13, 2009 at 11:24:06AM +0100, Heinrich Apfelmus wrote: > > > > In other words, the book in your example is not a real book, it's just a > > few bytes in the computer that model it for the purpose of tracking > > whether it's lent out or not. For instance, these few bytes can be a > > unique ID and a possible lend function is > > > > lend :: BookID -> Library -> Library > > I should also point out that people coming from an OO or imperative > background often look at a function like this and think it looks > incredibly inefficient --- why throw away the entire *library* and > build a new one *from scratch* when all we want to do is modify one > little part of it? This seems a huge price to pay for immutability! > > But this line of thinking confuses abstract semantics with concrete > implementation (something that imperative programming unfortunately > tends to encourage, in my experience). The runtime is free to > implement operations like "lend" any way it likes, as long as the > abstract semantics are preserved. > +1 One of the turning points in learning the FP way is the realization that the conception of "function" as a "machine" or "transformation process" is misleading or even harmful. For most programmers coming from an imperative language background that's going to mean returning to a more mathematically pure notion of function, which means discarding the idea of mutating parts of an object in favor of establishing relations among different "objects" and letting the compiler worry about the gory details. Youschkevitch's fascinating history of the conceptmight be useful. -gregg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091214/f0253117/attachment.html From mcguire at crsr.net Mon Dec 14 15:33:54 2009 From: mcguire at crsr.net (Tommy M. McGuire) Date: Mon Dec 14 15:07:35 2009 Subject: [Haskell-beginners] Applicability of FP unchanging things to real world changing things In-Reply-To: References: Message-ID: <4B26A132.2050000@crsr.net> Glurk wrote: > However, on the other hand, I wonder how it ties in with real world systems > that do in fact do deal with objects that change state. Do they change state? Or do you see a new object with a different state than the previous object? Can you step into the same river twice? > For example, if I was building a library system - I might have book objects, > and if a book gets borrowed, there remains the same book object, but it now > just has a different state - from "on shelf" say, to "borrowed". > > Now, in Haskell, I might have a function to lend a book :- > > lend book1 > > and this is going to return a new book, with the appropriate status change.. > ..but what of the old book ? I don't want 2 book objects floating around.. > ...to my way of thinking, it's really not a new book, it really is a change of > state. > > How do people see this kind of situation ? > Is it just the way of looking at it... ? > Do I just accept that I toss out my old library object, and have a new one, > which happens to be the same as the old one, except for the "new" book which > is now borrowed ? > > Do I really need to get over thinking of objects in the first place, even > though it's what I see exist in the real world ? As Master Apfelmus has written, what you see (or what you think you see, if that is different) is almost completely irrelevant to what is going on in your program in the computer. If you lend a book, the book doesn't change. The library doesn't change. What changes is a model of the library, which now indicates that a book is lent to someone, and the real question is how best to build that model of the library. Most object oriented languages are inherently procedural; this is equivalent to writing all of your code in the IO monad. Haskell gives you more options than that, including writing pure functional code with the type lend :: Book -> Library -> Library which has all sorts of neat properties that help you build the model without falling into some of the potholes that go along with procedural programming. > Is there where we part company with non mutability and venture into the monads > where we do have side effects ? At some point, you will ask, "What about these two Libraries floating around?" and realize that what you really need is a monad and ideally one specific to your Library (rather than the general IO monad). Then you will be enlightened. -- Tommy "Gotta cut down on the cold meds" McGuire mcguire@crsr.net From vss at 73rus.com Mon Dec 14 17:35:13 2009 From: vss at 73rus.com (Vlad Skvortsov) Date: Mon Dec 14 17:08:36 2009 Subject: [Haskell-beginners] writing many1Till combinator for Parsec In-Reply-To: <200912121416.12881.daniel.is.fischer@web.de> References: <4B22EAA3.1080306@73rus.com> <200912121416.12881.daniel.is.fischer@web.de> Message-ID: <4B26BDA1.5030006@73rus.com> Daniel Fischer wrote: > You want a nonempty sequence of 'p's which aren't 'end's, followed by an 'end'. > So you could do for example > a) > many1Till p end = do > ps <- manyTill p end > guard (not $ null ps) > return ps > > , i.e. check whether the result of manyTill is a nonempty list after the fact, or check > whether manyTill p end will return an empty list before manyTill is run, like > b) > many1Till p end = do > notFollowedBy end > manyTill p end > > (i.e. many1Till p end = notFollowedBy end >> manyTill p end). > Thanks Daniel! I missed out on 'guard' and somewhy was under impression that 'notFollowedBy' can only deal with Chars. >> many1Till :: Parser a -> Parser end -> Parser [a] >> many1Till p end = do >> try (end >> (unexpected "sequence terminator")) >> <|> (do { p1 <- p; ps <- manyTill p end; return (p1:ps) }) >> >> Here there are two disadvantages: >> >> 1) I don't like hardcoding "sequence terminator" here; >> 2) the error output should say that only 'p' parser is expected, while >> it says (technically correct) that either 'p' or 'end' is expected: >> >> Prelude Main Text.ParserCombinators.Parsec> parseTest (many1Till letter >> (char '.')) "1" >> parse error at (line 1, column 1): >> unexpected "1" >> expecting "." or letter >> >> (What I want here is to say "expecting letter") >> > > For that, you need the slightly clumsier > c) > many1Till p end = do > notFollowedBy end > p1 <- p > ps <- manyTill p end > return (p1:ps) > Yep, that works but still provides incorrect diagnostics when fed with an empty string: Prelude Main Text.ParserCombinators.Parsec> parseTest (many1Till letter (char '.')) "" parse error at (line 1, column 1): unexpected end of input expecting "." or letter It's not a showstopper, but I'd still like to understand how to make it provide better error messages. Thanks! -- Vlad Skvortsov, vss@73rus.com, http://vss.73rus.com From daniel.is.fischer at web.de Mon Dec 14 18:57:15 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 14 18:32:48 2009 Subject: [Haskell-beginners] writing many1Till combinator for Parsec In-Reply-To: <4B26BDA1.5030006@73rus.com> References: <4B22EAA3.1080306@73rus.com> <200912121416.12881.daniel.is.fischer@web.de> <4B26BDA1.5030006@73rus.com> Message-ID: <200912150057.15815.daniel.is.fischer@web.de> Am Montag 14 Dezember 2009 23:35:13 schrieb Vlad Skvortsov: > > Thanks Daniel! I missed out on 'guard' and somewhy was under impression > that 'notFollowedBy' can only deal with Chars. That's correct, its type is notFollowedBy :: Show tok => GenParser tok st tok -> GenParser tok st () I didn't lookup the type. However, you can easily generalize it: nFB p = ((try p >> pzero) <|> return ()) "" Be aware, however, that the use of try may have adverse effects on performance. > >> many1Till :: Parser a -> Parser end -> Parser [a] > >> many1Till p end = do > >> try (end >> (unexpected "sequence terminator")) > >> <|> (do { p1 <- p; ps <- manyTill p end; return (p1:ps) }) > >> > >> Here there are two disadvantages: > >> > >> 1) I don't like hardcoding "sequence terminator" here; Understandable, but I haven't a better idea either. > >> 2) the error output should say that only 'p' parser is expected, while > >> it says (technically correct) that either 'p' or 'end' is expected: Remove expectations of end by labelling the test with an empty string: many1Till p end = ((try end >> unexpected "whatever") "") <|> do { p1 <- p; ps <- manyTill p end; return (p1:ps) } > >> > >> Prelude Main Text.ParserCombinators.Parsec> parseTest (many1Till letter > >> (char '.')) "1" > >> parse error at (line 1, column 1): > >> unexpected "1" > >> expecting "." or letter > >> > >> (What I want here is to say "expecting letter") > > > > For that, you need the slightly clumsier > > c) > > many1Till p end = do > > notFollowedBy end make that nFB end or better ((try end >> unexpected "whatever") "") > > p1 <- p > > ps <- manyTill p end > > return (p1:ps) > > Yep, that works but still provides incorrect diagnostics when fed with > an empty string: > > Prelude Main Text.ParserCombinators.Parsec> parseTest (many1Till letter > (char '.')) "" > parse error at (line 1, column 1): > unexpected end of input > expecting "." or letter > > It's not a showstopper, but I'd still like to understand how to make it > provide better error messages. > > Thanks! From streborg at hotmail.com Tue Dec 15 02:53:31 2009 From: streborg at hotmail.com (Glurk) Date: Tue Dec 15 02:28:00 2009 Subject: [Haskell-beginners] Re: Applicability of FP unchanging things to real world changing things References: <4B26A132.2050000@crsr.net> Message-ID: I agree with the points some people have raised - as I said in the original post, I certainly like some of the things that FP gives me. > Do they change state? Or do you see a new object with a different state than > the previous object? Can you step into the same river twice? I think a lot of people, looking at the real world, would answer, yes, it clearly IS the same book, now in a different state. And yes, I CAN step into the same river twice. This is how people see and think about the real world. So, while I understand and like the benefits that thinking of things as mathematical concepts gives me, it seems to me that it does take your program further away from the real word, and thus can make it less understandable because of this. There is a certain adavantage in having a close mapping from the real world to your program - if your program is meant to be dealing with real world things. > As Master Apfelmus has written, what you see (or what you think you see, if > that is different) is almost completely irrelevant to what is going on in your > program in the computer. If you lend a book, the book doesn't change. The > library doesn't change. What changes is a model of the library, which now > indicates that a book is lent to someone, and the real question is how best to > build that model of the library. I agree with you, that yes, it's our model that we're really working with, not the real world, and that the question is how best to build the model. However, in answering that question, as I said, I think that there are some advantages in there being a close relationship between the real world, and our model - in terms of understandability, which, personally, I believe is one of the most important things in any system. So, I'm not sure I agree that what we see in the real world is "almost completely irrelevant". If the mapping from real world to program is hard to understand, then it can make it harder to maintain. To make a farfetched example, if we model our book as an apple, and each time it is lent a bite gets taken out of it...... well..that's just completely ridiculous, right ? It's ridiculous because what we see in the real world IS important to how we model. It certainly doesn't mean that we have to model things exactly as we see them - obviously, we drop things we think are irrelevant etc ...but, I think in generaly, it CAN make visualization and understanding easier, if our model has a certain similarity to the thing it is modelling ! So, I'm just thinking that in the real world, we typically do think of changing objects, so a model which also has this property, can help in understanding. Of course, if we train ourselves to think differently...then a model containing immutable objects might have more benefits than drawbacks - and I think that's what most FP supporters are claiming. > At some point, you will ask, "What about these two Libraries floating around?" > and realize that what you really need is a monad and ideally one specific to > your Library (rather than the general IO monad). Then you will be enlightened. I guess that brings up another point - that eventually we are drawn into monads, which to me seems a bit unfortunate, because it seems that it leads us back to imperative programming with mutable state... As someone else suggested, perhaps FRP is an answer here.. ..I must admit I don't understand much about that, I'll look into it a bit more ! Glurk From stephen.tetley at gmail.com Tue Dec 15 06:24:37 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Tue Dec 15 05:58:40 2009 Subject: [Haskell-beginners] Re: Applicability of FP unchanging things to real world changing things In-Reply-To: References: <4B26A132.2050000@crsr.net> Message-ID: <5fdc56d70912150324t3303b9een12a32d11d0cc1c30@mail.gmail.com> 2009/12/15 Glurk : > So, I'm just thinking that in the real world, we typically do think of > changing objects, so a model which also has this property, can help in > understanding. Ah but Glurk, a model that has this property can often greatly _hinder_ understanding: Its well know in OO circles that state change is problematic for 'modelling' - vis the damage done to a circle or square object by the otherwise standard operation of a non-uniform scale, where the circle is obliged to become an ellipse, the square an oblong. [1] Typestate object oriented languages exist where one can migrate e.g a closed file object into an open file and back again, but are somewhat off the beaten path, seemingly doomed to be curios every once in a while at POPL, OOPSLA... Best wishes Stephen [1] http://en.wikipedia.org/wiki/Circle-ellipse_problem [2] http://www.cs.cmu.edu/~aldrich/papers/onward2009-state.pdf From scdames at gmail.com Wed Dec 16 23:05:10 2009 From: scdames at gmail.com (Sherard D.) Date: Wed Dec 16 22:39:00 2009 Subject: [Haskell-beginners] Large tables and GHC. Message-ID: <4B29ADF6.4090407@gmail.com> Hi, I have a couple of rather large byte tables that I'd like to use. I decided to use them as arrays because I figured such large tables wouldn't work well as lists. table1 = listArray (0, 25599) [...] table2 = listArray (0, 25599) [...] This is how my code looks, minus the large tables. However, the problem is that the large tables are loaded as a list first, and then converted to an array. This is indeed a very big problem, as trying to compile with GHC takes an unacceptably long time. Is there any way I can get around this? - Sherard From stephen.tetley at gmail.com Thu Dec 17 04:05:51 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Thu Dec 17 03:39:46 2009 Subject: [Haskell-beginners] Large tables and GHC. In-Reply-To: <4B29ADF6.4090407@gmail.com> References: <4B29ADF6.4090407@gmail.com> Message-ID: <5fdc56d70912170105p3dc2b6c2m65945e5146bd6b1a@mail.gmail.com> Hi Sherard You could use Data.Array.IO to read the data at runtime. Its not ideal as as well as moving the array read to runtime (the data file must be present somewhere) it puts you in the IO monad... I'm supposing you really want the equivalent of the C idiom where bitmaps or whatever are stored as char or byte arrays: const char bitmap1[] = { 0xFF, ... } GHC has array literals between #'s, here is a snippet from code generate by Alex, the lexer generator: data AlexAddr = AlexA# Addr# alex_deflt :: AlexAddr alex_deflt = AlexA# "\xff\xff\xff\xff\xff\xff\xff\xff"# Unfortunately I can't seem to find mention of array literals in the GHC user guide only the related 'Magic Hash' and I've never used array literals directly myself - only with code generated by Alex, so I can't really say how they work. Hopefully someone will add a better explanation soon. Best wishes Stephen 2009/12/17 Sherard D. : > Hi, > I have a couple of rather large byte tables that I'd like to use. I decided > to use them as arrays because I figured such large tables wouldn't work well > as lists. From shawn-haskell at willden.org Thu Dec 17 10:01:31 2009 From: shawn-haskell at willden.org (Shawn Willden) Date: Thu Dec 17 09:35:29 2009 Subject: [Haskell-beginners] Re: Applicability of FP unchanging things to real world changing things In-Reply-To: <75cc17ac0912140854o74efeef5vd840a8a2fc7c3579@mail.gmail.com> References: <20091213182110.GA18733@seas.upenn.edu> <75cc17ac0912140854o74efeef5vd840a8a2fc7c3579@mail.gmail.com> Message-ID: <200912170801.31633.shawn-haskell@willden.org> On Monday 14 December 2009 09:54:53 am Gregg Reynolds wrote: > Youschkevitch's fascinating history of the concept > might be > useful. Too bad it's paywalled :-( Shawn. From kane96 at gmx.de Thu Dec 17 10:03:59 2009 From: kane96 at gmx.de (kane96) Date: Thu Dec 17 09:37:56 2009 Subject: [Haskell-beginners] find element of tupels Message-ID: <20091217150359.139670@gmx.net> Hi, I have a list of tuples: [(Jan, 31),(Feb, 28),(Mar, 31),...] called monthAndMaxDay Date is: type Day = Int data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) type Year = Int type Date = (Day,Month,Year) Now I want to check if a date is legal: legalDate :: Date -> Bool legalDate (myDay, myMonth, myYear) = not (myDay <= 0) && myDay >= (find ((== myMonth) . fst) monthAndMaxDay) . snd the find works to search for the month in the first element of every tupel but at the end I have to check the second value of the tupel (the day) that it issn't higher than the maximal number of days in that month. Where do I have to set the "snd" correctly. Here I get the error: Couldn't match expected type `b -> c' against inferred type `Maybe (Month, Day)' -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From magnus at therning.org Thu Dec 17 10:21:13 2009 From: magnus at therning.org (Magnus Therning) Date: Thu Dec 17 09:55:09 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: <20091217150359.139670@gmx.net> References: <20091217150359.139670@gmx.net> Message-ID: On Thu, Dec 17, 2009 at 3:03 PM, kane96 wrote: > Hi, > I have a list of tuples: [(Jan, 31),(Feb, 28),(Mar, 31),...] called monthAndMaxDay > > Date is: > type Day = Int > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) > type Year = Int > type Date = (Day,Month,Year) > > Now I want to check if a date is legal: > legalDate :: Date -> Bool > legalDate (myDay, myMonth, myYear) = > ? ?not (myDay <= 0) && myDay >= ?(find ((== myMonth) . fst) monthAndMaxDay) . snd > > the find works to search for the month in the first element of every tupel but at the end I have to check the second value of the tupel (the day) that it issn't higher than the maximal number of days in that month. Where do I have to set the "snd" correctly. Here I get the error: Couldn't match expected type `b -> c' > ? ? ? ? ? against inferred type `Maybe (Month, Day)' First of all I'd take a look at the function Prelude.lookup, it'll be useful in this case. Using that function I'd do something like this: legalDate (myDay, myMonth, myYear) = maybe False id $ do days <- lookup myMonth monthAndMaxDay return (myDay <= days) /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe From patrick.leboutillier at gmail.com Thu Dec 17 10:41:51 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Thu Dec 17 10:15:47 2009 Subject: [Haskell-beginners] Large tables and GHC. In-Reply-To: <4B29ADF6.4090407@gmail.com> References: <4B29ADF6.4090407@gmail.com> Message-ID: Hi, On Wed, Dec 16, 2009 at 11:05 PM, Sherard D. wrote: > Hi, > > I have a couple of rather large byte tables that I'd like to use. I decided > to use them as arrays because I figured such large tables wouldn't work well > as lists. > > table1 = listArray (0, 25599) [...] > table2 = listArray (0, 25599) [...] > > This is how my code looks, minus the large tables. However, the problem is > that the large tables are loaded as a list first, and then converted to an > array. This is indeed a very big problem, as trying to compile with GHC > takes an unacceptably long time. If compilating time is only an issue while developping, maybe you can put your tables in a separate module? That way they only get compiled once (or when you change them) and they don't get recompiled when you change the rest of your program. Patrick > > Is there any way I can get around this? > > > - Sherard > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From andrew at swclan.homelinux.org Thu Dec 17 11:09:10 2009 From: andrew at swclan.homelinux.org (Andrew Sackville-West) Date: Thu Dec 17 10:45:49 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: <20091217150359.139670@gmx.net> References: <20091217150359.139670@gmx.net> Message-ID: <20091217160910.GA9466@basement.swclan.homelinux.org> On Thu, Dec 17, 2009 at 04:03:59PM +0100, kane96 wrote: > Hi, > I have a list of tuples: [(Jan, 31),(Feb, 28),(Mar, 31),...] called monthAndMaxDay > > Date is: > type Day = Int > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) > type Year = Int > type Date = (Day,Month,Year) > > Now I want to check if a date is legal: > legalDate :: Date -> Bool > legalDate (myDay, myMonth, myYear) = > not (myDay <= 0) && myDay >= (find ((== myMonth) . fst) monthAndMaxDay) . snd > > the find works to search for the month in the first element of every tupel but at the end I have to check the second value of the tupel (the day) that it issn't higher than the maximal number of days in that month. Where do I have to set the "snd" correctly. Here I get the error: Couldn't match expected type `b -> c' > against inferred type `Maybe (Month, Day)' I'm sure the error message goes on to say something like: in the first argument of (.) namely (find ((== myMonth) . fst) monthAndMaxDay) ... you have to interpret this error message a little bit. It is saying the composition operator (.) is expecting a function of type b -> c in it's first argument (or on the left-hand side), but you have provided something of type Maybe (Month, Day). This type is what that (find...) evaluates to. I'm missing the correct terminology here, but you cannot provide something that is fully evaluable on the left-hand side of (.). It needs to be something that evaluates to a function of one argument. That argument will be supplied by the function provided on the right hand side of (.). So, at a minimum, you need to swap your snd and your (find...), but that doesn't solve the problem of getting the tuple out of the Maybe monad that find returns. A -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: Digital signature Url : http://www.haskell.org/pipermail/beginners/attachments/20091217/f14541dd/attachment.bin From kane96 at gmx.de Thu Dec 17 11:18:41 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Thu Dec 17 10:53:28 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: References: <20091217150359.139670@gmx.net> Message-ID: <20091217161841.159680@gmx.net> thanks Magnus, great, works so far. I added to check that myDay have to be greater 0: legalDate :: Date -> Bool legalDate (myDay, myMonth, myYear) = maybe False id $ do days <- lookup myMonth monthAndMaxDay return (not (myDay <= 0) && (myDay <= days)) Another thing is, that I have to check for leapYears. I have a function that checks if a year is a leap year isLeapYear :: Int -> Bool isLeapYear year = mod year 4 == 0 monthAndMaxDay has 30 days for February which have to be fix. So i have to check in legalDate if the year is a leap year. If so I have to check myDay in February for 29 days, otherwise for 28 days. How can I implement this to isLegalDate? -------- Original-Nachricht -------- > Datum: Thu, 17 Dec 2009 15:21:13 +0000 > Von: Magnus Therning > An: kane96 > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] find element of tupels > On Thu, Dec 17, 2009 at 3:03 PM, kane96 wrote: > > Hi, > > I have a list of tuples: [(Jan, 31),(Feb, 28),(Mar, 31),...] called > monthAndMaxDay > > > > Date is: > > type Day = Int > > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | > Nov | Dec deriving (Eq,Enum,Show) > > type Year = Int > > type Date = (Day,Month,Year) > > > > Now I want to check if a date is legal: > > legalDate :: Date -> Bool > > legalDate (myDay, myMonth, myYear) = > > ? ?not (myDay <= 0) && myDay >= ?(find ((== myMonth) . fst) > monthAndMaxDay) . snd > > > > the find works to search for the month in the first element of every > tupel but at the end I have to check the second value of the tupel (the day) > that it issn't higher than the maximal number of days in that month. Where > do I have to set the "snd" correctly. Here I get the error: Couldn't match > expected type `b -> c' > > ? ? ? ? ? against inferred type `Maybe (Month, Day)' > > > First of all I'd take a look at the function Prelude.lookup, it'll be > useful in this case. > > Using that function I'd do something like this: > > legalDate (myDay, myMonth, myYear) = maybe False id $ do > days <- lookup myMonth monthAndMaxDay > return (myDay <= days) > > /M > > -- > Magnus Therning (OpenPGP: 0xAB4DFBA4) > magnus?therning?org Jabber: magnus?therning?org > http://therning.org/magnus identi.ca|twitter: magthe -- Preisknaller: GMX DSL Flatrate f?r nur 16,99 Euro/mtl.! http://portal.gmx.net/de/go/dsl02 From kane96 at gmx.de Thu Dec 17 12:21:21 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Thu Dec 17 11:55:23 2009 Subject: [Haskell-beginners] Enum for natural numbers Message-ID: <20091217172121.159700@gmx.net> Hi, I have data Nat = Z | S Nat deriving (Eq,Ord,Show) toEnum should return Z for negative numbers. I did something like this but the problem is I don't know how to set "less than". I tried > and lt: instance Enum Nat where toEnum (gt 0) = S Z toEnum (lt 1) = Z -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From allbery at ece.cmu.edu Thu Dec 17 13:56:30 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Thu Dec 17 13:31:48 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091217172121.159700@gmx.net> References: <20091217172121.159700@gmx.net> Message-ID: <672565B0-5711-4468-875B-DD718FF739F8@ece.cmu.edu> On Dec 17, 2009, at 12:21 , kane96@gmx.de wrote: > toEnum should return Z for negative numbers. I did something like > this but the problem is I don't know how to set "less than". I tried > > and lt: > > instance Enum Nat where > toEnum (gt 0) = S Z > toEnum (lt 1) = Z Take a look at guards. -- brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery@kf8nh.com system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon university KF8NH -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 195 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20091217/edb90242/PGP.bin From hjgtuyl at chello.nl Thu Dec 17 14:44:34 2009 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Thu Dec 17 14:18:31 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: <20091217161841.159680@gmx.net> References: <20091217150359.139670@gmx.net> <20091217161841.159680@gmx.net> Message-ID: On Thu, 17 Dec 2009 17:18:41 +0100, wrote: > thanks Magnus, great, works so far. I added to check that myDay have to > be greater 0: > > legalDate :: Date -> Bool > legalDate (myDay, myMonth, myYear) = maybe False id $ do > days <- lookup myMonth monthAndMaxDay > return (not (myDay <= 0) && (myDay <= days)) > > Another thing is, that I have to check for leapYears. I have a function > that checks if a year is a leap year > > isLeapYear :: Int -> Bool > isLeapYear year = mod year 4 == 0 That is not entirely correct; from package time: isLeapYear :: Integer -> Bool isLeapYear year = (mod year 4 == 0) && ((mod year 400 == 0) || not (mod year 100 == 0)) > > monthAndMaxDay has 30 days for February which have to be fix. So i have > to check in legalDate if the year is a leap year. If so I have to check > myDay in February for 29 days, otherwise for 28 days. How can I > implement this to isLegalDate? Use fromGregorianValid from package time. Regards, Henk-Jan van Tuyl -- http://Van.Tuyl.eu/ http://members.chello.nl/hjgtuyl/tourdemonad.html -- -- From mike.erickson at gmail.com Thu Dec 17 17:56:13 2009 From: mike.erickson at gmail.com (Mike Erickson) Date: Thu Dec 17 17:30:07 2009 Subject: [Haskell-beginners] Is this MR? Type restriction confusion Message-ID: I was trying to convert a function, f1 x l = map (\y -> y*x) l to so-called point-free style, but in reducing it I found two functions that seemed to work the same, until I discovered they have different types, and aren't equivalent: f1a x = map (*x) -- has type (Num a) => a -> [a] -> [a] f1b = \x -> map (*x) -- has type Integer -> [Integer] -> [Integer] Can someone help me understand why the latter has a more restrictive type? If I add the type signature "f1b :: (Num a) => a -> [a] -> [a]", they are once again equivalent, but am confused about what's going on. If this is MR, what exactly am I overloading here? I read through http://www.haskell.org/haskellwiki/Monomorphism_restriction and http://www.cs.auckland.ac.nz/references/haskell/haskell-intro-html/pitfalls.html. If anyone has a good reading recommendation here, I'd love to see it. Because if this is MR, I'm not understanding what MR is correctly. Also, They don't generate a type error, which makes me think it is not MR, but something else. Thanks, Mike From daniel.is.fischer at web.de Thu Dec 17 18:17:56 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Dec 17 17:53:20 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: References: <20091217150359.139670@gmx.net> <20091217161841.159680@gmx.net> Message-ID: <200912180017.56474.daniel.is.fischer@web.de> Am Donnerstag 17 Dezember 2009 20:44:34 schrieb Henk-Jan van Tuyl: > On Thu, 17 Dec 2009 17:18:41 +0100, wrote: > > thanks Magnus, great, works so far. I added to check that myDay have to > > be greater 0: > > > > legalDate :: Date -> Bool > > legalDate (myDay, myMonth, myYear) = maybe False id $ do > > days <- lookup myMonth monthAndMaxDay > > return (not (myDay <= 0) && (myDay <= days)) > > > > Another thing is, that I have to check for leapYears. I have a function > > that checks if a year is a leap year > > > > isLeapYear :: Int -> Bool > > isLeapYear year = mod year 4 == 0 > > That is not entirely correct; from package time: > isLeapYear :: Integer -> Bool > isLeapYear year = (mod year 4 == 0) && ((mod year 400 == 0) || not (mod > year 100 == 0)) > > > monthAndMaxDay has 30 days for February which have to be fix. So i have > > to check in legalDate if the year is a leap year. If so I have to check > > myDay in February for 29 days, otherwise for 28 days. How can I > > implement this to isLegalDate? > > Use fromGregorianValid from package time. Or legalDate (d,Feb,y) = 0 < d && d < (if isLeapYear y then 30 else 29) legalDate (d,m,y) | m `elem` [Apr,Jun,Sep,Nov] = 0 < d && d < 31 | otherwise = 0 < d && d < 32 > > Regards, > Henk-Jan van Tuyl > > > -- > http://Van.Tuyl.eu/ > http://members.chello.nl/hjgtuyl/tourdemonad.html > -- From allbery at ece.cmu.edu Thu Dec 17 18:35:32 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Thu Dec 17 18:09:43 2009 Subject: [Haskell-beginners] Is this MR? Type restriction confusion In-Reply-To: References: Message-ID: On Dec 17, 2009, at 17:56 , Mike Erickson wrote: > f1a x = map (*x) -- has type (Num a) => a -> [a] -> [a] > > f1b = \x -> map (*x) -- has type Integer -> [Integer] -> [Integer] > > Can someone help me understand why the latter has a more restrictive > type? That is indeed the monomorphism restriction. In very short: if a top level form (like your f1, f1a, f1b) takes no arguments and does not have an explicit type, its type is restricted according to defaulting; if no suitable default exists, it is rejected. In this case, defaulting gave it the type Integer because Integer is the first type in the defaults list that allows the declaration to typecheck. (The default "defaults list" is Integer, Double, and in recent GHC () (the null/unit type). -- brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery@kf8nh.com system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon university KF8NH -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 195 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20091217/78bdbd6b/PGP.bin From daniel.is.fischer at web.de Thu Dec 17 18:45:26 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Dec 17 18:20:51 2009 Subject: [Haskell-beginners] Is this MR? Type restriction confusion In-Reply-To: References: Message-ID: <200912180045.26436.daniel.is.fischer@web.de> Am Donnerstag 17 Dezember 2009 23:56:13 schrieb Mike Erickson: > I was trying to convert a function, > > f1 x l = map (\y -> y*x) l > > to so-called point-free style, but in reducing it I found two > functions that seemed to work the same, until I discovered they have > different types, and aren't equivalent: > > f1a x = map (*x) -- has type (Num a) => a -> [a] -> [a] > > f1b = \x -> map (*x) -- has type Integer -> [Integer] -> [Integer] > > Can someone help me understand why the latter has a more restrictive type? Indeed it's the monomorphism restriction. In f1a x = map (*x) , f1a is bound by a *function binding* (bound name and (>= 1) pattern on the left of '='), thus it has a polymorphic type. In f1b = \x -> map (*x) (btw, you can further point-free this as map . (*)), f1b is bound by a *simple pattern binding*, thus the monomorphism restriction says that without a type signature, it must have a monomorphic type. Type inference determines the type (Num a) => a -> [a] -> [a] for the function. This is a "type class polymorphic" type [the monomorphism restriction doesn't restrict unconstrained types, only if a type class is involved does it kick in], hence by the monomorphism restriction, it must have a monomorphic type. The type class is Num, thus by the default defaulting rules, for (Num a), a is instantiated as Integer, hence f1b :: Integer -> [Integer] -> [Integer] > > If I add the type signature "f1b :: (Num a) => a -> [a] -> [a]", they > are once again equivalent, but am confused about what's going on. If The monomorphism restriction only applies to functions without a type signature. > this is MR, what exactly am I overloading here? > > I read through http://www.haskell.org/haskellwiki/Monomorphism_restriction > and > http://www.cs.auckland.ac.nz/references/haskell/haskell-intro-html/pitfalls >.html. If anyone has a good reading recommendation here, I'd love to see it. Read the report:http://haskell.org/onlinereport/decls.html#sect4.5.5 (start at section 4.5.4) and http://haskell.org/onlinereport/decls.html#sect4.4.3 for pattern and function bindings. It's a little technical, but with the other resources it should be understandable. In short, if you declare a function point-free and the inferred type involves type classes, it cannot be polymorphic unless you give a type signature. Without a type signature, the implementation tries to determine a monomorphic type from the inferred polymorphic type by the defaulting rules (http://haskell.org/onlinereport/decls.html#sect4.3.4). If that succeeds, this type is given to the function, otherwise it's a type error and the module doesn't compile. > Because if this is MR, I'm not understanding what MR is correctly. Also, > They don't generate a type error, which makes me think it is not MR, but > something else. > > Thanks, > > Mike From mike.erickson at gmail.com Thu Dec 17 19:46:34 2009 From: mike.erickson at gmail.com (Mike Erickson) Date: Thu Dec 17 19:20:27 2009 Subject: [Haskell-beginners] Is this MR? Type restriction confusion In-Reply-To: <200912180045.26436.daniel.is.fischer@web.de> References: <200912180045.26436.daniel.is.fischer@web.de> Message-ID: On Thu, Dec 17, 2009 at 3:45 PM, Daniel Fischer wrote: > Am Donnerstag 17 Dezember 2009 23:56:13 schrieb Mike Erickson: >> I was trying to convert a function, >> >> f1 x l = map (\y -> y*x) l >> >> to so-called point-free style, but in reducing it I found two >> functions that seemed to work the same, until I discovered they have >> different types, and aren't equivalent: >> >> f1a x = map (*x) -- has type (Num a) => a -> [a] -> [a] >> >> f1b = \x -> map (*x) -- has type Integer -> [Integer] -> [Integer] >> >> Can someone help me understand why the latter has a more restrictive type? > > Indeed it's the monomorphism restriction. > [...] This was very helpful. I think I understand, although it's still digesting. > In short, if you declare a function point-free and the inferred type involves type > classes, it cannot be polymorphic unless you give a type signature. Without a type > signature, the implementation tries to determine a monomorphic type from the inferred > polymorphic type by the defaulting rules > (http://haskell.org/onlinereport/decls.html#sect4.3.4). If that succeeds, this type is > given to the function, otherwise it's a type error and the module doesn't compile. Shortly after posting (of course) I discovered the online report and 4.5.4 and 4.5.5 were helpful as well. Thanks to all that responded, Mike From byorgey at seas.upenn.edu Thu Dec 17 22:41:41 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Thu Dec 17 22:15:35 2009 Subject: [Haskell-beginners] Is this MR? Type restriction confusion In-Reply-To: References: <200912180045.26436.daniel.is.fischer@web.de> Message-ID: <20091218034141.GA4631@seas.upenn.edu> On Thu, Dec 17, 2009 at 04:46:34PM -0800, Mike Erickson wrote: > On Thu, Dec 17, 2009 at 3:45 PM, Daniel Fischer > wrote: > > Am Donnerstag 17 Dezember 2009 23:56:13 schrieb Mike Erickson: > >> I was trying to convert a function, > >> > >> f1 x l = map (\y -> y*x) l > >> > >> to so-called point-free style, but in reducing it I found two > >> functions that seemed to work the same, until I discovered they have > >> different types, and aren't equivalent: > >> > >> f1a x = map (*x) -- has type (Num a) => a -> [a] -> [a] > >> > >> f1b = \x -> map (*x) -- has type Integer -> [Integer] -> [Integer] > >> > >> Can someone help me understand why the latter has a more restrictive type? > > > > Indeed it's the monomorphism restriction. > > [...] > > This was very helpful. I think I understand, although it's still digesting. > > > In short, if you declare a function point-free and the inferred type involves type > > classes, it cannot be polymorphic unless you give a type signature. Without a type > > signature, the implementation tries to determine a monomorphic type from the inferred > > polymorphic type by the defaulting rules > > (http://haskell.org/onlinereport/decls.html#sect4.3.4). If that succeeds, this type is > > given to the function, otherwise it's a type error and the module doesn't compile. > > Shortly after posting (of course) I discovered the online report and > 4.5.4 and 4.5.5 were helpful as well. I should point out that the monomorphism restriction will probably be removed from a future version of the language standard. I recommend turning it off, especially in ghci (by putting ':set -XNoMonomorphismRestriction' in your .ghci file)---it is rarely useful and just confuses people. -Brent From hjgtuyl at chello.nl Fri Dec 18 06:01:53 2009 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Fri Dec 18 05:35:47 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: <200912180017.56474.daniel.is.fischer@web.de> References: <20091217150359.139670@gmx.net> <20091217161841.159680@gmx.net> <200912180017.56474.daniel.is.fischer@web.de> Message-ID: On Fri, 18 Dec 2009 00:17:56 +0100, Daniel Fischer wrote: > > legalDate (d,Feb,y) = 0 < d && d < (if isLeapYear y then 30 else 29) This should be: legalDate (d, Feb, y) = 0 < d && d < (if isLeapYear y then 29 else 28) > legalDate (d,m,y) > | m `elem` [Apr,Jun,Sep,Nov] = 0 < d && d < 31 > | otherwise = 0 < d && d < 32 > Regards, Henk-Jan van Tuyl -- http://Van.Tuyl.eu/ http://members.chello.nl/hjgtuyl/tourdemonad.html -- From daniel.is.fischer at web.de Fri Dec 18 07:03:06 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Dec 18 06:39:54 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: References: <20091217150359.139670@gmx.net> <200912180017.56474.daniel.is.fischer@web.de> Message-ID: <200912181303.07183.daniel.is.fischer@web.de> Am Freitag 18 Dezember 2009 12:01:53 schrieb Henk-Jan van Tuyl: > On Fri, 18 Dec 2009 00:17:56 +0100, Daniel Fischer > > wrote: > > legalDate (d,Feb,y) = 0 < d && d < (if isLeapYear y then 30 else 29) > > This should be: > legalDate (d, Feb, y) = 0 < d && d < (if isLeapYear y then 29 else 28) No, I test for strict inequality, hence 30 resp. 29. > > > legalDate (d,m,y) > > > > | m `elem` [Apr,Jun,Sep,Nov] = 0 < d && d < 31 > > | otherwise = 0 < d && d < 32 > > Regards, > Henk-Jan van Tuyl From kane96 at gmx.de Fri Dec 18 09:34:39 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Fri Dec 18 09:08:34 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <672565B0-5711-4468-875B-DD718FF739F8@ece.cmu.edu> References: <20091217172121.159700@gmx.net> <672565B0-5711-4468-875B-DD718FF739F8@ece.cmu.edu> Message-ID: <20091218143439.113140@gmx.net> ok, but I shall use Enum in the exercise. -------- Original-Nachricht -------- > Datum: Thu, 17 Dec 2009 13:56:30 -0500 > Von: "Brandon S. Allbery KF8NH" > An: kane96@gmx.de > CC: "Brandon S. Allbery KF8NH" , beginners@haskell.org > Betreff: Re: [Haskell-beginners] Enum for natural numbers > On Dec 17, 2009, at 12:21 , kane96@gmx.de wrote: > > toEnum should return Z for negative numbers. I did something like > > this but the problem is I don't know how to set "less than". I tried > > > and lt: > > > > instance Enum Nat where > > toEnum (gt 0) = S Z > > toEnum (lt 1) = Z > > > Take a look at guards. > > -- > brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery@kf8nh.com > system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu > electrical and computer engineering, carnegie mellon university KF8NH > > -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From kane96 at gmx.de Fri Dec 18 09:35:52 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Fri Dec 18 09:09:47 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: References: <20091217150359.139670@gmx.net> <20091217161841.159680@gmx.net> Message-ID: <20091218143552.113150@gmx.net> -------- Original-Nachricht -------- > Datum: Thu, 17 Dec 2009 20:44:34 +0100 > Von: "Henk-Jan van Tuyl" > An: kane96@gmx.de, beginners@haskell.org > Betreff: Re: [Haskell-beginners] find element of tupels > On Thu, 17 Dec 2009 17:18:41 +0100, wrote: > > > thanks Magnus, great, works so far. I added to check that myDay have to > > be greater 0: > > > > legalDate :: Date -> Bool > > legalDate (myDay, myMonth, myYear) = maybe False id $ do > > days <- lookup myMonth monthAndMaxDay > > return (not (myDay <= 0) && (myDay <= days)) > > > > Another thing is, that I have to check for leapYears. I have a function > > that checks if a year is a leap year > > > > isLeapYear :: Int -> Bool > > isLeapYear year = mod year 4 == 0 > > That is not entirely correct; from package time: > isLeapYear :: Integer -> Bool > isLeapYear year = (mod year 4 == 0) && ((mod year 400 == 0) || not (mod > > year 100 == 0)) ok > > > > > > monthAndMaxDay has 30 days for February which have to be fix. So i have > > to check in legalDate if the year is a leap year. If so I have to check > > myDay in February for 29 days, otherwise for 28 days. How can I > > implement this to isLegalDate? > > Use fromGregorianValid from package time. but the problem is I shall implement it on my own in this exercise > > Regards, > Henk-Jan van Tuyl > > > -- > http://Van.Tuyl.eu/ > http://members.chello.nl/hjgtuyl/tourdemonad.html > -- > > > > -- -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser From kane96 at gmx.de Fri Dec 18 09:57:56 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Fri Dec 18 09:31:49 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: <200912180017.56474.daniel.is.fischer@web.de> References: <20091217150359.139670@gmx.net> <20091217161841.159680@gmx.net> <200912180017.56474.daniel.is.fischer@web.de> Message-ID: <20091218145756.236650@gmx.net> thx Daniel. Now I implemented it like that to use my monthAndMaxDay list and just use the isLeapYear check for February: legalDate :: Date -> Bool legalDate (myDay, Feb, myYear) = 0 < myDay && myDay <= (if isLeapYear myYear then 29 else 28) legalDate (myDay, myMonth, myYear) = maybe False id $ do days <- lookup myMonth monthAndMaxDay return (not (myDay <= 0) && (myDay <= days)) -------- Original-Nachricht -------- > Datum: Fri, 18 Dec 2009 00:17:56 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > Betreff: Re: [Haskell-beginners] find element of tupels > Am Donnerstag 17 Dezember 2009 20:44:34 schrieb Henk-Jan van Tuyl: > > On Thu, 17 Dec 2009 17:18:41 +0100, wrote: > > > thanks Magnus, great, works so far. I added to check that myDay have > to > > > be greater 0: > > > > > > legalDate :: Date -> Bool > > > legalDate (myDay, myMonth, myYear) = maybe False id $ do > > > days <- lookup myMonth monthAndMaxDay > > > return (not (myDay <= 0) && (myDay <= days)) > > > > > > Another thing is, that I have to check for leapYears. I have a > function > > > that checks if a year is a leap year > > > > > > isLeapYear :: Int -> Bool > > > isLeapYear year = mod year 4 == 0 > > > > That is not entirely correct; from package time: > > isLeapYear :: Integer -> Bool > > isLeapYear year = (mod year 4 == 0) && ((mod year 400 == 0) || not > (mod > > year 100 == 0)) > > > > > monthAndMaxDay has 30 days for February which have to be fix. So i > have > > > to check in legalDate if the year is a leap year. If so I have to > check > > > myDay in February for 29 days, otherwise for 28 days. How can I > > > implement this to isLegalDate? > > > > Use fromGregorianValid from package time. > > Or > > legalDate (d,Feb,y) = 0 < d && d < (if isLeapYear y then 30 else 29) > legalDate (d,m,y) > | m `elem` [Apr,Jun,Sep,Nov] = 0 < d && d < 31 > | otherwise = 0 < d && d < 32 > > > > > Regards, > > Henk-Jan van Tuyl > > > > > > -- > > http://Van.Tuyl.eu/ > > http://members.chello.nl/hjgtuyl/tourdemonad.html > > -- > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From kane96 at gmx.de Fri Dec 18 11:01:01 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Fri Dec 18 10:34:56 2009 Subject: [Haskell-beginners] print all days of calendar Message-ID: <20091218160101.113160@gmx.net> I have to create a calendar like this: type Calendar = [Date] Date is: type Day = Int data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) type Year = Int type Date = (Day,Month,Year) I shall create a function: calendar :: Year -> Calendar that return a calendar for the given year like: [(1, Jan, 2009), (2, Jan, 2009), ..., (31, Dec, 2009)] I also have a function from a previous exercise which checks if a given date is valid. Is there a function for a loop that iterates from 1 to n and checks if the date is valid. If it's valid it should return the date otherwise it should jump to the next month or end at the end of the year? Or is it better to do it on another way with this data I have? -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser From deniz.a.m.dogan at gmail.com Fri Dec 18 12:06:32 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Fri Dec 18 11:40:46 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091217172121.159700@gmx.net> References: <20091217172121.159700@gmx.net> Message-ID: <7b501d5c0912180906l655b34c3safe2bcfec0d87c52@mail.gmail.com> 2009/12/17 : > Hi, > I have data Nat = Z | S Nat deriving (Eq,Ord,Show) > > toEnum should return Z for negative numbers. I did something like this but the problem is I don't know how to set "less than". I tried > and lt: > > instance Enum Nat where > ? ?toEnum (gt 0) = S Z > ? ?toEnum (lt 1) = Z > -- > GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! > Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > Fill in the gaps: instance Enum Nat where toEnum x | x <= 0 = ... | otherwise = ... -- Deniz Dogan From kane96 at gmx.de Fri Dec 18 12:42:45 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Fri Dec 18 12:16:37 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <7b501d5c0912180906l655b34c3safe2bcfec0d87c52@mail.gmail.com> References: <20091217172121.159700@gmx.net> <7b501d5c0912180906l655b34c3safe2bcfec0d87c52@mail.gmail.com> Message-ID: <20091218174245.113160@gmx.net> ahhh, ok, thanks so far. Here is how the output should looks like: *Main> toEnum (-1) :: Nat Z *Main> toEnum 0 :: Nat Z *Main> toEnum 1 :: Nat S Z *Main> fromEnum (S (S Z)) 2 the first three things work, but I don't know about the last one. Does anybody how it should work and what's the sense of it? -------- Original-Nachricht -------- > Datum: Fri, 18 Dec 2009 18:06:32 +0100 > Von: Deniz Dogan > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] Enum for natural numbers > 2009/12/17 : > > Hi, > > I have data Nat = Z | S Nat deriving (Eq,Ord,Show) > > > > toEnum should return Z for negative numbers. I did something like this > but the problem is I don't know how to set "less than". I tried > and lt: > > > > instance Enum Nat where > > ? ?toEnum (gt 0) = S Z > > ? ?toEnum (lt 1) = Z > > -- > > GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! > > Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > > > Fill in the gaps: > > instance Enum Nat where > toEnum x | x <= 0 = ... > | otherwise = ... > > -- > Deniz Dogan -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser From deniz.a.m.dogan at gmail.com Fri Dec 18 12:59:40 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Fri Dec 18 12:33:52 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091218174245.113160@gmx.net> References: <20091217172121.159700@gmx.net> <7b501d5c0912180906l655b34c3safe2bcfec0d87c52@mail.gmail.com> <20091218174245.113160@gmx.net> Message-ID: <7b501d5c0912180959j4248552xcf30b4deed8d01f5@mail.gmail.com> 2009/12/18 : > ahhh, ok, thanks so far. Here is how the output should looks like: > *Main> toEnum (-1) :: Nat > Z > *Main> toEnum 0 :: Nat > Z > *Main> toEnum 1 :: Nat > S Z > *Main> fromEnum (S (S Z)) > 2 > > the first three things work, but I don't know about the last one. Does anybody how it should work and what's the sense of it? > Looks right to me. "Z" means 0 (Zero), "S x" means "the Successor of x". So (S (S (S Z))) means "the successor of the successor of the successor of zero", which is 3. > > -------- Original-Nachricht -------- >> Datum: Fri, 18 Dec 2009 18:06:32 +0100 >> Von: Deniz Dogan >> An: kane96@gmx.de >> CC: beginners@haskell.org >> Betreff: Re: [Haskell-beginners] Enum for natural numbers > >> 2009/12/17 ?: >> > Hi, >> > I have data Nat = Z | S Nat deriving (Eq,Ord,Show) >> > >> > toEnum should return Z for negative numbers. I did something like this >> but the problem is I don't know how to set "less than". I tried > and lt: >> > >> > instance Enum Nat where >> > ? ?toEnum (gt 0) = S Z >> > ? ?toEnum (lt 1) = Z >> > -- >> > GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! >> > Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 >> > _______________________________________________ >> > Beginners mailing list >> > Beginners@haskell.org >> > http://www.haskell.org/mailman/listinfo/beginners >> > >> >> Fill in the gaps: >> >> instance Enum Nat where >> ? ? toEnum x | x <= 0 = ... >> ? ? ? ? ? ? ?| otherwise = ... >> >> -- >> Deniz Dogan > > -- > Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - > sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Deniz Dogan From kane96 at gmx.de Fri Dec 18 13:02:16 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Fri Dec 18 12:36:09 2009 Subject: [Haskell-beginners] inserting tupels inside list as tupels in list Message-ID: <20091218180216.113150@gmx.net> maybe the subject is a little bit confusing :p I have a organiser list like that and have to add events (like panic, xmas, ...) which is also a type of tupel for a specific date: aliceOrg = [ ( (21,Dec,2009), [panic,aliceBDay] ) ( (25,Dec,2009), [xmas] ) ( (10,Jan,2010), [bobBDay] ) What function(s) can I use to add these nested lists and tupels here? -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser From magnus at therning.org Fri Dec 18 14:09:11 2009 From: magnus at therning.org (Magnus Therning) Date: Fri Dec 18 13:43:12 2009 Subject: [Haskell-beginners] find element of tupels In-Reply-To: <20091218145756.236650@gmx.net> References: <20091217150359.139670@gmx.net> <20091217161841.159680@gmx.net> <200912180017.56474.daniel.is.fischer@web.de> <20091218145756.236650@gmx.net> Message-ID: <4B2BD357.5080002@therning.org> On 18/12/09 14:57, kane96@gmx.de wrote: > thx Daniel. Now I implemented it like that to use my monthAndMaxDay list and just use the isLeapYear check for February: > > legalDate :: Date -> Bool > legalDate (myDay, Feb, myYear) = 0 < myDay && myDay <= (if isLeapYear > myYear then 29 else 28) > legalDate (myDay, myMonth, myYear) = maybe False id $ do > days <- lookup myMonth monthAndMaxDay > return (not (myDay <= 0) && (myDay <= days)) I know it's a minor detail, but wouldn't it be clearer to change that last line to read something like this: return $ 0 < myDay && myDay <= days ? /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature Url : http://www.haskell.org/pipermail/beginners/attachments/20091218/1536c2ad/signature.bin From byorgey at seas.upenn.edu Fri Dec 18 17:58:12 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Fri Dec 18 17:32:04 2009 Subject: [Haskell-beginners] inserting tupels inside list as tupels in list In-Reply-To: <20091218180216.113150@gmx.net> References: <20091218180216.113150@gmx.net> Message-ID: <20091218225812.GA19856@seas.upenn.edu> On Fri, Dec 18, 2009 at 07:02:16PM +0100, kane96@gmx.de wrote: > maybe the subject is a little bit confusing :p > > I have a organiser list like that and have to add events (like panic, xmas, ...) which is also a type of tupel for a specific date: > > aliceOrg = [ ( (21,Dec,2009), [panic,aliceBDay] ) > ( (25,Dec,2009), [xmas] ) > ( (10,Jan,2010), [bobBDay] ) > > What function(s) can I use to add these nested lists and tupels here? You can use all the functions for manipulating lists and tuples in the standard libraries... I'm not entirely sure what you are asking. Let me suggest, however, that you probably don't want to be using tuples so much; make your own data types. Something like this: type Day = Int data Month = Jan | Feb | ... type Year = Int data Date = Date Day Month Year data CalEntry = CalEntry Date [Event] data Event = ... type Organizer = [CalEntry] This is much less confusing since instead of just tuples everywhere you have specific types that say exactly what the data represents. -Brent From drg at david.gordon.name Fri Dec 18 18:55:34 2009 From: drg at david.gordon.name (David Gordon) Date: Fri Dec 18 18:29:45 2009 Subject: [Haskell-beginners] Fwd: Type constraints question In-Reply-To: References: Message-ID: Apologies for the spam, I had some difficulty getting my email address set up right on the list and wanted to make sure this finally got through (or perhaps there are like 5 copies on the list now... sorry.) thanks ---------- Forwarded message ---------- Ok, now I will try asking the right question (previous try wasn't actually an example of the problem I'm having) Here's the code: data Test = Test data Test2 = Test2 class MyClass a where getChild :: MyClass b => a -> b instance MyClass Test where getChild a = Test2 instance MyClass Test2 where getChild a = Test On HUGS I get: Error occurred ERROR line 9 - Inferred type is not general enough *** Expression : getChild *** Expected type : (MyClass Test, MyClass a) => Test -> a *** Inferred type : (MyClass Test, MyClass Test2) => Test -> Test2 So, what's the problem with always returning a particular instance of MyClass? I just want to constrain it to be an instance of MyClass, nothing more. thanks, David 2009/12/18 David Gordon > > Hi Folks, > Total newbie here. I don't know if I am having a syntactic problem or a conceptual problem. > This code: > data Test = Test > data Test2 = Test2 > class MyClass a where > getChild :: (MyClass b) => a -> b > instance MyClass Test where > getChild = Test2 > instance MyClass Test2 where > getChild = Test > results in: > [1 of 1] Compiling Main ( test.hs, interpreted ) > test.hs:10:15: > Couldn't match expected type `Test -> b' > against inferred type `Test2' > In the expression: Test2 > In the definition of `getChild': getChild = Test2 > In the instance declaration for `MyClass Test' > test.hs:13:15: > Couldn't match expected type `Test2 -> b' > against inferred type `Test' > In the expression: Test > In the definition of `getChild': getChild = Test > In the instance declaration for `MyClass Test2' > Failed, modules loaded: none. > Is this a reasonable thing to try and do in Haskell? If not, I have a lot more questions... ;) > many thanks, > David > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091218/40110c22/attachment-0001.html From jon at ffconsultancy.com Fri Dec 18 20:52:54 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Fri Dec 18 19:12:44 2009 Subject: [Haskell-beginners] Parallel mutation In-Reply-To: <20091210120055.7341df55.mle+hs@mega-nerd.com> References: <200912082056.46077.jon@ffconsultancy.com> <20091210115501.fe2e80df.mle+hs@mega-nerd.com> <20091210120055.7341df55.mle+hs@mega-nerd.com> Message-ID: <200912190152.54440.jon@ffconsultancy.com> On Thursday 10 December 2009 01:00:55 Erik de Castro Lopo wrote: > Erik de Castro Lopo wrote: > > So why not look at Data Parallel Haskell: > > > > http://www.haskell.org/haskellwiki/GHC/Data_Parallel_Haskell > > Quicksort example: > > http://darcs.haskell.org/ghc-6.10/packages/dph/examples/qsort/ > > I haven't tested this. It isn't even a real quicksort => it will be orders of magnitude slower than a real quicksort. -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From daniel.is.fischer at web.de Fri Dec 18 20:15:10 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Dec 18 19:50:31 2009 Subject: [Haskell-beginners] Fwd: Type constraints question In-Reply-To: References: Message-ID: <200912190215.10442.daniel.is.fischer@web.de> Am Samstag 19 Dezember 2009 00:55:34 schrieb David Gordon: > Apologies for the spam, I had some difficulty getting my email address set > up right on the list and wanted to make sure this finally got through (or > perhaps there are like 5 copies on the list now... sorry.) > > thanks > > ---------- Forwarded message ---------- > > Ok, now I will try asking the right question (previous try wasn't actually > an example of the problem I'm having) > > Here's the code: > > > data Test = Test > > data Test2 = Test2 > > class MyClass a where > getChild :: MyClass b => a -> b > > instance MyClass Test where > getChild a = Test2 > > instance MyClass Test2 where > getChild a = Test > > On HUGS I get: > > Error occurred > ERROR line 9 - Inferred type is not general enough > *** Expression : getChild > *** Expected type : (MyClass Test, MyClass a) => Test -> a > *** Inferred type : (MyClass Test, MyClass Test2) => Test -> Test2 > > So, what's the problem with always returning a particular instance of > MyClass? I just want to constrain it to be an instance of MyClass, nothing > more. The signature of getChild promises that *whichever type the caller wants*, as long as it's a member of MyClass, it can be provided. The implementation returns one specific type. It's different from interfaces in Java, where the callee decides which type is returned, here the caller can demand the type that the callee has to return. The signature of getChild is actually getChild :: forall b. MyClass b => a -> b while the implementation has the signature (not legal Haskell) getChild :: exists b. MyClass b => a -> b. What you want is, I believe, that each instance a of MyClass specifies a type b belonging to MyClass which getChild returns. You can achieve part of that for example with a multiparameter type class {-# LANGUAGE MultiParamTypeClasses #-} class MyClass2 a b where getChild :: a -> b However, this allows that a has children of more than one type ( instance MyClass2 Test Test2 where getChild _ = Test2 instance MyClass2 Test Test where getChild _ = Test ) and this doesn't enforce that b itself has children. To enforce that every type has only one type of children, you can use functional dependencies (or type families, see below): {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} class MyClass3 a b | a -> b where getChild :: a -> b The functional dependency "a -> b" (separated from the class head by "|") says that a uniquely determines b. But that still doesn't enforce that b has children. For that, you need {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts #-} class MyClass4 a b | a -> b where getChild :: MyClass4 b c => a -> b Now each type can have only one type of children and they must have children too. Another way to achieve the above is via type families: {-# LANGUAGE TypeFamilies, FlexibleContexts #-} class MyClass5 a where type Child a :: * getChild :: (MyClass5 (Child a)) => a -> Child a instance MyClass5 Test where type Child Test = Test2 getChild _ = Test2 instance MyClass5 Test2 where type Child Test2 = Test getChild _ = Test > > thanks, > > David > > > 2009/12/18 David Gordon > > > Hi Folks, > > Total newbie here. I don't know if I am having a syntactic problem or a > > conceptual problem. > > > This code: > > data Test = Test > > data Test2 = Test2 > > class MyClass a where > > getChild :: (MyClass b) => a -> b > > instance MyClass Test where > > getChild = Test2 > > instance MyClass Test2 where > > getChild = Test > > results in: > > [1 of 1] Compiling Main ( test.hs, interpreted ) > > test.hs:10:15: > > Couldn't match expected type `Test -> b' > > against inferred type `Test2' > > In the expression: Test2 > > In the definition of `getChild': getChild = Test2 > > In the instance declaration for `MyClass Test' > > test.hs:13:15: > > Couldn't match expected type `Test2 -> b' > > against inferred type `Test' > > In the expression: Test > > In the definition of `getChild': getChild = Test > > In the instance declaration for `MyClass Test2' > > Failed, modules loaded: none. > > Is this a reasonable thing to try and do in Haskell? If not, I have a lot > > more questions... ;) > > > many thanks, > > David From chaddai.fouche at gmail.com Sat Dec 19 05:16:45 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Sat Dec 19 04:50:36 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <20091218160101.113160@gmx.net> References: <20091218160101.113160@gmx.net> Message-ID: On Fri, Dec 18, 2009 at 5:01 PM, wrote: > I also have a function from a previous exercise which checks if a given date is valid. Is there a function for a loop that iterates from 1 to n and checks if the date is valid. If it's valid it should return the date otherwise it should jump to the next month or end at the end of the year? Or is it better to do it on another way with this data I have? Since you derived Enum for Month, you can do [Jan..Dec] and get the list of the months in order. There are then two options, either you generate all cartesian product of [Jan..Dec] and [1..31] and check which are valid, or you write a function that for a given month and year tells you how many days it counts and then generate for month "m" all the pair in combination with [1..daysCount m]. Whatever your decision, list comprehensions are probably the tool of choice to do it though it is by no mean harder to do without. -- Jeda? From amy at nualeargais.ie Sat Dec 19 08:20:43 2009 From: amy at nualeargais.ie (=?ISO-8859-1?Q?Amy_de_Buitl=E9ir?=) Date: Sat Dec 19 07:54:33 2009 Subject: [Haskell-beginners] `coarbitrary' is not a (visible) method of class `Arbitrary' Message-ID: <77b28c350912190520q3571dd64jdfc102ea8e0dc6a5@mail.gmail.com> I'm trying to follow the instructions in http://haskell.org/haskellwiki/How_to_write_a_Haskell_program. I'm at the step where we've just written a QuickCheck test: amy@localhost ~/forbairt/haq $ cat Tests.hs import Char import List import Test.QuickCheck import Text.Printf main = mapM_ (\(s,a) -> printf "%-25s: " s >> a) tests instance Arbitrary Char where arbitrary = choose ('\0', '\128') coarbitrary c = variant (ord c `rem` 4) -- reversing twice a finite list, is the same as identity prop_reversereverse s = (reverse . reverse) s == id s where _ = s :: [Int] -- and add this to the tests list tests = [("reverse.reverse/id", test prop_reversereverse)] But when I try to run it, I get the following errors: amy@localhost ~/forbairt/haq $ runhaskell Tests.hs Tests.hs:10:4: `coarbitrary' is not a (visible) method of class `Arbitrary' Tests.hs:17:33: Not in scope: `test' I think this has something to do with the changes between QuickCheck v1 and v2. Can someone tell me what I need to do to make this example work? Thank you in advance! Amy From yazicivo at ttmail.com Sat Dec 19 08:37:45 2009 From: yazicivo at ttmail.com (Volkan YAZICI) Date: Sat Dec 19 08:11:39 2009 Subject: [Haskell-beginners] Pure Regex.PCRE Possible? (PLEAC, Fix Style) Message-ID: <87fx77axue.fsf@alamut.alborz.net> Hi, I'm trying to implement FixStyle[1] program of PLEAC[2] for Haskell. (It's missing in the Haskell version of PLEAC.) For this purpose, I needed regular expressions. (Now, I have two problems!) Despite, my code is, IMHO, quite purely functional, Regex.PCRE.String functions totally mess up the design with impure functions they introduce even for really simple string matching stuff. If you'd check out the sources[3], you'll see below impure functions. transDictRegex :: IO PCRE.Regex matchRegex :: String -> IO (String, String, String) translate :: String -> IO String However, if I'm not mistaken, above functions _should_ be absolutely pure. Is it possible to encapsulate impure PCRE functions into their pure equivalents? BTW, why are PCRE functions impure? Regards. [1] http://pleac.sourceforge.net/pleac_perl/strings.html [2] http://pleac.sourceforge.net/ [3] http://hpaste.org/fastcgi/hpaste.fcgi/view?id=14422 From daniel.is.fischer at web.de Sat Dec 19 08:46:00 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Dec 19 08:21:22 2009 Subject: [Haskell-beginners] `coarbitrary' is not a (visible) method of class `Arbitrary' In-Reply-To: <77b28c350912190520q3571dd64jdfc102ea8e0dc6a5@mail.gmail.com> References: <77b28c350912190520q3571dd64jdfc102ea8e0dc6a5@mail.gmail.com> Message-ID: <200912191446.01740.daniel.is.fischer@web.de> Am Samstag 19 Dezember 2009 14:20:43 schrieb Amy de Buitl?ir: > I'm trying to follow the instructions in > http://haskell.org/haskellwiki/How_to_write_a_Haskell_program. I'm at > the step where we've just written a QuickCheck test: > > amy@localhost ~/forbairt/haq $ cat Tests.hs > import Char > import List > import Test.QuickCheck > import Text.Printf > > main = mapM_ (\(s,a) -> printf "%-25s: " s >> a) tests > > instance Arbitrary Char where > arbitrary = choose ('\0', '\128') > coarbitrary c = variant (ord c `rem` 4) > > -- reversing twice a finite list, is the same as identity > prop_reversereverse s = (reverse . reverse) s == id s > where _ = s :: [Int] > > -- and add this to the tests list > tests = [("reverse.reverse/id", test prop_reversereverse)] > > > But when I try to run it, I get the following errors: > > amy@localhost ~/forbairt/haq $ runhaskell Tests.hs > > Tests.hs:10:4: > `coarbitrary' is not a (visible) method of class `Arbitrary' > > Tests.hs:17:33: Not in scope: `test' > > > I think this has something to do with the changes between QuickCheck > v1 and v2. Yes. coarbitrary has moved to its own class, CoArbitrary. Now there's also method shrink in Arbitrary. There is already an instance Arbitrary Char in QC 2, as well as instance CoArbitrary Char. In QC 1, test was a synonym for quickCheck, so why not use quickCheck? > Can someone tell me what I need to do to make this example > work? Thank you in advance! > > Amy HTH, Daniel From amy at nualeargais.ie Sat Dec 19 09:30:10 2009 From: amy at nualeargais.ie (=?ISO-8859-1?Q?Amy_de_Buitl=E9ir?=) Date: Sat Dec 19 09:04:01 2009 Subject: [Haskell-beginners] `coarbitrary' is not a (visible) method of class `Arbitrary' In-Reply-To: <200912191446.01740.daniel.is.fischer@web.de> References: <77b28c350912190520q3571dd64jdfc102ea8e0dc6a5@mail.gmail.com> <200912191446.01740.daniel.is.fischer@web.de> Message-ID: <77b28c350912190630v1a7b61f2k899eb9bc48d9f67@mail.gmail.com> Thank you Daniel, that solved it. In case anyone else is struggling with this, here's a revised version of Test.hs which works fine for me. import Char import List import Test.QuickCheck import Text.Printf main = mapM_ (\(s,a) -> printf "%-25s: " s >> a) tests -- reversing twice a finite list, is the same as identity prop_reversereverse s = (reverse . reverse) s == id s where _ = s :: [Int] -- and add this to the tests list tests = [("reverse.reverse/id", quickCheck prop_reversereverse)] From daniel.is.fischer at web.de Sat Dec 19 09:33:34 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Dec 19 09:08:56 2009 Subject: [Haskell-beginners] `coarbitrary' is not a (visible) method of class `Arbitrary' In-Reply-To: <77b28c350912190630v1a7b61f2k899eb9bc48d9f67@mail.gmail.com> References: <77b28c350912190520q3571dd64jdfc102ea8e0dc6a5@mail.gmail.com> <200912191446.01740.daniel.is.fischer@web.de> <77b28c350912190630v1a7b61f2k899eb9bc48d9f67@mail.gmail.com> Message-ID: <200912191533.35005.daniel.is.fischer@web.de> Am Samstag 19 Dezember 2009 15:30:10 schrieb Amy de Buitl?ir: > import Char > import List The wrappers around the pre-hierarchical-modules standard libraries may not be around forever, so it's better to get used to import Data.Char import Data.List before they're gone. From stephen.tetley at gmail.com Sat Dec 19 12:05:36 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sat Dec 19 11:39:26 2009 Subject: [Haskell-beginners] Pure Regex.PCRE Possible? (PLEAC, Fix Style) In-Reply-To: <87fx77axue.fsf@alamut.alborz.net> References: <87fx77axue.fsf@alamut.alborz.net> Message-ID: <5fdc56d70912190905p29ebd73sef94afadb8a90daf@mail.gmail.com> Hello Under the hood PCRE.regex uses withCStringLen which has the type: withCStringLen :: String -> (CStringLen -> IO a) -> IO a You can see the code here: http://hackage.haskell.org/packages/archive/regex-pcre-builtin/0.94.2.1.7.7/doc/html/src/Text-Regex-PCRE-String.html So the implementation is impure - it is built on impure code. In the Real Word Haskell book, there is another implementation of a PCRE interface, here the authors decided that their use of PCRE is pure. The functions they have that use side effects - allocating memory and freeing it - use the side effects entirely locally inside each function body and the side effects never leak out of any function. http://book.realworldhaskell.org/read/interfacing-with-c-the-ffi.html The implementation from the book is here: http://hackage.haskell.org/package/pcre-light Potentially the author of Text.Regex.PCRE could have decided that the use of PCRE was pure and gone some way to hiding the IO type of withCStringLen and similar functions (withCStringLen already encapsulates its side effects). But as a design decision - if you are using IO it is entirely reasonable to keep within IO even if what you are doing appears pure (and personally I would choose to use the IO version as I like to know when a library I'm using is performing side effects). Best wishes Stephen 2009/12/19 Volkan YAZICI : > Hi, > > I'm trying to implement FixStyle[1] program of PLEAC[2] for Haskell. > (It's missing in the Haskell version of PLEAC.) For this purpose, I > needed regular expressions. (Now, I have two problems!) ?Despite, my > code is, IMHO, quite purely functional, Regex.PCRE.String functions > totally mess up the design with impure functions they introduce even for > really simple string matching stuff. > > If you'd check out the sources[3], you'll see below impure functions. > > ?transDictRegex :: IO PCRE.Regex > ?matchRegex :: String -> IO (String, String, String) > ?translate :: String -> IO String > > However, if I'm not mistaken, above functions _should_ be absolutely > pure. Is it possible to encapsulate impure PCRE functions into their > pure equivalents? > > BTW, why are PCRE functions impure? > > > Regards. > > [1] http://pleac.sourceforge.net/pleac_perl/strings.html > [2] http://pleac.sourceforge.net/ > [3] http://hpaste.org/fastcgi/hpaste.fcgi/view?id=14422 > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From david.robert.gordon at googlemail.com Fri Dec 18 05:54:03 2009 From: david.robert.gordon at googlemail.com (David Gordon) Date: Sat Dec 19 17:17:24 2009 Subject: [Haskell-beginners] Type constraints question In-Reply-To: References: Message-ID: Hi Folks, Total newbie here. I don't know if I am having a syntactic problem or a conceptual problem. This code: data Test = Test data Test2 = Test2 class MyClass a where getChild :: (MyClass b) => a -> b instance MyClass Test where getChild = Test2 instance MyClass Test2 where getChild = Test results in: [1 of 1] Compiling Main ( test.hs, interpreted ) test.hs:10:15: Couldn't match expected type `Test -> b' against inferred type `Test2' In the expression: Test2 In the definition of `getChild': getChild = Test2 In the instance declaration for `MyClass Test' test.hs:13:15: Couldn't match expected type `Test2 -> b' against inferred type `Test' In the expression: Test In the definition of `getChild': getChild = Test In the instance declaration for `MyClass Test2' Failed, modules loaded: none. Is this a reasonable thing to try and do in Haskell? If not, I have a lot more questions... ;) many thanks, David -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091218/ef193dce/attachment.html From drg at david.gordon.name Fri Dec 18 18:19:05 2009 From: drg at david.gordon.name (David Gordon) Date: Sat Dec 19 17:19:09 2009 Subject: [Haskell-beginners] Re: Type constraints question In-Reply-To: References: Message-ID: Ok, now I will try asking the right question (previous try wasn't actually an example of the problem I'm having) Here's the code: data Test = Test data Test2 = Test2 class MyClass a where getChild :: MyClass b => a -> b instance MyClass Test where getChild a = Test2 instance MyClass Test2 where getChild a = Test On HUGS I get: Error occurred ERROR line 9 - Inferred type is not general enough *** Expression : getChild *** Expected type : (MyClass Test, MyClass a) => Test -> a *** Inferred type : (MyClass Test, MyClass Test2) => Test -> Test2 So, what's the problem with always returning a particular instance of MyClass? I just want to constrain it to be an instance of MyClass, nothing more. thanks, David 2009/12/18 David Gordon > > Hi Folks, > Total newbie here. I don't know if I am having a syntactic problem or a conceptual problem. > This code: > data Test = Test > data Test2 = Test2 > class MyClass a where > getChild :: (MyClass b) => a -> b > instance MyClass Test where > getChild = Test2 > instance MyClass Test2 where > getChild = Test > results in: > [1 of 1] Compiling Main ( test.hs, interpreted ) > test.hs:10:15: > Couldn't match expected type `Test -> b' > against inferred type `Test2' > In the expression: Test2 > In the definition of `getChild': getChild = Test2 > In the instance declaration for `MyClass Test' > test.hs:13:15: > Couldn't match expected type `Test2 -> b' > against inferred type `Test' > In the expression: Test > In the definition of `getChild': getChild = Test > In the instance declaration for `MyClass Test2' > Failed, modules loaded: none. > Is this a reasonable thing to try and do in Haskell? If not, I have a lot more questions... ;) > many thanks, > David > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091218/2b3d0fef/attachment.html From chaddai.fouche at gmail.com Sun Dec 20 04:16:59 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Sun Dec 20 03:50:47 2009 Subject: [Haskell-beginners] Pure Regex.PCRE Possible? (PLEAC, Fix Style) In-Reply-To: <87fx77axue.fsf@alamut.alborz.net> References: <87fx77axue.fsf@alamut.alborz.net> Message-ID: On Sat, Dec 19, 2009 at 2:37 PM, Volkan YAZICI wrote: > However, if I'm not mistaken, above functions _should_ be absolutely > pure. Is it possible to encapsulate impure PCRE functions into their > pure equivalents? > > BTW, why are PCRE functions impure? Mainly because they _are_ the core that _is_ encapsulated as you suggested : regex-pcre as many other regex library, provides the same basic mostly pure interface which is in regex-base. That interface comes with many specific pure function (matchText, matchOnce, matchAll and so on, as well as makeRegex and others) and some "magic" operators like =~ which decides what kind of matching you want to do depending on the type of the result. See this tutorial for some example of usage : http://www.serpentine.com/blog/2007/02/27/a-haskell-regular-expression-tutorial/ -- Jeda? From kane96 at gmx.de Sun Dec 20 08:36:06 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Sun Dec 20 08:09:57 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <7b501d5c0912180959j4248552xcf30b4deed8d01f5@mail.gmail.com> References: <20091217172121.159700@gmx.net> <7b501d5c0912180906l655b34c3safe2bcfec0d87c52@mail.gmail.com> <20091218174245.113160@gmx.net> <7b501d5c0912180959j4248552xcf30b4deed8d01f5@mail.gmail.com> Message-ID: <20091220133606.160220@gmx.net> Maybe I didn't understand the exercise if have to do. It says: "Write the instance Enum Nat where toEnum is defined as a total function that returns Z for negative integers. Some examples: *Main> toEnum (-1) :: Nat Z *Main> toEnum 0 :: Nat Z *Main> toEnum 1 :: Nat S Z *Main> fromEnum (S (S Z)) 2 so I did: data Nat = Z | S Nat deriving (Eq,Ord,Show) instance Enum Nat where toEnum x|x > 0 = S Z |otherwise = Z somehow it looks really wrong. Do you understand want I have to do and how it should look like? -------- Original-Nachricht -------- > Datum: Fri, 18 Dec 2009 18:59:40 +0100 > Von: Deniz Dogan > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] Enum for natural numbers > 2009/12/18 : > > ahhh, ok, thanks so far. Here is how the output should looks like: > > *Main> toEnum (-1) :: Nat > > Z > > *Main> toEnum 0 :: Nat > > Z > > *Main> toEnum 1 :: Nat > > S Z > > *Main> fromEnum (S (S Z)) > > 2 > > > > the first three things work, but I don't know about the last one. Does > anybody how it should work and what's the sense of it? > > > > Looks right to me. "Z" means 0 (Zero), "S x" means "the Successor of > x". So (S (S (S Z))) means "the successor of the successor of the > successor of zero", which is 3. > > > > > -------- Original-Nachricht -------- > >> Datum: Fri, 18 Dec 2009 18:06:32 +0100 > >> Von: Deniz Dogan > >> An: kane96@gmx.de > >> CC: beginners@haskell.org > >> Betreff: Re: [Haskell-beginners] Enum for natural numbers > > > >> 2009/12/17 ?: > >> > Hi, > >> > I have data Nat = Z | S Nat deriving (Eq,Ord,Show) > >> > > >> > toEnum should return Z for negative numbers. I did something like > this > >> but the problem is I don't know how to set "less than". I tried > and > lt: > >> > > >> > instance Enum Nat where > >> > ? ?toEnum (gt 0) = S Z > >> > ? ?toEnum (lt 1) = Z > >> > -- > >> > GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! > >> > Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 > >> > _______________________________________________ > >> > Beginners mailing list > >> > Beginners@haskell.org > >> > http://www.haskell.org/mailman/listinfo/beginners > >> > > >> > >> Fill in the gaps: > >> > >> instance Enum Nat where > >> ? ? toEnum x | x <= 0 = ... > >> ? ? ? ? ? ? ?| otherwise = ... > >> > >> -- > >> Deniz Dogan > > > > -- > > Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox > 3.5 - > > sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > > > > > -- > Deniz Dogan -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From deniz.a.m.dogan at gmail.com Sun Dec 20 08:45:02 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Sun Dec 20 08:19:10 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091220133606.160220@gmx.net> References: <20091217172121.159700@gmx.net> <7b501d5c0912180906l655b34c3safe2bcfec0d87c52@mail.gmail.com> <20091218174245.113160@gmx.net> <7b501d5c0912180959j4248552xcf30b4deed8d01f5@mail.gmail.com> <20091220133606.160220@gmx.net> Message-ID: <7b501d5c0912200545w6a47d8c7vb4cdcfe2a27c5eb@mail.gmail.com> 2009/12/20 : > Maybe I didn't understand the exercise if have to do. It says: > "Write the instance Enum Nat where toEnum is defined as a total function that returns Z for negative integers. Some examples: > *Main> toEnum (-1) :: Nat > Z > *Main> toEnum 0 :: Nat > Z > *Main> toEnum 1 :: Nat > S Z > *Main> fromEnum (S (S Z)) > 2 > > so I did: > data Nat = Z | S Nat deriving (Eq,Ord,Show) > instance Enum Nat where > toEnum x|x > 0 = S Z > ? ? ? ?|otherwise = Z > > > somehow it looks really wrong. Do you understand want I have to do and how it should look like? > In your current definition of toEnum, you always return "S Z" (in other words, "1", "the successor of zero") for any integer i > 0. This is clearly incorrect as you said. Your "otherwise" guard is correct, but the other one is not. I get the feeling that this exercise is about learning how to use recursion, so look into that. A few relevant links: http://en.wikibooks.org/wiki/Haskell/Recursion (the factorial example) http://learnyouahaskell.com/recursion http://book.realworldhaskell.org/read/functional-programming.html Hope that helps -- Deniz Dogan From kane96 at gmx.de Sun Dec 20 08:50:41 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Sun Dec 20 08:24:29 2009 Subject: [Haskell-beginners] inserting tupels inside list as tupels in list In-Reply-To: <20091218225812.GA19856@seas.upenn.edu> References: <20091218180216.113150@gmx.net> <20091218225812.GA19856@seas.upenn.edu> Message-ID: <20091220135041.160230@gmx.net> I already have things like that: type Day = Int 17 data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) type Year = Int type Date = (Day,Month,Year) type ID = Int type Event = (ID,String) type Organiser = [ (Date, [Event]) ] and now I should implement a function like this: addEvents :: Date -> [Event] -> Organiser -> Organiser that adds to an organiser a list of events for a specific date an example looks like this: xmas :: Event xmas = (2, "Christmas") aliceOrg :: Organiser aliceOrg = [ ( (21,Dec,2009), [panic,aliceBDay] ), ( (25,Dec,2009), [xmas] ) ] -------- Original-Nachricht -------- > Datum: Fri, 18 Dec 2009 17:58:12 -0500 > Von: Brent Yorgey > An: beginners@haskell.org > Betreff: Re: [Haskell-beginners] inserting tupels inside list as tupels in list > On Fri, Dec 18, 2009 at 07:02:16PM +0100, kane96@gmx.de wrote: > > maybe the subject is a little bit confusing :p > > > > I have a organiser list like that and have to add events (like panic, > xmas, ...) which is also a type of tupel for a specific date: > > > > aliceOrg = [ ( (21,Dec,2009), [panic,aliceBDay] ) > > ( (25,Dec,2009), [xmas] ) > > ( (10,Jan,2010), [bobBDay] ) > > > > What function(s) can I use to add these nested lists and tupels here? > > You can use all the functions for manipulating lists and tuples in the > standard libraries... I'm not entirely sure what you are asking. > > Let me suggest, however, that you probably don't want to be using > tuples so much; make your own data types. Something like this: > > type Day = Int > data Month = Jan | Feb | ... > type Year = Int > > data Date = Date Day Month Year > > data CalEntry = CalEntry Date [Event] > data Event = ... > > type Organizer = [CalEntry] > > This is much less confusing since instead of just tuples everywhere > you have specific types that say exactly what the data represents. > > -Brent > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- Preisknaller: GMX DSL Flatrate f?r nur 16,99 Euro/mtl.! http://portal.gmx.net/de/go/dsl02 From daniel.is.fischer at web.de Sun Dec 20 08:59:45 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Dec 20 08:35:02 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091220133606.160220@gmx.net> References: <20091217172121.159700@gmx.net> <7b501d5c0912180959j4248552xcf30b4deed8d01f5@mail.gmail.com> <20091220133606.160220@gmx.net> Message-ID: <200912201459.46280.daniel.is.fischer@web.de> Am Sonntag 20 Dezember 2009 14:36:06 schrieb kane96@gmx.de: > Maybe I didn't understand the exercise if have to do. It says: > "Write the instance Enum Nat where toEnum is defined as a total function > that returns Z for negative integers. Some examples: *Main> toEnum (-1) :: > Nat > Z > *Main> toEnum 0 :: Nat > Z > *Main> toEnum 1 :: Nat > S Z > *Main> fromEnum (S (S Z)) > 2 > > so I did: > data Nat = Z | S Nat deriving (Eq,Ord,Show) > instance Enum Nat where > toEnum x|x > 0 = S Z > > |otherwise = Z > > somehow it looks really wrong. Do you understand want I have to do and how > it should look like? > Your task is to write an Enum instance for Nat. class Enum a where succ :: a -> a pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int enumFrom :: a -> [a] enumFromThen :: a -> a -> [a] enumFromTo :: a -> a -> [a] enumFromThenTo :: a -> a -> a -> [a] So you have to write functions succ :: Nat -> Nat -- that's very easy pred :: Nat -> Nat -- easy too, except you have to decide whether to throw an error on pred Z or have pred Z = Z (which would fit with the required toEnum) toEnum :: Int -> Nat -- that has the additional requirement that it should return Z for negative input and so on. The first thing is to understand the Nat datatype. That models the so-called Peano numbers (or, put another way, it's built to mirror the Peano axioms for the natural numbers). Z corresponds to 0 S Z corresponds to 1, which is the successor of 0 S (S Z) corresponds to 2, which is the successor of 1 ... For non-negative n, toEnum n should be the Peano number corresponding to n and for negative n, toEnum n should be Z (to avoid exceptions). So, toEnum n | n < 0 = Z toEnum 0 = Z toEnum n = ? -- here, we know n > 0 fromEnum should be the correspondnece the other way round, so fromEnum Z = 0 fromEnum (S p) = ? -- which Int corresponds to the successor of p? From yazicivo at ttmail.com Sun Dec 20 09:34:11 2009 From: yazicivo at ttmail.com (Volkan YAZICI) Date: Sun Dec 20 09:08:01 2009 Subject: [Haskell-beginners] Re: Pure Regex.PCRE Possible? (PLEAC, Fix Style) In-Reply-To: <87fx77axue.fsf@alamut.alborz.net> (Volkan YAZICI's message of "Sat\, 19 Dec 2009 15\:37\:45 +0200") References: <87fx77axue.fsf@alamut.alborz.net> Message-ID: <877hshogt8.fsf@alamut.alborz.net> On Sat, 19 Dec 2009, Volkan YAZICI writes: > I'm trying to implement FixStyle[1] program of PLEAC[2] for Haskell. > (It's missing in the Haskell version of PLEAC.) For this purpose, I > needed regular expressions. (Now, I have two problems!) Despite, my > code is, IMHO, quite purely functional, Regex.PCRE.String functions > totally mess up the design with impure functions they introduce even for > really simple string matching stuff. > > If you'd check out the sources[3], you'll see below impure functions. > > transDictRegex :: IO PCRE.Regex > matchRegex :: String -> IO (String, String, String) > translate :: String -> IO String > > However, if I'm not mistaken, above functions _should_ be absolutely > pure. Is it possible to encapsulate impure PCRE functions into their > pure equivalents? > > BTW, why are PCRE functions impure? OTH, I'm looking at my "translate" and it fails on infinite strings. Is it because of something lacking in my implementation, or a limitation of Regex.PCRE? Regards. -------------- next part -------------- A non-text attachment was scrubbed... Name: FixStyle.hs Type: text/x-haskell Size: 2113 bytes Desc: not available Url : http://www.haskell.org/pipermail/beginners/attachments/20091220/f30cf389/FixStyle.bin From daniel.is.fischer at web.de Sun Dec 20 09:52:06 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Dec 20 09:27:57 2009 Subject: [Haskell-beginners] Re: Pure Regex.PCRE Possible? (PLEAC, Fix Style) In-Reply-To: <877hshogt8.fsf@alamut.alborz.net> References: <87fx77axue.fsf@alamut.alborz.net> <877hshogt8.fsf@alamut.alborz.net> Message-ID: <200912201552.06467.daniel.is.fischer@web.de> Am Sonntag 20 Dezember 2009 15:34:11 schrieb Volkan YAZICI: > > OTH, I'm looking at my "translate" and it fails on infinite strings. Is > it because of something lacking in my implementation, or a limitation of > Regex.PCRE? > > > Regards. I don't know whether the regex library can deal well with infinite input, but in translate input = do ? (head, word, tail) <- matchRegex input ? tailTrans <- (translate tail) ? return $ head ++ (transWord word) ++ tailTrans the IO-semantics require that the whole input is processed before anything is returned (translating tail might throw an exception, after all). Maybe it'll work with a little unsafeInterleaveIO magic: import System.IO.Unsafe translate input = do ? (head, word, tail) <- matchRegex input ? tailTrans <- unsafeInterleaveIO (translate tail) ? return $ head ++ (transWord word) ++ tailTrans From daniel.is.fischer at web.de Sun Dec 20 10:16:32 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Dec 20 09:51:49 2009 Subject: [Haskell-beginners] Re: Pure Regex.PCRE Possible? (PLEAC, Fix Style) In-Reply-To: <200912201552.06467.daniel.is.fischer@web.de> References: <87fx77axue.fsf@alamut.alborz.net> <877hshogt8.fsf@alamut.alborz.net> <200912201552.06467.daniel.is.fischer@web.de> Message-ID: <200912201616.33274.daniel.is.fischer@web.de> Am Sonntag 20 Dezember 2009 15:52:06 schrieb Daniel Fischer: > Am Sonntag 20 Dezember 2009 15:34:11 schrieb Volkan YAZICI: > > OTH, I'm looking at my "translate" and it fails on infinite strings. Is > > it because of something lacking in my implementation, or a limitation of > > Regex.PCRE? > > > > > > Regards. > > I don't know whether the regex library can deal well with infinite input, No, it can't. It uses withCStringLen, that's not capable of dealing with infinite input. From kane96 at gmx.de Sun Dec 20 15:06:36 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Sun Dec 20 14:40:23 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <200912201459.46280.daniel.is.fischer@web.de> References: <20091217172121.159700@gmx.net> <7b501d5c0912180959j4248552xcf30b4deed8d01f5@mail.gmail.com> <20091220133606.160220@gmx.net> <200912201459.46280.daniel.is.fischer@web.de> Message-ID: <20091220200636.160190@gmx.net> -------- Original-Nachricht -------- > Datum: Sun, 20 Dec 2009 14:59:45 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] Enum for natural numbers > Am Sonntag 20 Dezember 2009 14:36:06 schrieb kane96@gmx.de: > > Maybe I didn't understand the exercise if have to do. It says: > > "Write the instance Enum Nat where toEnum is defined as a total function > > that returns Z for negative integers. Some examples: *Main> toEnum (-1) > :: > > Nat > > Z > > *Main> toEnum 0 :: Nat > > Z > > *Main> toEnum 1 :: Nat > > S Z > > *Main> fromEnum (S (S Z)) > > 2 > > > > so I did: > > data Nat = Z | S Nat deriving (Eq,Ord,Show) > > instance Enum Nat where > > toEnum x|x > 0 = S Z > > > > |otherwise = Z > > > > somehow it looks really wrong. Do you understand want I have to do and > how > > it should look like? > > > > Your task is to write an Enum instance for Nat. > > class Enum a where > succ :: a -> a > pred :: a -> a > toEnum :: Int -> a > fromEnum :: a -> Int > enumFrom :: a -> [a] > enumFromThen :: a -> a -> [a] > enumFromTo :: a -> a -> [a] > enumFromThenTo :: a -> a -> a -> [a] > > So you have to write functions > > succ :: Nat -> Nat -- that's very easy > pred :: Nat -> Nat -- easy too, except you have to decide whether to > throw an error > on pred Z or have pred Z = Z (which would fit with the required toEnum) > > toEnum :: Int -> Nat > -- that has the additional requirement that it should return Z for > negative input > > and so on. > > The first thing is to understand the Nat datatype. That models the > so-called Peano numbers > (or, put another way, it's built to mirror the Peano axioms for the > natural numbers). > Z corresponds to 0 > S Z corresponds to 1, which is the successor of 0 > S (S Z) corresponds to 2, which is the successor of 1 ... > > For non-negative n, toEnum n should be the Peano number corresponding to n > and for > negative n, toEnum n should be Z (to avoid exceptions). > So, > > toEnum n > | n < 0 = Z > toEnum 0 = Z > toEnum n = ? -- here, we know n > 0 > > fromEnum should be the correspondnece the other way round, so > > fromEnum Z = 0 > fromEnum (S p) = ? -- which Int corresponds to the successor of p? what is P? Now I read some short textes about it and think I know more or less what I have to do for the exercise. But I don't know really how. Do you know any examples for it, how it normally looks like? -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From daniel.is.fischer at web.de Sun Dec 20 15:28:21 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Dec 20 15:05:09 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091220200636.160190@gmx.net> References: <20091217172121.159700@gmx.net> <200912201459.46280.daniel.is.fischer@web.de> <20091220200636.160190@gmx.net> Message-ID: <200912202128.22006.daniel.is.fischer@web.de> Am Sonntag 20 Dezember 2009 21:06:36 schrieb kane96@gmx.de: > > So, > > > > toEnum n > > ? ? | n < 0 = Z > > toEnum 0 = Z > > toEnum n = ? ? ?-- here, we know n > 0 > > > > fromEnum should be the correspondnece the other way round, so > > > > fromEnum Z = 0 > > fromEnum (S p) = ? ? ? ?-- which Int corresponds to the successor of p? > > what is P? Any element of Nat (p for Peano). > > Now I read some short textes about it and think I know more or less what I > have to do for the exercise. But I don't know really how. Do you know any > examples for it, how it normally looks like? Deniz Dogan posted a few links to recursion earlier today, if you look at them, you should get the general idea. As a further example, replicate :: Int -> a -> [a] replicate n x | n <= 0 = [] | otherwise = x:replicate (n-1) x may help. From kane96 at gmx.de Sun Dec 20 15:35:45 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Sun Dec 20 15:09:35 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <200912202128.22006.daniel.is.fischer@web.de> References: <20091217172121.159700@gmx.net> <200912201459.46280.daniel.is.fischer@web.de> <20091220200636.160190@gmx.net> <200912202128.22006.daniel.is.fischer@web.de> Message-ID: <20091220203545.160190@gmx.net> -------- Original-Nachricht -------- > Datum: Sun, 20 Dec 2009 21:28:21 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > Betreff: Re: [Haskell-beginners] Enum for natural numbers > Am Sonntag 20 Dezember 2009 21:06:36 schrieb kane96@gmx.de: > > > So, > > > > > > toEnum n > > > ? ? | n < 0 = Z > > > toEnum 0 = Z > > > toEnum n = ? ? ?-- here, we know n > 0 > > > > > > fromEnum should be the correspondnece the other way round, so > > > > > > fromEnum Z = 0 > > > fromEnum (S p) = ? ? ? ?-- which Int corresponds to the successor > of p? > > > > what is P? > > Any element of Nat (p for Peano). > > > > > Now I read some short textes about it and think I know more or less what > I > > have to do for the exercise. But I don't know really how. Do you know > any > > examples for it, how it normally looks like? > > Deniz Dogan posted a few links to recursion earlier today, if you look at > them, you should > get the general idea. > As a further example, > > replicate :: Int -> a -> [a] > replicate n x > | n <= 0 = [] > | otherwise = x:replicate (n-1) x > > may help. my problem is that I don't know how to use Enum correctly and didn't find any helpfull example > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser From deniz.a.m.dogan at gmail.com Sun Dec 20 15:39:39 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Sun Dec 20 15:13:44 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091220203545.160190@gmx.net> References: <20091217172121.159700@gmx.net> <200912201459.46280.daniel.is.fischer@web.de> <20091220200636.160190@gmx.net> <200912202128.22006.daniel.is.fischer@web.de> <20091220203545.160190@gmx.net> Message-ID: <7b501d5c0912201239p593ebb24y854581c6bb543a82@mail.gmail.com> 2009/12/20 : > > -------- Original-Nachricht -------- >> Datum: Sun, 20 Dec 2009 21:28:21 +0100 >> Von: Daniel Fischer >> An: beginners@haskell.org >> Betreff: Re: [Haskell-beginners] Enum for natural numbers > >> Am Sonntag 20 Dezember 2009 21:06:36 schrieb kane96@gmx.de: >> > > So, >> > > >> > > toEnum n >> > > ? ? | n < 0 = Z >> > > toEnum 0 = Z >> > > toEnum n = ? ? ?-- here, we know n > 0 >> > > >> > > fromEnum should be the correspondnece the other way round, so >> > > >> > > fromEnum Z = 0 >> > > fromEnum (S p) = ? ? ? ?-- which Int corresponds to the successor >> of p? >> > >> > what is P? >> >> Any element of Nat (p for Peano). >> >> > >> > Now I read some short textes about it and think I know more or less what >> I >> > have to do for the exercise. But I don't know really how. Do you know >> any >> > examples for it, how it normally looks like? >> >> Deniz Dogan posted a few links to recursion earlier today, if you look at >> them, you should >> get the general idea. >> As a further example, >> >> replicate :: Int -> a -> [a] >> replicate n x >> ? ? | n <= 0 ? ?= [] >> ? ? | otherwise = x:replicate (n-1) x >> >> may help. > > my problem is that I don't know how to use Enum correctly and didn't find any helpfull example > If I may say so, I don't think that your understanding of Enum is the problem here, it's the lack of understanding of Haskell in general, but specifically algebraic data types[1] and recursion[2]. [1] data Maybe a = Just a | Nothing [2] f n = f (n - 1) + f (n - 2) -- Deniz Dogan From ml at isaac.cedarswampstudios.org Sun Dec 20 15:55:37 2009 From: ml at isaac.cedarswampstudios.org (Isaac Dupree) Date: Sun Dec 20 15:29:38 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091220203545.160190@gmx.net> References: <20091217172121.159700@gmx.net> <200912201459.46280.daniel.is.fischer@web.de> <20091220200636.160190@gmx.net> <200912202128.22006.daniel.is.fischer@web.de> <20091220203545.160190@gmx.net> Message-ID: <4B2E8F49.2000507@isaac.cedarswampstudios.org> kane96@gmx.de wrote: > -------- Original-Nachricht -------- >> Datum: Sun, 20 Dec 2009 21:28:21 +0100 >> Von: Daniel Fischer >> An: beginners@haskell.org >> Betreff: Re: [Haskell-beginners] Enum for natural numbers > >> Am Sonntag 20 Dezember 2009 21:06:36 schrieb kane96@gmx.de: >>>> So, >>>> >>>> toEnum n >>>> | n < 0 = Z >>>> toEnum 0 = Z >>>> toEnum n = ? -- here, we know n > 0 >>>> >>>> fromEnum should be the correspondnece the other way round, so >>>> >>>> fromEnum Z = 0 >>>> fromEnum (S p) = ? -- which Int corresponds to the successor >> of p? >>> what is P? >> Any element of Nat (p for Peano). >> >>> Now I read some short textes about it and think I know more or less what >> I >>> have to do for the exercise. But I don't know really how. Do you know >> any >>> examples for it, how it normally looks like? >> Deniz Dogan posted a few links to recursion earlier today, if you look at >> them, you should >> get the general idea. >> As a further example, >> >> replicate :: Int -> a -> [a] >> replicate n x >> | n <= 0 = [] >> | otherwise = x:replicate (n-1) x >> >> may help. > > my problem is that I don't know how to use Enum correctly and didn't find any helpfull example Enum is used for things that are in sequence and can be numbered likewise. For example, (if you consider Monday the first day of the week) data Weekday = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday probably Monday would correspond to 0, Tuesday to 1, Wednesday to 2, and so on through Sunday corresponding to 6. In your problem, data Nat = Z | S Nat Z corresponds to 0, (S Z) corresponds to 1, (S (S Z)) corresponds to 2, and so on forever. Perhaps you can see this by seeing "Z" as "0" and "S" as "1 +". Z <-> 0 (S Z) <-> (1 + 0) (S (S Z)) <-> (1 + (1 + 0)) etc... but you'll have to find a way to define this pattern with just a small number of cases, not a huge infinite number. -Isaac From daniel.is.fischer at web.de Sun Dec 20 15:55:49 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Dec 20 15:31:04 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091220203545.160190@gmx.net> References: <20091217172121.159700@gmx.net> <200912202128.22006.daniel.is.fischer@web.de> <20091220203545.160190@gmx.net> Message-ID: <200912202155.49743.daniel.is.fischer@web.de> Am Sonntag 20 Dezember 2009 21:35:45 schrieb kane96@gmx.de: > > As a further example, > > > > replicate :: Int -> a -> [a] > > replicate n x > > > > | n <= 0 = [] > > | otherwise = x:replicate (n-1) x > > > > may help. > > my problem is that I don't know how to use Enum correctly and didn't find > any helpfull example > toEnum and fromEnum should give the correspondence 0 <-> Z 1 <-> S Z 2 <-> S (S Z) 3 <-> S (S (S Z)) 4 <-> S (S (S (S Z))) 5 <-> S (S (S (S (S Z)))) and so on. Of course, defining toEnum entirely via pattern matching toEnum 0 = Z toEnum 1 = S Z toEnum 2 = S (S Z) toEnum 3 = S (S (S Z)) ... will take too long to type (and will drive the compiler mad), so define it via recursion. It will strongly resemble the definition of replicate above. The definition of fromEnum will resemble that of genericLength, http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/src/Data- List.html#genericLength From kane96 at gmx.de Sun Dec 20 16:11:51 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Sun Dec 20 15:45:39 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: References: <20091218160101.113160@gmx.net> Message-ID: <20091220211151.160210@gmx.net> I implemented the first step which works if I fix the months (instead of the Month Enum) and just return the day and not an element of type Date this works: calendar year = [ day | month <- [Jan, Feb], day <- [1..31], legalDate(day,month,year) == True ] this doesn't work: calendar year = [ Date(day,month,year) | month <- Month, day <- [1..31], legalDate(day,month,year) == True ] -------- Original-Nachricht -------- > Datum: Sat, 19 Dec 2009 11:16:45 +0100 > Von: "Chadda? Fouch?" > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] print all days of calendar > On Fri, Dec 18, 2009 at 5:01 PM, wrote: > > I also have a function from a previous exercise which checks if a given > date is valid. Is there a function for a loop that iterates from 1 to n and > checks if the date is valid. If it's valid it should return the date > otherwise it should jump to the next month or end at the end of the year? Or is > it better to do it on another way with this data I have? > > Since you derived Enum for Month, you can do [Jan..Dec] and get the > list of the months in order. There are then two options, either you > generate all cartesian product of [Jan..Dec] and [1..31] and check > which are valid, or you write a function that for a given month and > year tells you how many days it counts and then generate for month "m" > all the pair in combination with [1..daysCount m]. > > Whatever your decision, list comprehensions are probably the tool of > choice to do it though it is by no mean harder to do without. > > -- > Jeda? -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From uzytkownik2 at gmail.com Sun Dec 20 16:23:13 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Sun Dec 20 15:57:26 2009 Subject: [Haskell-beginners] Problems with EclipseFP Message-ID: <1261344193.5673.1.camel@picard> Did anyone used eclipsefp? I installed version 2 but I didn't change anything in eclipse (I haven't notice a difference - it does not recognise .hs file, nothing about haskell in help/new project/new file etc.). Regards From daniel.is.fischer at web.de Sun Dec 20 16:25:53 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Dec 20 16:01:08 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <20091220211151.160210@gmx.net> References: <20091218160101.113160@gmx.net> <20091220211151.160210@gmx.net> Message-ID: <200912202225.53592.daniel.is.fischer@web.de> Am Sonntag 20 Dezember 2009 22:11:51 schrieb kane96@gmx.de: > I implemented the first step which works if I fix the months (instead of > the Month Enum) and just return the day and not an element of type Date > > this works: > calendar year = [ day | month <- [Jan, Feb], day <- [1..31], > legalDate(day,month,year) ? ? == True ] > > this doesn't work: > calendar year = [ Date(day,month,year) | month <- Month, day <- [1..31], > legalDate(day,month,year) ? ? == True ] Date was a type synonym for the triple, so calendar year = [ (day,month,year) | month <- Month, day <- [1..31], legalDate(day,month,year)] should be what you want. Note, "condition == True" is better written as "condition". From drg at david.gordon.name Mon Dec 21 02:18:11 2009 From: drg at david.gordon.name (David Gordon) Date: Mon Dec 21 01:52:15 2009 Subject: [Haskell-beginners] Type constraints question In-Reply-To: <200912190215.10442.daniel.is.fischer@web.de> References: <200912190215.10442.daniel.is.fischer@web.de> Message-ID: Thanks for this detailed reply, that's helped with a lot of questions I had. I think the real problem here is that I am still looking for C++/Java-style subtype polymorphism. I wanted the child to be any type implementing MyClass, including types declared in other modules, without having to declare a new MyClass each time to be able to return that type. I thought that simply promising to return some type implementing the MyClass interface would be enough to satisfy type safety. The thing I am actually trying to build is a dynamically-generated view on a large tree structure. The generation is done by a chain of objects built according to a configuration loaded at runtime. Each object in the chain represents modifications to the tree which it exposes via a simple getChildren/getParent interface which exposes the view on the tree generated by the chain. Crucially, it should be possible to introduce new chain objects, and it should also be possible to create arbitrary chains at runtime. In some cases the result of getChildren will vary depending on the runtime-constructed chain. It seems like the simplest solution (in pure Haskell 98 at least) would be to unify my possible child classes into a single Test data type with different constructors and methods according to the different types I was trying to implement before. So, I lose the extensibility but at least I can prototype my design in a simple way. I am also investigating type families and GADTs - feels like it will be a few sessions before I've got my head around them. It seems like being expert in type systems is part of the Haskell lifestyle! thanks for your help, David 2009/12/18 Daniel Fischer Am Samstag 19 Dezember 2009 00:55:34 schrieb David Gordon: > Apologies for the spam, I had some difficulty getting my email address set > up right on the list and wanted to make sure this finally got through (or > perhaps there are like 5 copies on the list now... sorry.) > > thanks > > ---------- Forwarded message ---------- > > Ok, now I will try asking the right question (previous try wasn't actually > an example of the problem I'm having) > > Here's the code: > > > data Test = Test > > data Test2 = Test2 > > class MyClass a where > ? ? getChild :: MyClass b => a -> b > > instance MyClass Test where > ? ? getChild a = Test2 > > instance MyClass Test2 where > ? ? getChild a = Test > > On HUGS I get: > > Error occurred > ERROR line 9 - Inferred type is not general enough > *** Expression ? ?: getChild > *** Expected type : (MyClass Test, MyClass a) => Test -> a > *** Inferred type : (MyClass Test, MyClass Test2) => Test -> Test2 > > So, what's the problem with always returning a particular instance of > MyClass? I just want to constrain it to be an instance of MyClass, nothing > more. The signature of getChild promises that *whichever type the caller wants*, as long as it's a member of MyClass, it can be provided. The implementation returns one specific type. It's different from interfaces in Java, where the callee decides which type is returned, here the caller can demand the type that the callee has to return. The signature of getChild is actually getChild :: forall b. MyClass b => a -> b while the implementation has the signature (not legal Haskell) getChild :: exists b. MyClass b => a -> b. What you want is, I believe, that each instance a of MyClass specifies a type b belonging to MyClass which getChild returns. You can achieve part of that for example with a multiparameter type class {-# LANGUAGE MultiParamTypeClasses #-} class MyClass2 a b where ? ?getChild :: a -> b However, this allows that a has children of more than one type ( instance MyClass2 Test Test2 where ? ?getChild _ = Test2 instance MyClass2 Test Test where ? ?getChild _ = Test ) and this doesn't enforce that b itself has children. To enforce that every type has only one type of children, you can use functional dependencies (or type families, see below): {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} class MyClass3 a b | a -> b where ? ?getChild :: a -> b The functional dependency "a -> b" (separated from the class head by "|") says that a uniquely determines b. But that still doesn't enforce that b has children. For that, you need {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts #-} class MyClass4 a b | a -> b where ? ?getChild :: MyClass4 b c => a -> b Now each type can have only one type of children and they must have children too. Another way to achieve the above is via type families: {-# LANGUAGE TypeFamilies, FlexibleContexts #-} class MyClass5 a where ? ?type Child a :: * ? ?getChild :: (MyClass5 (Child a)) => a -> Child a instance MyClass5 Test where ? ?type Child Test = Test2 ? ?getChild _ = Test2 instance MyClass5 Test2 where ? ?type Child Test2 = Test ? ?getChild _ = Test > > thanks, > > David > > > 2009/12/18 David Gordon > > > Hi Folks, > > Total newbie here. I don't know if I am having a syntactic problem or a > > conceptual problem. > > > This code: > > data Test = Test > > data Test2 = Test2 > > class MyClass a where > > ? ? getChild :: (MyClass b) => a -> b > > instance MyClass Test where > > ? ? getChild = Test2 > > instance MyClass Test2 where > > ? ? getChild = Test > > results in: > > [1 of 1] Compiling Main ? ? ? ? ? ? ( test.hs, interpreted ) > > test.hs:10:15: > > ? ? Couldn't match expected type `Test -> b' > > ? ? ? ? ? ?against inferred type `Test2' > > ? ? In the expression: Test2 > > ? ? In the definition of `getChild': getChild = Test2 > > ? ? In the instance declaration for `MyClass Test' > > test.hs:13:15: > > ? ? Couldn't match expected type `Test2 -> b' > > ? ? ? ? ? ?against inferred type `Test' > > ? ? In the expression: Test > > ? ? In the definition of `getChild': getChild = Test > > ? ? In the instance declaration for `MyClass Test2' > > Failed, modules loaded: none. > > Is this a reasonable thing to try and do in Haskell? If not, I have a lot > > more questions... ;) > > > many thanks, > > David From kane96 at gmx.de Mon Dec 21 04:56:06 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 04:29:54 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <7b501d5c0912200545w6a47d8c7vb4cdcfe2a27c5eb@mail.gmail.com> References: <20091217172121.159700@gmx.net> <7b501d5c0912180906l655b34c3safe2bcfec0d87c52@mail.gmail.com> <20091218174245.113160@gmx.net> <7b501d5c0912180959j4248552xcf30b4deed8d01f5@mail.gmail.com> <20091220133606.160220@gmx.net> <7b501d5c0912200545w6a47d8c7vb4cdcfe2a27c5eb@mail.gmail.com> Message-ID: <20091221095606.63560@gmx.net> Now everything works but to print Z also for negative Integers. Don't know how to implement the <=0 or le0 in this case again: instance Enum Nat where toEnum 0 = Z toEnum (n+1) = S(toEnum n) fromEnum Z = 0 fromEnum (S n) = 1 + fromEnum n -------- Original-Nachricht -------- > Datum: Sun, 20 Dec 2009 14:45:02 +0100 > Von: Deniz Dogan > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] Enum for natural numbers > 2009/12/20 : > > Maybe I didn't understand the exercise if have to do. It says: > > "Write the instance Enum Nat where toEnum is defined as a total function > that returns Z for negative integers. Some examples: > > *Main> toEnum (-1) :: Nat > > Z > > *Main> toEnum 0 :: Nat > > Z > > *Main> toEnum 1 :: Nat > > S Z > > *Main> fromEnum (S (S Z)) > > 2 > > > > so I did: > > data Nat = Z | S Nat deriving (Eq,Ord,Show) > > instance Enum Nat where > > toEnum x|x > 0 = S Z > > ? ? ? ?|otherwise = Z > > > > > > somehow it looks really wrong. Do you understand want I have to do and > how it should look like? > > > > In your current definition of toEnum, you always return "S Z" (in > other words, "1", "the successor of zero") for any integer i > 0. This > is clearly incorrect as you said. Your "otherwise" guard is correct, > but the other one is not. I get the feeling that this exercise is > about learning how to use recursion, so look into that. > > A few relevant links: > http://en.wikibooks.org/wiki/Haskell/Recursion (the factorial example) > http://learnyouahaskell.com/recursion > http://book.realworldhaskell.org/read/functional-programming.html > > Hope that helps > > -- > Deniz Dogan -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser From kane96 at gmx.de Mon Dec 21 05:05:03 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 04:38:49 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <200912202225.53592.daniel.is.fischer@web.de> References: <20091218160101.113160@gmx.net> <20091220211151.160210@gmx.net> <200912202225.53592.daniel.is.fischer@web.de> Message-ID: <20091221100503.63530@gmx.net> -------- Original-Nachricht -------- > Datum: Sun, 20 Dec 2009 22:25:53 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] print all days of calendar > Am Sonntag 20 Dezember 2009 22:11:51 schrieb kane96@gmx.de: > > I implemented the first step which works if I fix the months (instead of > > the Month Enum) and just return the day and not an element of type Date > > > > this works: > > calendar year = [ day | month <- [Jan, Feb], day <- [1..31], > > legalDate(day,month,year) ? ? == True ] > > > > this doesn't work: > > calendar year = [ Date(day,month,year) | month <- Month, day <- [1..31], > > legalDate(day,month,year) ? ? == True ] > > Date was a type synonym for the triple, so > calendar year > = [ (day,month,year) | month <- Month, day <- [1..31], > legalDate(day,month,year)] > > should be what you want. > Note, "condition == True" is better written as "condition". still have the problem that it says: "Not in scope: data constructor `Month'" but Month is declared as: data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) -- Preisknaller: GMX DSL Flatrate f?r nur 16,99 Euro/mtl.! http://portal.gmx.net/de/go/dsl02 From deniz.a.m.dogan at gmail.com Mon Dec 21 05:25:46 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Mon Dec 21 04:59:50 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091221095606.63560@gmx.net> References: <20091217172121.159700@gmx.net> <7b501d5c0912180906l655b34c3safe2bcfec0d87c52@mail.gmail.com> <20091218174245.113160@gmx.net> <7b501d5c0912180959j4248552xcf30b4deed8d01f5@mail.gmail.com> <20091220133606.160220@gmx.net> <7b501d5c0912200545w6a47d8c7vb4cdcfe2a27c5eb@mail.gmail.com> <20091221095606.63560@gmx.net> Message-ID: <7b501d5c0912210225l17c9ad18jf4570b1bb3b6d69f@mail.gmail.com> 2009/12/21 : > Now everything works but to print Z also for negative Integers. Don't know how to implement the <=0 or le0 in this case again: > > instance Enum Nat where > ? ? ? ?toEnum 0 = Z > ? ? ? ?toEnum (n+1) = S(toEnum n) > ? ? ? ?fromEnum Z = 0 > ? ? ? ?fromEnum (S n) = 1 + fromEnum n > Again, look into guards. You are definitely on the right track. Again, you should look into guards. instance Enum Nat where toEnum n | n <= 0 = Z | otherwise = ... -- do what with n? fromEnum Z = 0 fromEnum (S n) = 1 + fromEnum n You are on the right track. -- Deniz Dogan From daniel.is.fischer at web.de Mon Dec 21 05:26:04 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 21 05:01:19 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <20091221100503.63530@gmx.net> References: <20091218160101.113160@gmx.net> <200912202225.53592.daniel.is.fischer@web.de> <20091221100503.63530@gmx.net> Message-ID: <200912211126.05162.daniel.is.fischer@web.de> Am Montag 21 Dezember 2009 11:05:03 schrieb kane96@gmx.de: > > still have the problem that it says: > "Not in scope: data constructor `Month'" but Month is declared as: > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | > Nov | Dec deriving (Eq,Enum,Show) Sorry, didn't look closely enough. Month is the name of the datatype. You want month to run through all elements of Month, so you need a list, namely [Jan .. Dec] (it might be necessary to include Ord in the derived instances for Month). From daniel.is.fischer at web.de Mon Dec 21 05:28:14 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 21 05:03:29 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091221095606.63560@gmx.net> References: <20091217172121.159700@gmx.net> <7b501d5c0912200545w6a47d8c7vb4cdcfe2a27c5eb@mail.gmail.com> <20091221095606.63560@gmx.net> Message-ID: <200912211128.14871.daniel.is.fischer@web.de> Am Montag 21 Dezember 2009 10:56:06 schrieb kane96@gmx.de: > Now everything works but to print Z also for negative Integers. Don't know > how to implement the <=0 or le0 in this case again: > > instance Enum Nat where > ? ? ? ? toEnum 0 = Z > ? ? ? ? toEnum (n+1) = S(toEnum n) Note that many frown upon (n+k)-patterns and they may be removed from the language in future. Use guards: toEnum n | condition1 = rhs1 | condition2 = rhs2 > ? ? ? ? fromEnum Z = 0 > ? ? ? ? fromEnum (S n) = 1 + fromEnum n From kane96 at gmx.de Mon Dec 21 05:38:14 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 05:11:58 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <200912211126.05162.daniel.is.fischer@web.de> References: <20091218160101.113160@gmx.net> <200912202225.53592.daniel.is.fischer@web.de> <20091221100503.63530@gmx.net> <200912211126.05162.daniel.is.fischer@web.de> Message-ID: <20091221103814.63560@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 11:26:04 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] print all days of calendar > Am Montag 21 Dezember 2009 11:05:03 schrieb kane96@gmx.de: > > > > still have the problem that it says: > > "Not in scope: data constructor `Month'" but Month is declared as: > > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | > > Nov | Dec deriving (Eq,Enum,Show) > > Sorry, didn't look closely enough. > Month is the name of the datatype. You want month to run through all > elements of Month, so > you need a list, namely [Jan .. Dec] (it might be necessary to include Ord > in the derived > instances for Month). ahhh, it works in the right order. I tried [Jan..Dec] (without the spaces) which failed. Which function can I use to trim the calendar of a month from the calendar of the whole year, because I have to implement a function: getMonth :: Month -> Calendar -> Calendar -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From chaddai.fouche at gmail.com Mon Dec 21 05:48:02 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Mon Dec 21 05:21:46 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <200912211128.14871.daniel.is.fischer@web.de> References: <20091217172121.159700@gmx.net> <7b501d5c0912200545w6a47d8c7vb4cdcfe2a27c5eb@mail.gmail.com> <20091221095606.63560@gmx.net> <200912211128.14871.daniel.is.fischer@web.de> Message-ID: On Mon, Dec 21, 2009 at 11:28 AM, Daniel Fischer wrote: > Am Montag 21 Dezember 2009 10:56:06 schrieb kane96@gmx.de: >> Now everything works but to print Z also for negative Integers. Don't know >> how to implement the <=0 or le0 in this case again: >> >> instance Enum Nat where >> ? ? ? ? toEnum 0 = Z >> ? ? ? ? toEnum (n+1) = S(toEnum n) > > Note that many frown upon (n+k)-patterns and they may be removed from the language in > future. In fact they _have_been_ removed from the standard in Haskell 2010, so in ghc 6.14 they'll become an extension instead of working by default. You just have to use n as a pattern and (n-1) instead of n in the body. -- Jeda? From daniel.is.fischer at web.de Mon Dec 21 05:53:02 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 21 05:29:39 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <20091221103814.63560@gmx.net> References: <20091218160101.113160@gmx.net> <200912211126.05162.daniel.is.fischer@web.de> <20091221103814.63560@gmx.net> Message-ID: <200912211153.02227.daniel.is.fischer@web.de> Am Montag 21 Dezember 2009 11:38:14 schrieb kane96@gmx.de: > Which function can I use to trim the calendar of a month from the calendar > of the whole year, because I have to implement a function: getMonth :: > Month -> Calendar -> Calendar look at filter or span and break, takeWhile/dropWhile From kane96 at gmx.de Mon Dec 21 09:02:16 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 08:36:03 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <7b501d5c0912210225l17c9ad18jf4570b1bb3b6d69f@mail.gmail.com> References: <20091217172121.159700@gmx.net> <7b501d5c0912180906l655b34c3safe2bcfec0d87c52@mail.gmail.com> <20091218174245.113160@gmx.net> <7b501d5c0912180959j4248552xcf30b4deed8d01f5@mail.gmail.com> <20091220133606.160220@gmx.net> <7b501d5c0912200545w6a47d8c7vb4cdcfe2a27c5eb@mail.gmail.com> <20091221095606.63560@gmx.net> <7b501d5c0912210225l17c9ad18jf4570b1bb3b6d69f@mail.gmail.com> Message-ID: <20091221140216.63530@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 11:25:46 +0100 > Von: Deniz Dogan > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] Enum for natural numbers > 2009/12/21 : > > Now everything works but to print Z also for negative Integers. Don't > know how to implement the <=0 or le0 in this case again: > > > > instance Enum Nat where > > ? ? ? ?toEnum 0 = Z > > ? ? ? ?toEnum (n+1) = S(toEnum n) > > ? ? ? ?fromEnum Z = 0 > > ? ? ? ?fromEnum (S n) = 1 + fromEnum n > > > > Again, look into guards. You are definitely on the right track. > > Again, you should look into guards. > > instance Enum Nat where > toEnum n | n <= 0 = Z > | otherwise = ... -- do what with n? > fromEnum Z = 0 > fromEnum (S n) = 1 + fromEnum n I did it that way: instance Enum Nat where toEnum n | n <= 0 = Z | otherwise = S(toEnum (n-1)) fromEnum Z = 0 fromEnum (S n) = 1 + fromEnum n In another task I should create an infinite list: allNats :: [Nat] I would have done it in a recursion but there issn't a parameter to call allNats with -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From daniel.is.fischer at web.de Mon Dec 21 09:06:38 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 21 08:43:56 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091221140216.63530@gmx.net> References: <20091217172121.159700@gmx.net> <7b501d5c0912210225l17c9ad18jf4570b1bb3b6d69f@mail.gmail.com> <20091221140216.63530@gmx.net> Message-ID: <200912211506.38437.daniel.is.fischer@web.de> Am Montag 21 Dezember 2009 15:02:16 schrieb kane96@gmx.de: > In another task I should create an infinite list: allNats :: [Nat] > I would have done it in a recursion but there issn't a parameter to call > allNats with Prelude> :t iterate iterate :: (a -> a) -> a -> [a] From kane96 at gmx.de Mon Dec 21 11:04:56 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 10:38:41 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <200912211153.02227.daniel.is.fischer@web.de> References: <20091218160101.113160@gmx.net> <200912211126.05162.daniel.is.fischer@web.de> <20091221103814.63560@gmx.net> <200912211153.02227.daniel.is.fischer@web.de> Message-ID: <20091221160456.63540@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 11:53:02 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] print all days of calendar > Am Montag 21 Dezember 2009 11:38:14 schrieb kane96@gmx.de: > > Which function can I use to trim the calendar of a month from the > calendar > > of the whole year, because I have to implement a function: getMonth :: > > Month -> Calendar -> Calendar > > look at filter or span and break, takeWhile/dropWhile Dont't find any good examples of this functions that can help me. I think it have to be somethink like that, but don't find a way that works: getMonth :: Month -> Calendar -> Calendar getMonth month year = filter ([1..31],month,year) (calendar year) -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From kane96 at gmx.de Mon Dec 21 11:10:19 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 10:44:05 2009 Subject: [Haskell-beginners] inserting tupels inside list as tupels in list In-Reply-To: <20091220135041.160230@gmx.net> References: <20091218180216.113150@gmx.net> <20091218225812.GA19856@seas.upenn.edu> <20091220135041.160230@gmx.net> Message-ID: <20091221161019.63520@gmx.net> issn't there a way to manage this event list easily? -------- Original-Nachricht -------- > Datum: Sun, 20 Dec 2009 14:50:41 +0100 > Von: kane96@gmx.de > An: beginners@haskell.org > Betreff: Re: [Haskell-beginners] inserting tupels inside list as tupels in list > I already have things like that: > > type Day = Int 17 data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | > Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) > type Year = Int > type Date = (Day,Month,Year) > > type ID = Int > type Event = (ID,String) > type Organiser = [ (Date, [Event]) ] > > and now I should implement a function like this: > addEvents :: Date -> [Event] -> Organiser -> Organiser > that adds to an organiser a list of events for a specific date > > an example looks like this: > xmas :: Event > xmas = (2, "Christmas") > aliceOrg :: Organiser > aliceOrg = [ ( (21,Dec,2009), [panic,aliceBDay] ), > ( (25,Dec,2009), [xmas] ) ] > > > -------- Original-Nachricht -------- > > Datum: Fri, 18 Dec 2009 17:58:12 -0500 > > Von: Brent Yorgey > > An: beginners@haskell.org > > Betreff: Re: [Haskell-beginners] inserting tupels inside list as tupels > in list > > > On Fri, Dec 18, 2009 at 07:02:16PM +0100, kane96@gmx.de wrote: > > > maybe the subject is a little bit confusing :p > > > > > > I have a organiser list like that and have to add events (like panic, > > xmas, ...) which is also a type of tupel for a specific date: > > > > > > aliceOrg = [ ( (21,Dec,2009), [panic,aliceBDay] ) > > > ( (25,Dec,2009), [xmas] ) > > > ( (10,Jan,2010), [bobBDay] ) > > > > > > What function(s) can I use to add these nested lists and tupels here? > > > > You can use all the functions for manipulating lists and tuples in the > > standard libraries... I'm not entirely sure what you are asking. > > > > Let me suggest, however, that you probably don't want to be using > > tuples so much; make your own data types. Something like this: > > > > type Day = Int > > data Month = Jan | Feb | ... > > type Year = Int > > > > data Date = Date Day Month Year > > > > data CalEntry = CalEntry Date [Event] > > data Event = ... > > > > type Organizer = [CalEntry] > > > > This is much less confusing since instead of just tuples everywhere > > you have specific types that say exactly what the data represents. > > > > -Brent > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > -- > Preisknaller: GMX DSL Flatrate f?r nur 16,99 Euro/mtl.! > http://portal.gmx.net/de/go/dsl02 > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser From daniel.is.fischer at web.de Mon Dec 21 11:22:18 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 21 10:57:31 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <20091221160456.63540@gmx.net> References: <20091218160101.113160@gmx.net> <200912211153.02227.daniel.is.fischer@web.de> <20091221160456.63540@gmx.net> Message-ID: <200912211722.18885.daniel.is.fischer@web.de> Am Montag 21 Dezember 2009 17:04:56 schrieb kane96@gmx.de: > -------- Original-Nachricht -------- > > > Datum: Mon, 21 Dec 2009 11:53:02 +0100 > > Von: Daniel Fischer > > An: beginners@haskell.org > > CC: kane96@gmx.de > > Betreff: Re: [Haskell-beginners] print all days of calendar > > > > Am Montag 21 Dezember 2009 11:38:14 schrieb kane96@gmx.de: > > > Which function can I use to trim the calendar of a month from the > > > > calendar > > > > > of the whole year, because I have to implement a function: getMonth :: > > > Month -> Calendar -> Calendar > > > > look at filter or span and break, takeWhile/dropWhile > > Dont't find any good examples of this functions that can help me. I think > it have to be somethink like that, but don't find a way that works: > getMonth :: Month -> Calendar -> Calendar > getMonth month year = filter ([1..31],month,year) (calendar year) Prelude> :t filter filter :: (a -> Bool) -> [a] -> [a] So we need a predicate on the type of list elements. getMonth month cal = filter predicate cal where predicate (d,m,y) = ?? From kane96 at gmx.de Mon Dec 21 11:39:49 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 11:13:35 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <200912211722.18885.daniel.is.fischer@web.de> References: <20091218160101.113160@gmx.net> <200912211153.02227.daniel.is.fischer@web.de> <20091221160456.63540@gmx.net> <200912211722.18885.daniel.is.fischer@web.de> Message-ID: <20091221163949.63520@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 17:22:18 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] print all days of calendar > Am Montag 21 Dezember 2009 17:04:56 schrieb kane96@gmx.de: > > -------- Original-Nachricht -------- > > > > > Datum: Mon, 21 Dec 2009 11:53:02 +0100 > > > Von: Daniel Fischer > > > An: beginners@haskell.org > > > CC: kane96@gmx.de > > > Betreff: Re: [Haskell-beginners] print all days of calendar > > > > > > Am Montag 21 Dezember 2009 11:38:14 schrieb kane96@gmx.de: > > > > Which function can I use to trim the calendar of a month from the > > > > > > calendar > > > > > > > of the whole year, because I have to implement a function: getMonth > :: > > > > Month -> Calendar -> Calendar > > > > > > look at filter or span and break, takeWhile/dropWhile > > > > Dont't find any good examples of this functions that can help me. I > think > > it have to be somethink like that, but don't find a way that works: > > getMonth :: Month -> Calendar -> Calendar > > getMonth month year = filter ([1..31],month,year) (calendar year) > > Prelude> :t filter > filter :: (a -> Bool) -> [a] -> [a] > > So we need a predicate on the type of list elements. > > getMonth month cal = filter predicate cal > where > predicate (d,m,y) = ?? it has to match the given month and year. But don't know how to define it. -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From kane96 at gmx.de Mon Dec 21 12:27:03 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 12:00:49 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <200912211506.38437.daniel.is.fischer@web.de> References: <20091217172121.159700@gmx.net> <7b501d5c0912210225l17c9ad18jf4570b1bb3b6d69f@mail.gmail.com> <20091221140216.63530@gmx.net> <200912211506.38437.daniel.is.fischer@web.de> Message-ID: <20091221172703.63540@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 15:06:38 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] Enum for natural numbers > Am Montag 21 Dezember 2009 15:02:16 schrieb kane96@gmx.de: > > In another task I should create an infinite list: allNats :: [Nat] > > I would have done it in a recursion but there issn't a parameter to call > > allNats with > > Prelude> :t iterate > iterate :: (a -> a) -> a -> [a] this works: allNats = (iterate (1+) 1) but it doesn't match my declaration: allNats :: [Nat] -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From verdier.jean at gmail.com Mon Dec 21 13:40:23 2009 From: verdier.jean at gmail.com (jean verdier) Date: Mon Dec 21 13:14:05 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091221172703.63540@gmx.net> References: <20091217172121.159700@gmx.net> <7b501d5c0912210225l17c9ad18jf4570b1bb3b6d69f@mail.gmail.com> <20091221140216.63530@gmx.net> <200912211506.38437.daniel.is.fischer@web.de> <20091221172703.63540@gmx.net> Message-ID: <1261420823.2293.2.camel@localhost.localdomain> your type is data Nat = S Nat | Z and not data Nat = 1 + Nat | 0 On Mon, 2009-12-21 at 18:27 +0100, kane96@gmx.de wrote: > -------- Original-Nachricht -------- > > Datum: Mon, 21 Dec 2009 15:06:38 +0100 > > Von: Daniel Fischer > > An: beginners@haskell.org > > CC: kane96@gmx.de > > Betreff: Re: [Haskell-beginners] Enum for natural numbers > > > Am Montag 21 Dezember 2009 15:02:16 schrieb kane96@gmx.de: > > > In another task I should create an infinite list: allNats :: [Nat] > > > I would have done it in a recursion but there issn't a parameter to call > > > allNats with > > > > Prelude> :t iterate > > iterate :: (a -> a) -> a -> [a] > > this works: > allNats = (iterate (1+) 1) > but it doesn't match my declaration: > allNats :: [Nat] > > From daniel.is.fischer at web.de Mon Dec 21 13:54:09 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 21 13:29:24 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <20091221163949.63520@gmx.net> References: <20091218160101.113160@gmx.net> <200912211722.18885.daniel.is.fischer@web.de> <20091221163949.63520@gmx.net> Message-ID: <200912211954.09758.daniel.is.fischer@web.de> Am Montag 21 Dezember 2009 17:39:49 schrieb kane96@gmx.de: > > Prelude> :t filter > > filter :: (a -> Bool) -> [a] -> [a] > > > > So we need a predicate on the type of list elements. > > > > getMonth month cal = filter predicate cal > > ? ? ? where > > ? ? ? ? predicate (d,m,y) = ?? > > it has to match the given month and year. But don't know how to define it. Does (==) ring a few bells? From kane96 at gmx.de Mon Dec 21 14:47:38 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 14:21:29 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <200912211954.09758.daniel.is.fischer@web.de> References: <20091218160101.113160@gmx.net> <200912211722.18885.daniel.is.fischer@web.de> <20091221163949.63520@gmx.net> <200912211954.09758.daniel.is.fischer@web.de> Message-ID: <20091221194738.63560@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 19:54:09 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] print all days of calendar > Am Montag 21 Dezember 2009 17:39:49 schrieb kane96@gmx.de: > > > Prelude> :t filter > > > filter :: (a -> Bool) -> [a] -> [a] > > > > > > So we need a predicate on the type of list elements. > > > > > > getMonth month cal = filter predicate cal > > > ? ? ? where > > > ? ? ? ? predicate (d,m,y) = ?? > > > > it has to match the given month and year. But don't know how to define > it. > > Does (==) ring a few bells? not really... -- Preisknaller: GMX DSL Flatrate f?r nur 16,99 Euro/mtl.! http://portal.gmx.net/de/go/dsl02 From kane96 at gmx.de Mon Dec 21 15:02:06 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 14:36:02 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <1261420823.2293.2.camel@localhost.localdomain> References: <20091217172121.159700@gmx.net> <7b501d5c0912210225l17c9ad18jf4570b1bb3b6d69f@mail.gmail.com> <20091221140216.63530@gmx.net> <200912211506.38437.daniel.is.fischer@web.de> <20091221172703.63540@gmx.net> <1261420823.2293.2.camel@localhost.localdomain> Message-ID: <20091221200206.63520@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 19:40:23 +0100 > Von: jean verdier > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] Enum for natural numbers > your type is > data Nat = S Nat | Z > and not > data Nat = 1 + Nat | 0 Do I have to use something like fromEnum (S Z)? Or or the iteration wrong? > > On Mon, 2009-12-21 at 18:27 +0100, kane96@gmx.de wrote: > > -------- Original-Nachricht -------- > > > Datum: Mon, 21 Dec 2009 15:06:38 +0100 > > > Von: Daniel Fischer > > > An: beginners@haskell.org > > > CC: kane96@gmx.de > > > Betreff: Re: [Haskell-beginners] Enum for natural numbers > > > > > Am Montag 21 Dezember 2009 15:02:16 schrieb kane96@gmx.de: > > > > In another task I should create an infinite list: allNats :: [Nat] > > > > I would have done it in a recursion but there issn't a parameter to > call > > > > allNats with > > > > > > Prelude> :t iterate > > > iterate :: (a -> a) -> a -> [a] > > > > this works: > > allNats = (iterate (1+) 1) > > but it doesn't match my declaration: > > allNats :: [Nat] > > > > -- Preisknaller: GMX DSL Flatrate f?r nur 16,99 Euro/mtl.! http://portal.gmx.net/de/go/dsl02 From daniel.is.fischer at web.de Mon Dec 21 15:12:48 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 21 14:48:01 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <20091221194738.63560@gmx.net> References: <20091218160101.113160@gmx.net> <200912211954.09758.daniel.is.fischer@web.de> <20091221194738.63560@gmx.net> Message-ID: <200912212112.48767.daniel.is.fischer@web.de> Am Montag 21 Dezember 2009 20:47:38 schrieb kane96@gmx.de: > > > > Does (==) ring a few bells? > > not really... Prelude> let okay k = k^3 `mod` 13 == 5 in filter okay [1 .. 30] [7,8,11,20,21,24] Now, you don't want the numbers between 1 and 30 inclusive whose cube modulo 13 is 5, but the dates in a given month. getMonth :: Month -> Calendar -> Calendar getMonth month [(1,Jan,y),(2,Jan,y) ... (31,Dec,y)] From kane96 at gmx.de Mon Dec 21 15:39:38 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 15:13:25 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <200912212112.48767.daniel.is.fischer@web.de> References: <20091218160101.113160@gmx.net> <200912211954.09758.daniel.is.fischer@web.de> <20091221194738.63560@gmx.net> <200912212112.48767.daniel.is.fischer@web.de> Message-ID: <20091221203938.63550@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 21:12:48 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] print all days of calendar > Am Montag 21 Dezember 2009 20:47:38 schrieb kane96@gmx.de: > > > > > > Does (==) ring a few bells? > > > > not really... > > Prelude> let okay k = k^3 `mod` 13 == 5 in filter okay [1 .. 30] > [7,8,11,20,21,24] > > Now, you don't want the numbers between 1 and 30 inclusive whose cube > modulo 13 is 5, but > the dates in a given month. > > getMonth :: Month -> Calendar -> Calendar > getMonth month [(1,Jan,y),(2,Jan,y) ... (31,Dec,y)] more like this: getMonth month calendar = calendar filter ([1..31], month, year) but it doesn't make sense -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From daniel.is.fischer at web.de Mon Dec 21 16:00:58 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 21 15:36:11 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <20091221203938.63550@gmx.net> References: <20091218160101.113160@gmx.net> <200912212112.48767.daniel.is.fischer@web.de> <20091221203938.63550@gmx.net> Message-ID: <200912212200.58779.daniel.is.fischer@web.de> Am Montag 21 Dezember 2009 21:39:38 schrieb kane96@gmx.de: > -------- Original-Nachricht -------- > > > Datum: Mon, 21 Dec 2009 21:12:48 +0100 > > Von: Daniel Fischer > > An: beginners@haskell.org > > CC: kane96@gmx.de > > Betreff: Re: [Haskell-beginners] print all days of calendar > > > > Am Montag 21 Dezember 2009 20:47:38 schrieb kane96@gmx.de: > > > > Does (==) ring a few bells? > > > > > > not really... > > > > Prelude> let okay k = k^3 `mod` 13 == 5 in filter okay [1 .. 30] > > [7,8,11,20,21,24] > > > > Now, you don't want the numbers between 1 and 30 inclusive whose cube > > modulo 13 is 5, but > > the dates in a given month. > > > > getMonth :: Month -> Calendar -> Calendar > > getMonth month [(1,Jan,y),(2,Jan,y) ... (31,Dec,y)] > > more like this: > getMonth month calendar = calendar filter ([1..31], month, year) > but it doesn't make sense No. type Calendar = [Date] type Day = Int data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) type Year = Int type Date = (Day,Month,Year) So the calendar in "getMonth month calendar" is a list of date-triples as illustrated above. Prelude> :t filter filter :: (a -> Bool) -> [a] -> [a] So filter takes 1) a predicate (a function of type (a -> Bool)) 2) a list as arguments. getMonth :: Month -> [Date] -> [Date] One of the arguments to getMonth is a list, and the result should be a list of the same type, thus it's natural to pass that list unchanged to filter. getMonth month calendar = filter predicateThatYouNeed calendar What remains is to define predicateThatYouNeed. It will somehow involve the other argument to getMonth, namely month. And it must map (Day,Month,Year) triples to Bool. From daniel.is.fischer at web.de Mon Dec 21 16:06:46 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 21 15:41:59 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <20091221200206.63520@gmx.net> References: <20091217172121.159700@gmx.net> <1261420823.2293.2.camel@localhost.localdomain> <20091221200206.63520@gmx.net> Message-ID: <200912212206.47154.daniel.is.fischer@web.de> Am Montag 21 Dezember 2009 21:02:06 schrieb kane96@gmx.de: > > your type is > > data Nat = S Nat | Z > > and not > > data Nat = 1 + Nat | 0 > > Do I have to use something like fromEnum (S Z)? Or or the iteration wrong? Which operation on Nat corresponds to (1 +) on Int[eger] ? From kane96 at gmx.de Mon Dec 21 16:40:54 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 16:15:01 2009 Subject: [Haskell-beginners] Enum for natural numbers In-Reply-To: <200912212206.47154.daniel.is.fischer@web.de> References: <20091217172121.159700@gmx.net> <1261420823.2293.2.camel@localhost.localdomain> <20091221200206.63520@gmx.net> <200912212206.47154.daniel.is.fischer@web.de> Message-ID: <20091221214054.63520@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 22:06:46 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de, jean verdier > Betreff: Re: [Haskell-beginners] Enum for natural numbers > Am Montag 21 Dezember 2009 21:02:06 schrieb kane96@gmx.de: > > > your type is > > > data Nat = S Nat | Z > > > and not > > > data Nat = 1 + Nat | 0 > > > > Do I have to use something like fromEnum (S Z)? Or or the iteration > wrong? > > Which operation on Nat corresponds to (1 +) on Int[eger] ? I implemented it: allNats :: [Nat] allNats = iterate S Z -- Preisknaller: GMX DSL Flatrate f?r nur 16,99 Euro/mtl.! http://portal.gmx.net/de/go/dsl02 From kane96 at gmx.de Mon Dec 21 17:02:04 2009 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Dec 21 16:35:50 2009 Subject: [Haskell-beginners] print all days of calendar In-Reply-To: <200912212200.58779.daniel.is.fischer@web.de> References: <20091218160101.113160@gmx.net> <200912212112.48767.daniel.is.fischer@web.de> <20091221203938.63550@gmx.net> <200912212200.58779.daniel.is.fischer@web.de> Message-ID: <20091221220204.63560@gmx.net> -------- Original-Nachricht -------- > Datum: Mon, 21 Dec 2009 22:00:58 +0100 > Von: Daniel Fischer > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] print all days of calendar > Am Montag 21 Dezember 2009 21:39:38 schrieb kane96@gmx.de: > > -------- Original-Nachricht -------- > > > > > Datum: Mon, 21 Dec 2009 21:12:48 +0100 > > > Von: Daniel Fischer > > > An: beginners@haskell.org > > > CC: kane96@gmx.de > > > Betreff: Re: [Haskell-beginners] print all days of calendar > > > > > > Am Montag 21 Dezember 2009 20:47:38 schrieb kane96@gmx.de: > > > > > Does (==) ring a few bells? > > > > > > > > not really... > > > > > > Prelude> let okay k = k^3 `mod` 13 == 5 in filter okay [1 .. 30] > > > [7,8,11,20,21,24] > > > > > > Now, you don't want the numbers between 1 and 30 inclusive whose cube > > > modulo 13 is 5, but > > > the dates in a given month. > > > > > > getMonth :: Month -> Calendar -> Calendar > > > getMonth month [(1,Jan,y),(2,Jan,y) ... (31,Dec,y)] > > > > more like this: > > getMonth month calendar = calendar filter ([1..31], month, year) > > but it doesn't make sense > > No. > type Calendar = [Date] > type Day = Int > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | > Nov | Dec > deriving (Eq,Enum,Show) > type Year = Int > type Date = (Day,Month,Year) > > So the calendar in "getMonth month calendar" is a list of date-triples as > illustrated > above. > > Prelude> :t filter > filter :: (a -> Bool) -> [a] -> [a] > > So filter takes > 1) a predicate (a function of type (a -> Bool)) > 2) a list > as arguments. > > getMonth :: Month -> [Date] -> [Date] > > One of the arguments to getMonth is a list, and the result should be a > list of the same > type, thus it's natural to pass that list unchanged to filter. > > getMonth month calendar = filter predicateThatYouNeed calendar > > What remains is to define predicateThatYouNeed. It will somehow involve > the other argument > to getMonth, namely month. And it must map (Day,Month,Year) triples to > Bool. so I have to say that it have to match (Day, month, Year), but how... -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From chaddai.fouche at gmail.com Tue Dec 22 04:31:22 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Tue Dec 22 04:05:06 2009 Subject: [Haskell-beginners] inserting tupels inside list as tupels in list In-Reply-To: <20091221161019.63520@gmx.net> References: <20091218180216.113150@gmx.net> <20091218225812.GA19856@seas.upenn.edu> <20091220135041.160230@gmx.net> <20091221161019.63520@gmx.net> Message-ID: On Mon, Dec 21, 2009 at 5:10 PM, wrote: > issn't there a way to manage this event list easily? Sure there is, on the other hand you already had a lot of help on this mainling list, maybe you could try to finish this by yourself ? Some pointers though : - first I would like to point that while Day/Month/Year is the convention in some countries, (Year,Month,Day) makes a lot more sense from an informatic point of view given that the lexicographic order on that corresponds to the date order (add Ord to the derivation for your Month type) - second, a list may not be the most appropriate for associating date and event, a Map (from Data.Map) may be better. -- Jeda? From john.moore54 at gmail.com Tue Dec 22 15:48:11 2009 From: john.moore54 at gmail.com (John Moore) Date: Tue Dec 22 15:21:51 2009 Subject: [Haskell-beginners] expression parser Message-ID: <4f7ad1ad0912221248x29874dfdpba0283bbde8858e3@mail.gmail.com> Hi, Could some one point out what I'm doing wrong below. This is a parser which takes an arithmetic expression built up from single digits. Turns 3*4+2 into (3*4)+2 etc.It giving me the last expression in a do statement or parse error on -> (+++) :: Parser a -> Parser a -> Parser a expr :: term( '+' expr |"") term -> factor('*' term |"") expr :: Parser Int expr = do t <- term do char '+' e <- expr return (t + e) +++ return t term :: Parser Int term = do f <- factor do char '*' t <- term return (f * t) +++ return f factor :: Parser Int factor = do d <- digit return (digitToInt d) +++ do char '(' e <- expr char ')' return e eval :: String -> Int eval xs = fst(head(parse expr xs)) John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091222/14484e65/attachment.html From daniel.is.fischer at web.de Tue Dec 22 16:10:22 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Dec 22 15:45:31 2009 Subject: [Haskell-beginners] expression parser In-Reply-To: <4f7ad1ad0912221248x29874dfdpba0283bbde8858e3@mail.gmail.com> References: <4f7ad1ad0912221248x29874dfdpba0283bbde8858e3@mail.gmail.com> Message-ID: <200912222210.22428.daniel.is.fischer@web.de> Am Dienstag 22 Dezember 2009 21:48:11 schrieb John Moore: > Hi, > Could some one point out what I'm doing wrong below. This is a parser > which takes an arithmetic expression built up from single digits. Turns > 3*4+2 into (3*4)+2 etc.It giving me the last expression in a do statement > or parse error on -> > > (+++) :: Parser a -> Parser a -> Parser a > expr :: term( '+' expr |"") > term -> factor('*' term |"") What's happened here? A part of your grammar seems to have slipped into the code. > > expr :: Parser Int > expr = do t <- term > do char '+' > e <- expr > return (t + e) > +++ return t > > term :: Parser Int > term = do f <- factor > do char '*' > t <- term > return (f * t) > +++ return f > > factor :: Parser Int > factor = do d <- digit > return (digitToInt d) > +++ do char '(' > e <- expr > char ')' > return e > > eval :: String -> Int > eval xs = fst(head(parse expr xs)) Maybe it's just the mail programme, but what arrived here had wrong indentation. In expr, the inner do-block isn't aligned with "t <- term". In term, the "return (f * t)" isn't aligned with "char '*'" and "t <- term" and the whole inner dop-block isn't aligned with "f <- factor". In factor, "return (digitToInt d)" isn't aligned with "d <- digit" and in the second block, "char ')'" and "return e" aren't aligned with "char'('" and "e <- expr". Properly aligned and with an implementation of (+++) instead of grammar productions, it should work. > > > John From yazicivo at ttmail.com Wed Dec 23 08:02:12 2009 From: yazicivo at ttmail.com (Volkan YAZICI) Date: Wed Dec 23 07:35:54 2009 Subject: [Haskell-beginners] Re: Pure Regex.PCRE Possible? (PLEAC, Fix Style) In-Reply-To: (=?utf-8?Q?=22Chadda=C3=AF_Fouch=C3=A9=22's?= message of "Sun\, 20 Dec 2009 10\:16\:59 +0100") References: <87fx77axue.fsf@alamut.alborz.net> Message-ID: <87zl59j12j.fsf_-_@alamut.alborz.net> On Sun, 20 Dec 2009, Chadda? Fouch? writes: > On Sat, Dec 19, 2009 at 2:37 PM, Volkan YAZICI wrote: >> However, if I'm not mistaken, above functions _should_ be absolutely >> pure. Is it possible to encapsulate impure PCRE functions into their >> pure equivalents? >> >> BTW, why are PCRE functions impure? > > Mainly because they _are_ the core that _is_ encapsulated as you > suggested : regex-pcre as many other regex library, provides the same > basic mostly pure interface which is in regex-base. > > That interface comes with many specific pure function (matchText, > matchOnce, matchAll and so on, as well as makeRegex and others) and > some "magic" operators like =~ which decides what kind of matching you > want to do depending on the type of the result. > > See this tutorial for some example of usage : > http://www.serpentine.com/blog/2007/02/27/a-haskell-regular-expression-tutorial/ Am I missing something, or Text.Regex.Posix no more ships with Haskell, particularly 6.12.1 version? Regards. From chaddai.fouche at gmail.com Wed Dec 23 08:18:00 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Wed Dec 23 07:51:38 2009 Subject: [Haskell-beginners] Re: Pure Regex.PCRE Possible? (PLEAC, Fix Style) In-Reply-To: <87zl59j12j.fsf_-_@alamut.alborz.net> References: <87fx77axue.fsf@alamut.alborz.net> <87zl59j12j.fsf_-_@alamut.alborz.net> Message-ID: On Wed, Dec 23, 2009 at 2:02 PM, Volkan YAZICI wrote: >> See this tutorial for some example of usage : >> http://www.serpentine.com/blog/2007/02/27/a-haskell-regular-expression-tutorial/ > > Am I missing something, or Text.Regex.Posix no more ships with Haskell, > particularly 6.12.1 version? You didn't miss anything (I think it was even true with 6.10), that is because the GHC developers have decided to get out of the library business. In other words they decided to restrain themselves to the absolute core of the Haskell libraries necessary to get GHC running and nothing else. So, what should an Haskell developer do, when he don't absolutely need the _latest_ GHC release, the _latest_ libraries in all domain, and so on ? The Haskell Platform is the project that is supposed to replace the old big GHC release from the past, with regular releases of an integrated package with a stable and useful library set and a compiler version that are supposed to work nicely together : http://hackage.haskell.org/platform/ _This_ is what most Haskell developer should use, especially if they're beginners ! It contains regex-posix and regex-base (which is the common interface of most regex-* package, regex-pcre included). -- Jeda? From patrick.leboutillier at gmail.com Wed Dec 23 14:46:51 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Wed Dec 23 14:20:29 2009 Subject: [Haskell-beginners] Einstein's Problem Message-ID: Hi all, I've been working hard at trying to solve Einstein's problem (http://www.davar.net/MATH/PROBLEMS/EINSTEIN.HTM) if an efficient manner using Haskell. I have posted my solution here: http://haskell.pastebin.com/m3ff1973a This exercise has been a real eye opener for me, especially for learning to work with the Maybe and List monads. I'm looking for suggestions for making the "test" function nicer. In order to make my solution fast, I generate my test cases incrementally, thereby elimating most of the cases early on. However the function looks funny (deeply nested). I'm also open to any comments about making better use of the different Haskell idioms. Thanks a lot, Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From jon at ffconsultancy.com Wed Dec 23 16:14:24 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed Dec 23 14:33:55 2009 Subject: [Haskell-beginners] Performance of parallel mergesort Message-ID: <200912232114.24493.jon@ffconsultancy.com> I took the parallel merge sort described here: http://martin.sulzmann.googlepages.com/AMP-Spring2008-intro.pdf and added a simple test: main :: IO () main = do putStrLn $ show $ sum $ mergesort $ [sin x | x <- [1.0 .. 1000000.0]] Compiled it with GHC 6.8.2 from Debian testing and ran it with various +RTS -N arguments to measure its performance and obtained the following results on an 8 core: $ ghc --make -O2 -threaded mergesort.hs -o mergesort [1 of 1] Compiling Main ( mergesort.hs, mergesort.o ) Linking mergesort ... $ time ./mergesort +RTS -N1 -0.117109518058233 real 0m9.723s user 0m9.461s sys 0m0.232s $ time ./mergesort +RTS -N2 -0.117109518058233 real 0m13.574s user 0m15.225s sys 0m0.140s $ time ./mergesort +RTS -N3 -0.117109518058233 real 0m13.185s user 0m15.529s sys 0m0.184s $ time ./mergesort +RTS -N4 -0.117109518058233 real 0m13.251s user 0m15.829s sys 0m0.336s $ time ./mergesort +RTS -N5 -0.117109518058233 real 0m13.093s user 0m16.929s sys 0m0.164s $ time ./mergesort +RTS -N6 Segmentation fault real 0m5.711s user 0m7.408s sys 0m0.136s That segfault must be due to a bug in GHC so I thought perhaps a newer version of GHC might fix the segfault but I installed GHC 6.10.4 from Sid and now I get: $ ghc --make -O2 -threaded mergesort.hs -o mergesort Binary: Int64 truncated to fit in 32 bit Int ghc: panic! (the 'impossible' happened) (GHC version 6.10.4 for i386-unknown-linux): Prelude.chr: bad argument Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug I'll try the haskell-platform package next. Are these known problems? -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From aslatter at gmail.com Wed Dec 23 19:16:19 2009 From: aslatter at gmail.com (Antoine Latter) Date: Wed Dec 23 18:49:57 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <200912232114.24493.jon@ffconsultancy.com> References: <200912232114.24493.jon@ffconsultancy.com> Message-ID: <694519c50912231616n527d7e38hc8a7dd3efef62b4b@mail.gmail.com> Hi Jon, You're more likely to get a useful response over on the glasgow-haskell-users mailing list, as it looks like this is a GHC specific bug: http://www.haskell.org/mailman/listinfo/glasgow-haskell-users Running this at -N6 doesn't want to complete for me, so I'm not sure if it would segfault. I'm on a 64-bit Intel Mac OS X using GHC 6.12, dual core. With such a small example as this your best bet would be to file a bug report: http://hackage.haskell.org/trac/ghc/ You'll need to use the login guest/guest to file a new ticket. Antoine On Wed, Dec 23, 2009 at 9:14 PM, Jon Harrop wrote: > > I took the parallel merge sort described here: > > ?http://martin.sulzmann.googlepages.com/AMP-Spring2008-intro.pdf > > and added a simple test: > > main :: IO () > main = do > ? ?putStrLn $ show $ sum $ mergesort $ [sin x | x <- [1.0 .. 1000000.0]] > > Compiled it with GHC 6.8.2 from Debian testing and ran it with various > +RTS -N arguments to measure its performance and obtained the following > results on an 8 core: > > $ ghc --make -O2 -threaded mergesort.hs -o mergesort > [1 of 1] Compiling Main ? ? ? ? ? ? ( mergesort.hs, mergesort.o ) > Linking mergesort ... > $ time ./mergesort +RTS -N1 > -0.117109518058233 > > real ? ?0m9.723s > user ? ?0m9.461s > sys ? ? 0m0.232s > $ time ./mergesort +RTS -N2 > -0.117109518058233 > > real ? ?0m13.574s > user ? ?0m15.225s > sys ? ? 0m0.140s > $ time ./mergesort +RTS -N3 > -0.117109518058233 > > real ? ?0m13.185s > user ? ?0m15.529s > sys ? ? 0m0.184s > $ time ./mergesort +RTS -N4 > -0.117109518058233 > > real ? ?0m13.251s > user ? ?0m15.829s > sys ? ? 0m0.336s > $ time ./mergesort +RTS -N5 > -0.117109518058233 > > real ? ?0m13.093s > user ? ?0m16.929s > sys ? ? 0m0.164s > $ time ./mergesort +RTS -N6 > Segmentation fault > > real ? ?0m5.711s > user ? ?0m7.408s > sys ? ? 0m0.136s > > That segfault must be due to a bug in GHC so I thought perhaps a newer version > of GHC might fix the segfault but I installed GHC 6.10.4 from Sid and now I > get: > > $ ghc --make -O2 -threaded mergesort.hs -o mergesort > Binary: Int64 truncated to fit in 32 bit Int > ghc: panic! (the 'impossible' happened) > ?(GHC version 6.10.4 for i386-unknown-linux): > ? ? ? ?Prelude.chr: bad argument > > Please report this as a GHC bug: ?http://www.haskell.org/ghc/reportabug > > I'll try the haskell-platform package next. Are these known problems? > > -- > Dr Jon Harrop, Flying Frog Consultancy Ltd. > http://www.ffconsultancy.com/?e > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From aslatter at gmail.com Wed Dec 23 19:22:00 2009 From: aslatter at gmail.com (Antoine Latter) Date: Wed Dec 23 18:55:37 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <694519c50912231616n527d7e38hc8a7dd3efef62b4b@mail.gmail.com> References: <200912232114.24493.jon@ffconsultancy.com> <694519c50912231616n527d7e38hc8a7dd3efef62b4b@mail.gmail.com> Message-ID: <694519c50912231622i370abc4ofc25e0adb275f4a1@mail.gmail.com> On Thu, Dec 24, 2009 at 12:16 AM, Antoine Latter wrote: > Hi Jon, > > You're more likely to get a useful response over on the > glasgow-haskell-users mailing list, as it looks like this is a GHC > specific bug: http://www.haskell.org/mailman/listinfo/glasgow-haskell-users > > Running this at -N6 doesn't want to complete for me, so I'm not sure > if it would segfault. I'm on a 64-bit Intel Mac OS X using GHC 6.12, > dual core. > > With such a small example as this your best bet would be to file a bug report: > > http://hackage.haskell.org/trac/ghc/ > > You'll need to use the login guest/guest to file a new ticket. > > Antoine > Here's a paste-bin link for the code in question: http://hpaste.org/fastcgi/hpaste.fcgi/view?id=14871#a14871 > On Wed, Dec 23, 2009 at 9:14 PM, Jon Harrop wrote: >> >> I took the parallel merge sort described here: >> >> ?http://martin.sulzmann.googlepages.com/AMP-Spring2008-intro.pdf >> >> and added a simple test: >> >> main :: IO () >> main = do >> ? ?putStrLn $ show $ sum $ mergesort $ [sin x | x <- [1.0 .. 1000000.0]] >> >> Compiled it with GHC 6.8.2 from Debian testing and ran it with various >> +RTS -N arguments to measure its performance and obtained the following >> results on an 8 core: >> >> $ ghc --make -O2 -threaded mergesort.hs -o mergesort >> [1 of 1] Compiling Main ? ? ? ? ? ? ( mergesort.hs, mergesort.o ) >> Linking mergesort ... >> $ time ./mergesort +RTS -N1 >> -0.117109518058233 >> >> real ? ?0m9.723s >> user ? ?0m9.461s >> sys ? ? 0m0.232s >> $ time ./mergesort +RTS -N2 >> -0.117109518058233 >> >> real ? ?0m13.574s >> user ? ?0m15.225s >> sys ? ? 0m0.140s >> $ time ./mergesort +RTS -N3 >> -0.117109518058233 >> >> real ? ?0m13.185s >> user ? ?0m15.529s >> sys ? ? 0m0.184s >> $ time ./mergesort +RTS -N4 >> -0.117109518058233 >> >> real ? ?0m13.251s >> user ? ?0m15.829s >> sys ? ? 0m0.336s >> $ time ./mergesort +RTS -N5 >> -0.117109518058233 >> >> real ? ?0m13.093s >> user ? ?0m16.929s >> sys ? ? 0m0.164s >> $ time ./mergesort +RTS -N6 >> Segmentation fault >> >> real ? ?0m5.711s >> user ? ?0m7.408s >> sys ? ? 0m0.136s >> >> That segfault must be due to a bug in GHC so I thought perhaps a newer version >> of GHC might fix the segfault but I installed GHC 6.10.4 from Sid and now I >> get: >> >> $ ghc --make -O2 -threaded mergesort.hs -o mergesort >> Binary: Int64 truncated to fit in 32 bit Int >> ghc: panic! (the 'impossible' happened) >> ?(GHC version 6.10.4 for i386-unknown-linux): >> ? ? ? ?Prelude.chr: bad argument >> >> Please report this as a GHC bug: ?http://www.haskell.org/ghc/reportabug >> >> I'll try the haskell-platform package next. Are these known problems? >> >> -- >> Dr Jon Harrop, Flying Frog Consultancy Ltd. >> http://www.ffconsultancy.com/?e >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > From aslatter at gmail.com Wed Dec 23 19:23:06 2009 From: aslatter at gmail.com (Antoine Latter) Date: Wed Dec 23 18:56:42 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <694519c50912231622i370abc4ofc25e0adb275f4a1@mail.gmail.com> References: <200912232114.24493.jon@ffconsultancy.com> <694519c50912231616n527d7e38hc8a7dd3efef62b4b@mail.gmail.com> <694519c50912231622i370abc4ofc25e0adb275f4a1@mail.gmail.com> Message-ID: <694519c50912231623q3b233e64te9fc4bab1ce867a7@mail.gmail.com> On Thu, Dec 24, 2009 at 12:22 AM, Antoine Latter wrote: > On Thu, Dec 24, 2009 at 12:16 AM, Antoine Latter wrote: >> Hi Jon, >> >> You're more likely to get a useful response over on the >> glasgow-haskell-users mailing list, as it looks like this is a GHC >> specific bug: http://www.haskell.org/mailman/listinfo/glasgow-haskell-users >> >> Running this at -N6 doesn't want to complete for me, so I'm not sure >> if it would segfault. I'm on a 64-bit Intel Mac OS X using GHC 6.12, >> dual core. >> >> With such a small example as this your best bet would be to file a bug report: >> >> http://hackage.haskell.org/trac/ghc/ >> >> You'll need to use the login guest/guest to file a new ticket. >> >> Antoine >> > > Here's a paste-bin link for the code in question: > http://hpaste.org/fastcgi/hpaste.fcgi/view?id=14871#a14871 > -N6 finally completed. I'm using GHC 6.12 on Inter, dual-core mac-book. I'm not sure how comparable my setup is to what you tried. Antoine From daniel.is.fischer at web.de Wed Dec 23 19:34:52 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Dec 23 19:10:00 2009 Subject: [Haskell-beginners] Einstein's Problem In-Reply-To: References: Message-ID: <200912240134.52738.daniel.is.fischer@web.de> Am Mittwoch 23 Dezember 2009 20:46:51 schrieb Patrick LeBoutillier: > Hi all, > > I've been working hard at trying to solve Einstein's problem > (http://www.davar.net/MATH/PROBLEMS/EINSTEIN.HTM) if an efficient > manner using Haskell. > > I have posted my solution here: http://haskell.pastebin.com/m3ff1973a > > This exercise has been a real eye opener for me, especially for > learning to work with the Maybe and List monads. > > I'm looking for suggestions for making the "test" function nicer. In > order to make my solution fast, I generate my test cases > incrementally, > thereby elimating most of the cases early on. However the function > looks funny (deeply nested). Instead of if checkStreet s then ... else [], use Control.Monad.guard: test = do ds <- drinkPerms ns <- nationPerms let s = Street $ makeHouses ds ns [] [] [] guard (checkStreet s) ss <- smokePerms ... > > I'm also open to any comments about making better use of the different > Haskell idioms. There is a function permutations in Data.List, you can use that instead of writing your own (except if you want the permutations in a different order). xxxPerms = permutationsOf [toEnum 0 .. toEnum 4] :: [[XXX]] isn't particularly nice, better give the first and last constructor of each type or define allPerms :: (Enum a, Bounded a) => [[a]] allPerms = permutationsOf [minBound .. maxBound] and derive also Bounded for your types. nationPerms = filter rule1 $ permutationsOf [toEnum 0 .. toEnum 4] :: [[Nation]] where rule1 ns = (ns !! 0) == Norway is very inefficient, make that nationPerms = map (Norway:) $ permutationsOf [England .. Denmark] (yes, it's not so terrible for only five items, still it made me wince). Similar for drinkPerms. checkCond (f,c) h = fmap (== c) (f h) ~> checkCond (f,c) = fmap (== c) . f > > > Thanks a lot, > > Patrick From jon at ffconsultancy.com Wed Dec 23 21:24:19 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed Dec 23 19:43:46 2009 Subject: [Haskell-beginners] Performance of parallel mergesort Message-ID: <200912240224.19621.jon@ffconsultancy.com> For some reason all traffic from this beginners list stopped reaching me after the 13th of December. Thanks for the response, Antoine. I've tried to install more recent versions of GHC (6.10 and 6.12) but I cannot get either of them to work at all. GHC 6.8 generates code that segfaults and the GHC 6.10 from Debian testing cannot compile anything for me. So I thought I'd try GHC 6.12. That isn't in any repo so I decided to build it from source. I uninstalled all other GHCs to give it a fresh start. The GHC page says "Stop, install the Haskell Platform" but the Haskell Platform says you must install GHC first, so I've got a nice circular dependency right from the start! So I tried installing GHC 6.12 from source but that requires GHC to be installed. So I installed GHC 6.8 (the one that segfaults) using apt again from Debian. That seems to have built a GHC 6.12 that I can run from the command line but it cannot compile that program because it doesn't have parallel stuff. So I thought I'd install the Haskell Platform. Unfortunately, the Haskell Platform configure script gives the nonsensical error that I must "upgrade" from GHC 6.12 down to GHC 6.10. I was getting pretty run down by this point so I just told it to sod off using the --enable-unsupported-ghc-version command line option. The Haskell Platform's configure script then completed but building it failed with: [21 of 21] Compiling Graphics.UI.GLUT ( Graphics/UI/GLUT.hs, dist/build/Graphics/UI/GLUT.p_o ) Registering GLUT-2.1.1.2... Setup: GLUT-2.1.1.2: dependency "OpenGL-2.2.1.1-182b091280ce0de861295bc592bae77c" doesn't exist (use --force to override) Error: Building the GLUT-2.1.1.2 package failed make: *** [build.stamp] Error 2 I have glut and use it all the time from OCaml without a hitch so I've no idea what the problem is here. Oh well, I just discovered that installing GHC 6.12 has at least fixed GHC 6.10 so it can now compile and run that mergesort. Oh FFS, spoke too soon: $ time ./mergesort +RTS -N8 Stack space overflow: current size 8388608 bytes. Use `+RTS -Ksize' to increase it. real 0m38.801s user 4m0.851s sys 0m1.308s -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From patrick.leboutillier at gmail.com Wed Dec 23 21:30:54 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Wed Dec 23 21:04:30 2009 Subject: [Haskell-beginners] Einstein's Problem In-Reply-To: <200912240134.52738.daniel.is.fischer@web.de> References: <200912240134.52738.daniel.is.fischer@web.de> Message-ID: Daniel, > Instead of > > if checkStreet s then ... else [], use Control.Monad.guard: > > test = do > ? ?ds <- drinkPerms > ? ?ns <- nationPerms > ? ?let s = Street $ makeHouses ds ns [] [] [] > ? ?guard (checkStreet s) > ? ?ss <- smokePerms > ? ?... Excellent. That really cleans it up! >> >> I'm also open to any comments about making better use of the different >> Haskell idioms. > > There is a function permutations in Data.List, you can use that instead of writing your > own (except if you want the permutations in a different order). > xxxPerms = permutationsOf [toEnum 0 .. toEnum 4] :: [[XXX]] isn't particularly nice, > better give the first and last constructor of each type or define > allPerms :: (Enum a, Bounded a) => [[a]] > allPerms = permutationsOf [minBound .. maxBound] > and derive also Bounded for your types. Great! I tried to do something a bit like that using typeclasses, but I got lost along the way.. :( I love how allPerms generates the correct permutations using type inference! > nationPerms = filter rule1 $ permutationsOf [toEnum 0 .. toEnum 4] :: [[Nation]] > ? ?where rule1 ns = (ns !! 0) == Norway > > is very inefficient, make that > nationPerms ?= map (Norway:) $ permutationsOf [England .. Denmark] > (yes, it's not so terrible for only five items, still it made me wince). > Similar for drinkPerms. How do you do it with drinkPerms? The constant element is in the middle (with Nations it seems easier since it's the first one). > checkCond (f,c) h = fmap (== c) (f h) > ~> > checkCond (f,c) = fmap (== c) . f Ok. Hopefully someday these patterns will be obvious... Thanks a lot, Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From aslatter at gmail.com Wed Dec 23 21:55:33 2009 From: aslatter at gmail.com (Antoine Latter) Date: Wed Dec 23 21:29:09 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <200912240224.19621.jon@ffconsultancy.com> References: <200912240224.19621.jon@ffconsultancy.com> Message-ID: <694519c50912231855i327ca552w64432e9105795636@mail.gmail.com> On Thu, Dec 24, 2009 at 2:24 AM, Jon Harrop wrote: > > For some reason all traffic from this beginners list stopped reaching me after > the 13th of December. > > Thanks for the response, Antoine. I've tried to install more recent versions > of GHC (6.10 and 6.12) but I cannot get either of them to work at all. > > GHC 6.8 generates code that segfaults and the GHC 6.10 from Debian testing > cannot compile anything for me. So I thought I'd try GHC 6.12. That isn't in > any repo so I decided to build it from source. I uninstalled all other GHCs > to give it a fresh start. The GHC page says "Stop, install the Haskell > Platform" but the Haskell Platform says you must install GHC first, so I've > got a nice circular dependency right from the start! > > So I tried installing GHC 6.12 from source but that requires GHC to be > installed. So I installed GHC 6.8 (the one that segfaults) using apt again > from Debian. That seems to have built a GHC 6.12 that I can run from the > command line but it cannot compile that program because it doesn't have > parallel stuff. So I thought I'd install the Haskell Platform. > The Haskell Platform is currently the recommended way to go, but it won't be up on GHC 6.12 until some time in the new year (I don't know their timelines). For me, I didn't have a working GHC 6.12 setup until this morning. The compiler is ready, but we're still working on moving the libraries over to the new major version. Maybe compiling your own 6.10.4 would be the best choice until the next platform release. If you're willing to dive in, the version of cabal-install that works for GHC 6.12.1 is out now, but it does require some boot-strapping to get going, as GHC no longer ships libraries that aren't required to build GHC. But back to the GHC panic, it might be worth posting that error to the GHC-users list I mentioned earlier. Antoine From daniel.is.fischer at web.de Wed Dec 23 22:09:26 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Dec 23 21:44:34 2009 Subject: [Haskell-beginners] Einstein's Problem In-Reply-To: References: <200912240134.52738.daniel.is.fischer@web.de> Message-ID: <200912240409.27082.daniel.is.fischer@web.de> Am Donnerstag 24 Dezember 2009 03:30:54 schrieb Patrick LeBoutillier: > How do you do it with drinkPerms? The constant element is in the > middle (with Nations > it seems easier since it's the first one). insertAt :: Int -> a -> [a] -> [a] insertAt k x xs = case splitAt k xs of (front,back) -> front ++ x:back drinkPerms = map (insertAt 2 Milk) $ permutations [Coffee, Tea, Water, Beer] Another possibility to have x inserted at a fixed position in all permutations of xs is to use do (fs,bs) <- picks k xs pf <- permutations fs pb <- permutations bs return (pf ++ x:pb) which has the advantage that the permutations of the front are shared (if the back is longer than the front, it might be better to swap lines 2 and 3 to share the permutations of the back) and avoids the many splits. picks :: Int -> [a] -> [([a],[a])] picks k xs | k == 0 = [([],xs)] | k == l = [(xs,[])] | k > l = [] | otherwise = pickHelper l k xs where l = length xs pickHelper s t yys@(y:ys) | s == t = [(yys,[])] | otherwise = [(y:zs,ws) | (zs,ws) <- pickHelper (s-1) (t-1) ys] ++ [(zs,y:ws) | (zs,ws) <- pickHelper (s-1) t ys] It's by far not as nice as keeping the first element fixed, but you can easily keep more than one position fixed. And when you have a couple more items, this approach is enormously faster than filtering. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091223/b0ef4b6b/attachment-0001.html From tom.davie at gmail.com Thu Dec 24 04:09:41 2009 From: tom.davie at gmail.com (Tom Davie) Date: Thu Dec 24 03:43:17 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <200912240224.19621.jon@ffconsultancy.com> References: <200912240224.19621.jon@ffconsultancy.com> Message-ID: <8b70a98a0912240109i3163e596j4e2c5b9416fdbc4c@mail.gmail.com> The mergesort example given here has a rather nasty problem ? it creates sparks for mergeing the two lists at the same time as it creates the lists, so there's always at least one task blocking waiting for it's producers. This variation on a theme goes roughly twice as fast for me with -N1, and *does* get a speedup from -N: mergesort [] = [] mergesort [x] = [x] mergesort [x,y] = if x < y then [x,y] else [y,x] mergesort xs = (forceList sleft) `par` (forceList sright) `pseq` merge sleft sright where (left,right) = split (length xs `div` 2) xs sleft = mergesort left sright = mergesort right Note the `pseq` not `par` before the merge. I also added one more short-circuit case ? we want to avoid spawning threads for tiny tasks like sorting 1 element lists. Here's my results on a dual core running OS X: LappyBob:~ tatd2$ time ./test +RTS -N1 -0.117109518058233 real 0m4.608s user 0m4.400s sys 0m0.189s LappyBob:~ tatd2$ time ./test +RTS -N2 -0.117109518058233 real 0m3.648s user 0m6.360s sys 0m0.220s LappyBob:~ tatd2$ time ./test +RTS -N3 -0.117109518058233 real 0m50.679s user 1m24.235s sys 0m0.620s The last result is still off the wall, but it's a lot better. Bob On Thu, Dec 24, 2009 at 2:24 AM, Jon Harrop wrote: > > For some reason all traffic from this beginners list stopped reaching me > after > the 13th of December. > > Thanks for the response, Antoine. I've tried to install more recent > versions > of GHC (6.10 and 6.12) but I cannot get either of them to work at all. > > GHC 6.8 generates code that segfaults and the GHC 6.10 from Debian testing > cannot compile anything for me. So I thought I'd try GHC 6.12. That isn't > in > any repo so I decided to build it from source. I uninstalled all other GHCs > to give it a fresh start. The GHC page says "Stop, install the Haskell > Platform" but the Haskell Platform says you must install GHC first, so I've > got a nice circular dependency right from the start! > > So I tried installing GHC 6.12 from source but that requires GHC to be > installed. So I installed GHC 6.8 (the one that segfaults) using apt again > from Debian. That seems to have built a GHC 6.12 that I can run from the > command line but it cannot compile that program because it doesn't have > parallel stuff. So I thought I'd install the Haskell Platform. > > Unfortunately, the Haskell Platform configure script gives the nonsensical > error that I must "upgrade" from GHC 6.12 down to GHC 6.10. I was getting > pretty run down by this point so I just told it to sod off using > the --enable-unsupported-ghc-version command line option. The Haskell > Platform's configure script then completed but building it failed with: > > [21 of 21] Compiling Graphics.UI.GLUT ( Graphics/UI/GLUT.hs, > dist/build/Graphics/UI/GLUT.p_o ) > Registering GLUT-2.1.1.2... > Setup: GLUT-2.1.1.2: dependency > "OpenGL-2.2.1.1-182b091280ce0de861295bc592bae77c" doesn't exist (use > --force > to override) > > Error: > Building the GLUT-2.1.1.2 package failed > make: *** [build.stamp] Error 2 > > I have glut and use it all the time from OCaml without a hitch so I've no > idea > what the problem is here. > > Oh well, I just discovered that installing GHC 6.12 has at least fixed GHC > 6.10 so it can now compile and run that mergesort. Oh FFS, spoke too soon: > > $ time ./mergesort +RTS -N8 > Stack space overflow: current size 8388608 bytes. > Use `+RTS -Ksize' to increase it. > > real 0m38.801s > user 4m0.851s > sys 0m1.308s > > -- > Dr Jon Harrop, Flying Frog Consultancy Ltd. > http://www.ffconsultancy.com/?e > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091224/29363886/attachment.html From mutilating.cauliflowers.stephen at blacksapphire.com Thu Dec 24 07:58:54 2009 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Thu Dec 24 07:32:42 2009 Subject: [Haskell-beginners] Re: Applicability of FP unchanging things to real world changing things Message-ID: <4B33658E.8090607@blacksapphire.com> Glurk, You wrote: > I think a lot of people, looking at the real world, would answer, yes, it > clearly IS the same book, now in a different state. And yes, I CAN step into > the same river twice. This is how people see and think about the real world. I think this is a really interesting question, and I may be too new at functional programming myself to do it justice. I've been doing a lot of Haskell in a short time, so my experience is fairly intuitive and this email is part of the process of making it more conscious. Here's one way to structure the library: lend :: BookID -> Library -> Library actOn :: Request -> Library -> (Library, [Result]) actOn (Lend bookID) lib = (lend bookID lib, []) ... -- | A library is a transformation from Request events (e.g. 'lend') to Result events (e.g. overdue book email), -- implemented using lazy lists. library :: Library -> [Request] -> [Result] library lib0 reqs = concat $ snd $ mapAccumL (\lib req -> actOn req lib) lib0 reqs Now, are we mutating a library, or are we not? In spite of what the more Zen-oriented Haskellers might say, it seems to me we are. Call me uneducated but I can't really see what is actually wrong with the idea of mutation of state over time, where the abstraction is appropriate. Perhaps the point is that in Haskell, this is one of many ways of looking at it. Perhaps the essential difference here is that the library goes round in an "eddy" with an inflow of events influencing it as it goes round (and producing an outflow of Result events). This difference accounts for more than it seems to. (Trying to put my finger on it...) it's a much more restricted activity than mutating state outright, that means that if you change your code locally (e.g. re-write the I/O parts), your chance of breaking things is minimal to zero. > I guess that brings up another point - that eventually we are drawn into > monads, which to me seems a bit unfortunate, because it seems that it leads us > back to imperative programming with mutable state... In many situations where I could use a state monad I don't (though I went through a stage of using them). My advice would be just write the code straight, and if the state management gets complex, a state monad may be warranted, or some better way may present itself. The great beauty of Haskell is that you have a lot of choices when a situation like this arises, and going for a state monad before you've examined the alternatives potentially restrict them. In the library example, if Library is a complicated data structure, you might want to have some lift functions that allow functions that affect only parts of the library to be lifted into a 'Library -> Library' type, e.g. liftDueDates :: (DueDates -> DueDates) -> Library -> Library liftDueDates f lib = lib { libDueDates = f (libDueDates lib) } Or to take the concept further ... There may be situations where you want to do some process where there are a number of parts of the library you want to work with, but conceptually some other way of viewing it makes sense. The "Haskell Way" would be to take the right parts of Library and create a new data structure that reflects the conception better. (In FP you often abstract things using data where you would use code in imperative languages.) If some output from that process has to contribute to a modified Library, then implement that as yet another transformation. Putting things back together like this is the extra work that Haskell makes you do - but the benefits outweigh the costs. So I'd say this: If you write your code in really plain Haskell, you'll tend towards a functional approach (e.g. why pass Library when it's better to transform library in some way first?). In that process, a state monad might suggest itself as a way of making the code more readable, but the thinking is still "plain Haskell". Then you're using a state monad with "right mindfulness" so to speak. Way of looking at it #2: If you are using a state monad because it's easier for you to understand the code that way, that's probably the wrong reason to use one. If you're using it because your straightforward Haskell is looking a bit unreadable, and the state monad tidies it up, then that's probably the right reason to use one. Way of looking at it #3: Your data needs to go through transformations from one form to another. In functional programming, you turn that process into a flow of data (or a sequence of transformations) from one form into another. If the flow loops, it starts to look a bit like mutating state, but in a way that's really only a surface appearance. One difference between state monads and mutating state in place (as done in OO languages) is that (in my experience) even with a state monad, the state mutation never really gets a chance to dominate the program. Haskellers have a saying "don't fear the monad - only IO is impure" that's applicable here. However, it's true that monads can lead to bad code, so they need to be used only where they're actually appropriate. I had an example of an excellent use for a monad recently: A parser where looking up an XML tag by its id string is abstracted as a continuation (so it can use IO if it wants) and it needs the ability to bail out if there's a parse error. A monad allowed me to write this code purely and cleanly. Another difference (state monad vs. mutating in place) is that a state monad can never lead to race conditions. Steve From chaddai.fouche at gmail.com Thu Dec 24 08:24:30 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Thu Dec 24 07:58:15 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <8b70a98a0912240109i3163e596j4e2c5b9416fdbc4c@mail.gmail.com> References: <200912240224.19621.jon@ffconsultancy.com> <8b70a98a0912240109i3163e596j4e2c5b9416fdbc4c@mail.gmail.com> Message-ID: On Thu, Dec 24, 2009 at 10:09 AM, Tom Davie wrote: > The mergesort example given here has a rather nasty problem ? it creates > sparks for mergeing the two lists at the same time as it creates the lists, > so there's always at least one task blocking waiting for it's producers. Don't worry too much about this thread, here is why : - Jon Harrop is definitely not a beginner in Haskell land and has no business asking this question on this list - Jon Harrop is very well known on established functional programming mailing lists and forum as a very disagreeable troll (not only on Haskell). He love to trash whatever language hasn't his favours at the moment (I think right now he likes F#, which is a very interesting language nonetheless). - He apparently made an effort to include approximately all elements that could hurt Haskell reputation in this thoughtful gift to the community in this Christmas period : ** As you pointed the initial code he chose doesn't parallelize very well basically ** He tried to compile it with GHC 6.8 which was an important step towards better internals to handle parallelism in GHC but was also a time of big upheaval in this field and so not as stable as one could wish. ** He then installed GHC 6.10 and did not even clean up his previous compilations attempts before declaring that it didn't work (the error message he cited is usually observed when GHC encounters an interface file created by a previous version of GHC or on another architecture) at all without testing on some other clean sources. ** He then apparently decided that using a binary package for the 6.12 version was beneath its dignity and went on to install it from source (generally not recommended except for GHC developers that needs to work on the code or for port to unusual architectures) and claimed that there was a "circularity problem" since its 6.10 could not compile it (which it obviously could, as he discovered and qualified as "miraculous", not even considering that he had a working 6.8 before). I could choose to believe that Harrop really is as incompetent as he sounds and really did encounter all those problems (which are all possibles if unlikely to be met in quick succession) but the simple fact that he decided to post this message on the Haskell-Beginner list instead of the Haskell-cafe list where he's already well known and an occasional poster makes it that much more unlikely. The other interpretation is that JdH is up to his usual tricks, just sinking to a new low by posting in a venue where he's less likely to be recognized and more likely to worry unwary would-be-haskell-beginners. Merry Christmas ! -- Jeda? From jon at ffconsultancy.com Thu Dec 24 17:50:13 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu Dec 24 16:09:36 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <8b70a98a0912240109i3163e596j4e2c5b9416fdbc4c@mail.gmail.com> References: <200912240224.19621.jon@ffconsultancy.com> <8b70a98a0912240109i3163e596j4e2c5b9416fdbc4c@mail.gmail.com> Message-ID: <200912242250.14046.jon@ffconsultancy.com> On Thursday 24 December 2009 09:09:41 you wrote: > The mergesort example given here has a rather nasty problem ? it creates > sparks for mergeing the two lists at the same time as it creates the lists, > so there's always at least one task blocking waiting for it's producers. I see. So the sparks either contend for locks on the thunks to force that list or they repeat the same work. > This variation on a theme goes roughly twice as fast for me with -N1, and > *does* get a speedup from -N: > > mergesort [] = [] > mergesort [x] = [x] > mergesort [x,y] = if x < y then [x,y] else [y,x] > mergesort xs = (forceList sleft) `par` > (forceList sright) `pseq` > merge sleft sright > where > (left,right) = split (length xs `div` 2) xs > sleft = mergesort left > sright = mergesort right > > Note the `pseq` not `par` before the merge. Can you explain why that helps? > I also added one more short-circuit case ? we want to avoid spawning threads > for tiny tasks like sorting 1 element lists. This is something that concerns me. Lots of discussions of parallelism, including the Haskell literature I have read, neglect this critical problem of making sure that more time is spent doing useful work than spawning tasks (sparks). How is this solved in Haskell? Do you just put magic numbers in that work on the machine you're currently using? Also, how much work does a Haskell thread usually have to do to make it worth sparking? > Here's my results on a dual core running OS X: > > LappyBob:~ tatd2$ time ./test +RTS -N1 > -0.117109518058233 > > real 0m4.608s > user 0m4.400s > sys 0m0.189s > LappyBob:~ tatd2$ time ./test +RTS -N2 > -0.117109518058233 > > real 0m3.648s > user 0m6.360s > sys 0m0.220s > LappyBob:~ tatd2$ time ./test +RTS -N3 > -0.117109518058233 > > real 0m50.679s > user 1m24.235s > sys 0m0.620s > > The last result is still off the wall, but it's a lot better. That's another question: why did you get such awful performance for N=3 and I get similar results for N=8 on this 8 core? -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From jon at ffconsultancy.com Thu Dec 24 17:53:51 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu Dec 24 16:13:13 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <694519c50912231855i327ca552w64432e9105795636@mail.gmail.com> References: <200912240224.19621.jon@ffconsultancy.com> <694519c50912231855i327ca552w64432e9105795636@mail.gmail.com> Message-ID: <200912242253.52105.jon@ffconsultancy.com> On Thursday 24 December 2009 02:55:33 you wrote: > The Haskell Platform is currently the recommended way to go, but it > won't be up on GHC 6.12 until some time in the new year (I don't know > their timelines). I see, thanks. > For me, I didn't have a working GHC 6.12 setup until this morning. The > compiler is ready, but we're still working on moving the libraries > over to the new major version. > > Maybe compiling your own 6.10.4 would be the best choice until the > next platform release. Is that better than using the 6.10.4 from Debian (and the haskell-platform package)? > If you're willing to dive in, the version of cabal-install that works > for GHC 6.12.1 is out now, but it does require some boot-strapping to > get going, as GHC no longer ships libraries that aren't required to > build GHC. Yeah, I tried installing cabal from source as well but couldn't get it to work either. > But back to the GHC panic, it might be worth posting that error to the > GHC-users list I mentioned earlier. I cannot reproduce it with GHC 6.10 so it has probably long since been fixed (6.8 is two years old!). -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From jonathanGfischoff at gmail.com Thu Dec 24 17:21:56 2009 From: jonathanGfischoff at gmail.com (jonathanGfischoff@gmail.com) Date: Thu Dec 24 16:55:30 2009 Subject: [Haskell-beginners] Design Question: fmap with two lists Message-ID: <0016e64bba9eee1382047b80dd89@google.com> I have a class that is basically: data TwoLists = TL {doubleList :: [Double], intList :: [Int]} Almost all of the operations of this type map, fold, etc on one of the lists or the other, and then return a new instance of the type. So I am implementing to functions dFmap, and iFmap. I actually would like all of the list functions, but I don't want to reimplement them. So my question is, what is the haskell way of handling a type like this. Is there some sort of TwoTypeTraversable I should be deriving from? Essential is there a Haskell idiom for this situation. -Jonathan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091224/3a3bc1d9/attachment.html From jon at ffconsultancy.com Thu Dec 24 19:43:31 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu Dec 24 18:02:53 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: References: <200912240224.19621.jon@ffconsultancy.com> <8b70a98a0912240109i3163e596j4e2c5b9416fdbc4c@mail.gmail.com> Message-ID: <200912250043.31724.jon@ffconsultancy.com> On Thursday 24 December 2009 13:24:30 you wrote: > ** As you pointed the initial code he chose doesn't parallelize very > well basically I Googled for "parallel mergesort haskell" and found that code in lecture notes by an associate university professor who has pages of published papers on his specialist topic of parallel programming in Haskell. I had no idea it was bad code. > ** He tried to compile it with GHC 6.8 which was an important step > towards better internals to handle parallelism in GHC but was also a > time of big upheaval in this field and so not as stable as one could > wish. I didn't know that. > ** He then installed GHC 6.10 and did not even clean up his previous > compilations attempts before declaring that it didn't work (the error > message he cited is usually observed when GHC encounters an interface > file created by a previous version of GHC or on another architecture) > at all without testing on some other clean sources. Looks like 6.12 fixed that problem. > ** He then apparently decided that using a binary package for the 6.12 > version was beneath its dignity and went on to install it from source > (generally not recommended except for GHC developers that needs to > work on the code or for port to unusual architectures) I had no idea that building GHC from source was such a big deal. I'll use the binaries. > and claimed > that there was a "circularity problem" since its 6.10 could not > compile it (which it obviously could, as he discovered and qualified > as "miraculous", not even considering that he had a working 6.8 > before). The circularity problem is that the GHC and Haskell Platform download pages both say that you must install the other first: "Stop! For most users, we recommend installing the Haskell Platform instead of GHC." - http://www.haskell.org/ghc/download_ghc_6_12_1.html "You only need GHC installed to get started:" - http://hackage.haskell.org/platform/ I wasn't sure how to proceed so I guess and apparently got it wrong. -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From uzytkownik2 at gmail.com Thu Dec 24 19:48:25 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Thu Dec 24 19:22:20 2009 Subject: [Haskell-beginners] Re: Design Question: fmap with two lists In-Reply-To: <0016e64bba9eee1382047b80dd89@google.com> References: <0016e64bba9eee1382047b80dd89@google.com> Message-ID: <1261702105.5686.48.camel@picard> On Thu, 2009-12-24 at 22:21 +0000, jonathanGfischoff@gmail.com wrote: > I have a class that is basically: > Hmm. Class in haskell means something similar to interface in OOP. Yes it is confusing. > data TwoLists = TL {doubleList :: [Double], intList :: [Int]} > > Almost all of the operations of this type map, fold, etc on one of the > lists or the other, and then return a new instance of the type. It may be my level of English bit I cannot understend this sentence. > So I am implementing to functions dFmap, and iFmap. What is dFmap and iFmap? > I actually would like all of the list functions, but I don't want to > reimplement them. > Hmm. If you need to combine the lists I'd suggest zip/zipWith. If simply map/fold over one then just write (or similar): foldr f i . doubleList If you mean if there is class: class BiFunctor f where fmap2 :: (a -> c) -> (b -> d) -> f a b -> f c d fmap2 f g = fmap2b g . fmap2a f fmap2a :: (a -> c) -> f a b -> f c b fmap2a f = fmap2 f id fmap2b :: (b -> d) -> f a b -> f a d fmap2b = fmap2 id To write: data TwoLists a b = TwoLists [a] [b] instance BiFunctor TwoLists where fmap2 f g (TwoLists a b) = TwoLists (map f a) (map g b) then as far as I know - no - but you can always write your own. Regards From mabufo at gmail.com Thu Dec 24 20:18:37 2009 From: mabufo at gmail.com (Matt Young) Date: Thu Dec 24 19:52:10 2009 Subject: [Haskell-beginners] Finding the height of a simple binary tree Message-ID: Hi guys! Just so we are all on the same page, this problem is an exercise from the end of Chapter 3 in the book Real World Haskell (#8). The problem calls for me to write a function to figure out the height of our user defined binary tree type. Here is the type: --chapter3 binary tree recursive type data Tree a = Node a (Tree a) (Tree a) | Empty deriving (Show) With this type, we'd create a tree with no leaves like: Node "tree" Empty Empty, and a tree with a single leaf like Node "tree2" = Empty (Node "leaf" Empty Empty) Being new to Haskell, I'm not sure how to traverse this binary tree type that the book has given. No doubt we'll be using some crafty recursion to get this done. So to summarize what I'd like to know, 1) what is the best way to figure out the height of this binary tree type that I have, or rather any binary tree in general? 2) How do I translate that into Haskell code. Verbose explanations are appreciated. Thanks guys! -- -Matthew From rk at trie.org Thu Dec 24 20:34:35 2009 From: rk at trie.org (Rahul Kapoor) Date: Thu Dec 24 20:08:10 2009 Subject: [Haskell-beginners] Finding the height of a simple binary tree In-Reply-To: References: Message-ID: See if this case analysis helps: Height of the Empty Node is zero. Height of a non empty node is = 1 + (the greater height of its 2 sub trees) The function max gives you the greater of two values. HTH Rahul On Thu, Dec 24, 2009 at 8:18 PM, Matt Young wrote: > Hi guys! Just so we are all on the same page, this problem is an > exercise from the end of Chapter 3 in the book Real World Haskell > (#8). > > The problem calls for me to write a function to figure out the height > of our user defined binary tree type. > Here is the type: > ?--chapter3 binary tree recursive type > data Tree a = Node a (Tree a) (Tree a) > ? ? ? ? ? ? ? ? ? ? ? ? ?| Empty > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?deriving (Show) > With this type, we'd create a tree with no leaves like: Node "tree" > Empty Empty, and a tree with a single leaf like Node "tree2" = Empty > (Node "leaf" Empty Empty) > > Being new to Haskell, I'm not sure how to traverse this binary tree > type that the book has given. No doubt we'll be using some crafty > recursion to get this done. So to summarize what I'd like to know, 1) > what is the best way to figure out the height of this binary tree type > that I have, or rather any binary tree in general? 2) How do I > translate that into Haskell code. > > Verbose explanations are appreciated. > > Thanks guys! > > > -- > -Matthew > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From gtener at gmail.com Thu Dec 24 20:47:10 2009 From: gtener at gmail.com (=?UTF-8?Q?Krzysztof_Skrz=C4=99tnicki?=) Date: Thu Dec 24 20:20:43 2009 Subject: [Haskell-beginners] Finding the height of a simple binary tree In-Reply-To: References: Message-ID: <220e47b40912241747q27196e54kdc6a21feb1485518@mail.gmail.com> The code is also extremely simple: height Empty = 0 -- Height of the Empty Node is zero. height (Node t1 t2) = 1 + (max (height t1) (height t2)) -- Height of a non empty node is = 1 + (the greater height of its 2 sub trees) Regards On Fri, Dec 25, 2009 at 02:34, Rahul Kapoor wrote: > See if this case analysis helps: > > Height of the Empty Node is zero. > Height of a non empty node is = 1 + (the greater height of its 2 sub trees) > > The function max gives you the greater of two values. > > HTH > Rahul > > On Thu, Dec 24, 2009 at 8:18 PM, Matt Young wrote: > > Hi guys! Just so we are all on the same page, this problem is an > > exercise from the end of Chapter 3 in the book Real World Haskell > > (#8). > > > > The problem calls for me to write a function to figure out the height > > of our user defined binary tree type. > > Here is the type: > > --chapter3 binary tree recursive type > > data Tree a = Node a (Tree a) (Tree a) > > | Empty > > deriving (Show) > > With this type, we'd create a tree with no leaves like: Node "tree" > > Empty Empty, and a tree with a single leaf like Node "tree2" = Empty > > (Node "leaf" Empty Empty) > > > > Being new to Haskell, I'm not sure how to traverse this binary tree > > type that the book has given. No doubt we'll be using some crafty > > recursion to get this done. So to summarize what I'd like to know, 1) > > what is the best way to figure out the height of this binary tree type > > that I have, or rather any binary tree in general? 2) How do I > > translate that into Haskell code. > > > > Verbose explanations are appreciated. > > > > Thanks guys! > > > > > > -- > > -Matthew > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091224/4233e852/attachment.html From gtener at gmail.com Thu Dec 24 20:48:49 2009 From: gtener at gmail.com (=?UTF-8?Q?Krzysztof_Skrz=C4=99tnicki?=) Date: Thu Dec 24 20:22:23 2009 Subject: [Haskell-beginners] Finding the height of a simple binary tree In-Reply-To: <220e47b40912241747q27196e54kdc6a21feb1485518@mail.gmail.com> References: <220e47b40912241747q27196e54kdc6a21feb1485518@mail.gmail.com> Message-ID: <220e47b40912241748p6f392afev696381357830a43@mail.gmail.com> I made a typo: since Node is labeled we need to match against ternary constructor: height Empty = 0 -- Height of the Empty Node is zero. height (Node _ t1 t2) = 1 + (max (height t1) (height t2)) -- Height of a non empty node is = 1 + (the greater height of its 2 sub trees) 2009/12/25 Krzysztof Skrz?tnicki > The code is also extremely simple: > > height Empty = 0 -- Height of the Empty Node is zero. > height (Node t1 t2) = 1 + (max (height t1) (height t2)) -- Height of a non > empty node is = 1 + (the greater height of its 2 sub trees) > > Regards > > > > On Fri, Dec 25, 2009 at 02:34, Rahul Kapoor wrote: > >> See if this case analysis helps: >> >> Height of the Empty Node is zero. >> Height of a non empty node is = 1 + (the greater height of its 2 sub >> trees) >> >> The function max gives you the greater of two values. >> >> HTH >> Rahul >> >> On Thu, Dec 24, 2009 at 8:18 PM, Matt Young wrote: >> > Hi guys! Just so we are all on the same page, this problem is an >> > exercise from the end of Chapter 3 in the book Real World Haskell >> > (#8). >> > >> > The problem calls for me to write a function to figure out the height >> > of our user defined binary tree type. >> > Here is the type: >> > --chapter3 binary tree recursive type >> > data Tree a = Node a (Tree a) (Tree a) >> > | Empty >> > deriving (Show) >> > With this type, we'd create a tree with no leaves like: Node "tree" >> > Empty Empty, and a tree with a single leaf like Node "tree2" = Empty >> > (Node "leaf" Empty Empty) >> > >> > Being new to Haskell, I'm not sure how to traverse this binary tree >> > type that the book has given. No doubt we'll be using some crafty >> > recursion to get this done. So to summarize what I'd like to know, 1) >> > what is the best way to figure out the height of this binary tree type >> > that I have, or rather any binary tree in general? 2) How do I >> > translate that into Haskell code. >> > >> > Verbose explanations are appreciated. >> > >> > Thanks guys! >> > >> > >> > -- >> > -Matthew >> > _______________________________________________ >> > Beginners mailing list >> > Beginners@haskell.org >> > http://www.haskell.org/mailman/listinfo/beginners >> > >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091224/31a4e839/attachment-0001.html From apfelmus at quantentunnel.de Fri Dec 25 07:07:30 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Fri Dec 25 06:41:24 2009 Subject: [Haskell-beginners] Re: Applicability of FP unchanging things to real world changing things In-Reply-To: <4B33658E.8090607@blacksapphire.com> References: <4B33658E.8090607@blacksapphire.com> Message-ID: Stephen Blackheath wrote: > Glurk wrote: >> I think a lot of people, looking at the real world, would answer, yes, it >> clearly IS the same book, now in a different state. And yes, I CAN >> step into the same river twice. This is how people see and think >> about the real world. > > [...] > Here's one way to structure the library: > > lend :: BookID -> Library -> Library > > actOn :: Request -> Library -> (Library, [Result]) > actOn (Lend bookID) lib = (lend bookID lib, []) > .... > > -- | A library is a transformation from Request events (e.g. 'lend') > -- to Result events (e.g. overdue book email), > -- implemented using lazy lists. > library :: Library -> [Request] -> [Result] > library lib0 reqs = concat $ snd $ mapAccumL (\lib req -> actOn req lib) > lib0 reqs > > Now, are we mutating a library, or are we not? In spite of what the > more Zen-oriented Haskellers might say, it seems to me we are. Call me > uneducated but I can't really see what is actually wrong with the idea > of mutation of state over time, where the abstraction is appropriate. > Perhaps the point is that in Haskell, this is one of many ways of > looking at it. I think it's entirely fine to interpret the above code snippet as a program that changes the current library. ("To change" can be read two ways: either to *ex*change the current library for a new one or to *mutate* the current library. I lean towards the former because it is closer to what Haskell actually does; but such fine print matters little.) However -- and this is the key point -- that doesn't mean that the model has to change or mutate anything. Put differently, I would attribute a lack of imagination to any notion that the model must be formulated in terms of mutable variables. In other words, whether the real world mutates things and whether we interpret it that way is quite irrelevant; the real question is whether the programming language we use to model the real world should include mutation (in the form of mutable variables). And the answer to that not only depends on how much the language caters to primordial intuition, as Glurk argues, but also on how fluent and expressive the language is and how it "interacts with itself". The premise of Haskell is that we pay a small translation cost from pure functions to an interpretation involving mutations, a cost that can be reduced to zero with proper training, but reap a big profit when it comes to manipulating and composing pure functions / programs. Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From byorgey at seas.upenn.edu Fri Dec 25 21:10:19 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Fri Dec 25 20:43:48 2009 Subject: [Haskell-beginners] Re: Design Question: fmap with two lists In-Reply-To: <1261702105.5686.48.camel@picard> References: <0016e64bba9eee1382047b80dd89@google.com> <1261702105.5686.48.camel@picard> Message-ID: <20091226021018.GA11240@seas.upenn.edu> On Fri, Dec 25, 2009 at 01:48:25AM +0100, Maciej Piechotka wrote: > On Thu, 2009-12-24 at 22:21 +0000, jonathanGfischoff@gmail.com wrote: > > I have a class that is basically: > > > > Hmm. Class in haskell means something similar to interface in OOP. Yes > it is confusing. > > > data TwoLists = TL {doubleList :: [Double], intList :: [Int]} > > > > Almost all of the operations of this type map, fold, etc on one of the > > lists or the other, and then return a new instance of the type. > > It may be my level of English bit I cannot understend this sentence. > > > So I am implementing to functions dFmap, and iFmap. > > What is dFmap and iFmap? > > > I actually would like all of the list functions, but I don't want to > > reimplement them. > > > > Hmm. If you need to combine the lists I'd suggest zip/zipWith. If simply > map/fold over one then just write (or similar): > > foldr f i . doubleList > > If you mean if there is class: > class BiFunctor f where > fmap2 :: (a -> c) -> (b -> d) -> f a b -> f c d > fmap2 f g = fmap2b g . fmap2a f > fmap2a :: (a -> c) -> f a b -> f c b > fmap2a f = fmap2 f id > fmap2b :: (b -> d) -> f a b -> f a d > fmap2b = fmap2 id There is such a class in the category-extras package, although it is so general that it is probably not worth the effort of trying to understand it unless you really need the extra abstraction. -Brent From byorgey at seas.upenn.edu Fri Dec 25 21:14:24 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Fri Dec 25 20:47:54 2009 Subject: [Haskell-beginners] Finding the height of a simple binary tree In-Reply-To: References: Message-ID: <20091226021424.GB11240@seas.upenn.edu> On Thu, Dec 24, 2009 at 07:18:37PM -0600, Matt Young wrote: > Hi guys! Just so we are all on the same page, this problem is an > exercise from the end of Chapter 3 in the book Real World Haskell > (#8). > > The problem calls for me to write a function to figure out the height > of our user defined binary tree type. > Here is the type: > --chapter3 binary tree recursive type > data Tree a = Node a (Tree a) (Tree a) > | Empty > deriving (Show) > With this type, we'd create a tree with no leaves like: Node "tree" > Empty Empty, and a tree with a single leaf like Node "tree2" = Empty > (Node "leaf" Empty Empty) It seems that you are perhaps a little confused about values of this type. First of all, I would say that the value Node "tree" Empty Empty is a tree with one node, which is a leaf. A leaf is any node with no children --- as you can see this node's children are both Empty. The only tree with no leaves is the Empty tree. Also, this: Empty (Node "leaf" Empty Empty) is a type error. Empty cannot be applied to (Node "leaf" Empty Empty), since it is a constructor that takes no arguments. I am not sure what tree you had in mind. Did the other replies help you figure out how to find the height of a tree or would you like more detailed explanation? -Brent From haskell at dpillay.eml.cc Sat Dec 26 03:51:45 2009 From: haskell at dpillay.eml.cc (haskell@dpillay.eml.cc) Date: Sat Dec 26 03:25:14 2009 Subject: [Haskell-beginners] Finding the height of a simple binary tree In-Reply-To: References: Message-ID: <1261817505.3175.1351775641@webmail.messagingengine.com> Hey Matt, What generally helps is to lay out the pattern of heights you'd observe. a1 = Empty -- would be a tree with height of 0. a2 = Node 'a' Empty Empty -- would be a tree with height of 1. a3 = Node 'a' (Node 'b' (Node 'c' Empty Empty) Empty) (Node 'd' Empty Empty) -- would be a tree with height of 3 Using these 3 facts you could construct a function to traverse the tree recursively where the height at a particular node is 1 + the max height between the left and right sub-trees. Thanks! - Dinesh. On Thu, 24 Dec 2009 19:18 -0600, "Matt Young" wrote: > Hi guys! Just so we are all on the same page, this problem is an > exercise from the end of Chapter 3 in the book Real World Haskell > (#8). > > The problem calls for me to write a function to figure out the height > of our user defined binary tree type. > Here is the type: > --chapter3 binary tree recursive type > data Tree a = Node a (Tree a) (Tree a) > | Empty > deriving (Show) > With this type, we'd create a tree with no leaves like: Node "tree" > Empty Empty, and a tree with a single leaf like Node "tree2" = Empty > (Node "leaf" Empty Empty) > > Being new to Haskell, I'm not sure how to traverse this binary tree > type that the book has given. No doubt we'll be using some crafty > recursion to get this done. So to summarize what I'd like to know, 1) > what is the best way to figure out the height of this binary tree type > that I have, or rather any binary tree in general? 2) How do I > translate that into Haskell code. > > Verbose explanations are appreciated. > > Thanks guys! > > > -- > -Matthew > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From uzytkownik2 at gmail.com Sat Dec 26 12:12:00 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Sat Dec 26 11:45:40 2009 Subject: [Haskell-beginners] Re: Re: Design Question: fmap with two lists In-Reply-To: <20091226021018.GA11240@seas.upenn.edu> References: <0016e64bba9eee1382047b80dd89@google.com> <1261702105.5686.48.camel@picard> <20091226021018.GA11240@seas.upenn.edu> Message-ID: <1261847520.5658.0.camel@picard> On Fri, 2009-12-25 at 21:10 -0500, Brent Yorgey wrote: > There is such a class in the category-extras package, although it is > so general that it is probably not worth the effort of trying to > understand it unless you really need the extra abstraction. > > -Brent For the record - what is the name of it? I tried to search through category-extras twice. Regards From mcguire at crsr.net Sat Dec 26 13:00:49 2009 From: mcguire at crsr.net (Tommy M. McGuire) Date: Sat Dec 26 12:44:21 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <694519c50912231622i370abc4ofc25e0adb275f4a1@mail.gmail.com> References: <200912232114.24493.jon@ffconsultancy.com> <694519c50912231616n527d7e38hc8a7dd3efef62b4b@mail.gmail.com> <694519c50912231622i370abc4ofc25e0adb275f4a1@mail.gmail.com> Message-ID: <4B364F51.10009@crsr.net> Antoine Latter wrote: >> Here's a paste-bin link for the code in question: > http://hpaste.org/fastcgi/hpaste.fcgi/view?id=14871#a14871 I am not familiar with Control.Parallel at all, so someone please correct me if I'm wrong.... ...but that parallel mergesort looks very wrong to me. In the first place, the split is using the length of the list, which is going to force the spine of the list, leaving a bazillion thunks unless the runtime will evaluate the numerical value at each element. More importantly, it seems to be running the forcelist in parallel with the merge; forcelist is not going to do anything useful after the first pass over each element, and the merge has a data dependency on the split sub-lists, which is going to limit parallelism quite a bit. Am I wrong here? (Yep, Jeda?, I'm familiar with Jon and the reason he posted this here rather than the cafe.) -- Tommy M. McGuire mcguire@crsr.net From jon at ffconsultancy.com Sat Dec 26 14:44:36 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Sat Dec 26 13:03:50 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <8b70a98a0912240109i3163e596j4e2c5b9416fdbc4c@mail.gmail.com> References: <200912240224.19621.jon@ffconsultancy.com> <8b70a98a0912240109i3163e596j4e2c5b9416fdbc4c@mail.gmail.com> Message-ID: <200912261944.36574.jon@ffconsultancy.com> On Thursday 24 December 2009 09:09:41 Tom Davie wrote: > Here's my results on a dual core running OS X: > > LappyBob:~ tatd2$ time ./test +RTS -N1 > -0.117109518058233 > > real 0m4.608s > user 0m4.400s > sys 0m0.189s > LappyBob:~ tatd2$ time ./test +RTS -N2 > -0.117109518058233 > > real 0m3.648s > user 0m6.360s > sys 0m0.220s > LappyBob:~ tatd2$ time ./test +RTS -N3 > -0.117109518058233 > > real 0m50.679s > user 1m24.235s > sys 0m0.620s Here are my results on a dual quad-core: $ ghc-6.10.4 --make -O2 -threaded mergesort.hs -o mergesort [1 of 1] Compiling Main ( mergesort.hs, mergesort.o ) Linking mergesort ... jdh30@leper:~/Programs/mine/haskell/mergesort$ time ./mergesort +RTS -K100000000 +RTS -N1 -0.117109518058233 real 0m7.664s user 0m7.528s sys 0m0.136s $ time ./mergesort +RTS -K100000000 +RTS -N2 -0.117109518058233 real 0m7.224s user 0m9.773s sys 0m0.108s $ time ./mergesort +RTS -K100000000 +RTS -N3 -0.117109518058233 real 0m7.293s user 0m11.637s sys 0m0.168s $ time ./mergesort +RTS -K100000000 +RTS -N4 -0.117109518058233 real 0m7.333s user 0m12.689s sys 0m0.360s $ time ./mergesort +RTS -K100000000 +RTS -N5 -0.117109518058233 real 0m7.449s user 0m14.757s sys 0m0.548s $ time ./mergesort +RTS -K100000000 +RTS -N6 -0.117109518058233 real 0m7.043s user 0m14.985s sys 0m0.252s $ time ./mergesort +RTS -K100000000 +RTS -N7 -0.117109518058233 real 0m8.018s user 0m19.325s sys 0m1.012s $ time ./mergesort +RTS -K100000000 +RTS -N8 -0.117109518058233 real 0m55.963s user 5m55.654s sys 0m1.492s As you can see, there is still no significant speedup from parallelism. -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From jon at ffconsultancy.com Sat Dec 26 14:56:11 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Sat Dec 26 13:15:24 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <4B364F51.10009@crsr.net> References: <200912232114.24493.jon@ffconsultancy.com> <694519c50912231622i370abc4ofc25e0adb275f4a1@mail.gmail.com> <4B364F51.10009@crsr.net> Message-ID: <200912261956.11617.jon@ffconsultancy.com> On Saturday 26 December 2009 18:00:49 Tommy M. McGuire wrote: > Antoine Latter wrote: > >> Here's a paste-bin link for the code in question: > > > > http://hpaste.org/fastcgi/hpaste.fcgi/view?id=14871#a14871 > > I am not familiar with Control.Parallel at all, so someone please correct > me if I'm wrong.... > > ...but that parallel mergesort looks very wrong to me. > > In the first place, the split is using the length of the list, which is > going to force the spine of the list, leaving a bazillion thunks unless the > runtime will evaluate the numerical value at each element. > > More importantly, it seems to be running the forcelist in parallel with the > merge; forcelist is not going to do anything useful after the first pass > over each element, and the merge has a data dependency on the split > sub-lists, which is going to limit parallelism quite a bit. > > Am I wrong here? The parallelism is obviously not obtaining any real speedup so something is wrong. But can anyone fix it? -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From flopticalogic at gmail.com Sun Dec 27 00:11:13 2009 From: flopticalogic at gmail.com (Floptical Logic) Date: Sat Dec 26 23:44:41 2009 Subject: [Haskell-beginners] Interrupting a thread Message-ID: Hi, I am new to concurrency in Haskell and I am having trouble implementing the notion of interrupting a thread. In a new thread, call it waitNotify, I am trying to do the following: pop a number from a stack, wait some number of seconds based on the number popped from the stack, perform some notification, and repeat until there are no more numbers in the stack at which point we wait for a new number. These numbers will be supplied interactively by the user from main. When the user supplies a new number, I want to interrupt whatever waiting is happening in waitNotify, insert the number in the proper position in the current stack, and resume waitNotify using the updated stack. Note, here "stack" is just a generalization; it will likely just be a list. What is the most idiomatic way to capture this sort of behavior in Haskell? My two challenges are the notion of interrupting a thread, and sharing and updating this stack between threads (main and waitNotify). Thank you From legajid at free.fr Sun Dec 27 08:42:48 2009 From: legajid at free.fr (legajid) Date: Sun Dec 27 08:11:54 2009 Subject: [Haskell-beginners] Enumerated types Message-ID: <4B376458.7010809@free.fr> Hello, I have some trouble evaluating Enum class. Following is my source: data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving (Enum, Show) auths=[Buzzati .. Verne] ++ enumFrom Ray pref=take 3 auths -- 1 disp_pref=mapM_ (putStrLn) pref auth1 = Buzzati auth2 = succ auth1 -- Werber auth3 = pred Asimov -- Ray num_auth4=fromEnum Verne -- 2 -- 2 toEnum main= display Buzzati display x = do putStrLn (show x) display (succ x) -- 3 end of enum 1. could'nt match expected type [Char] against inferred type Authors I would like to display each data constructor name on one line , giving : Buzzati Werber Verne How can i translate data from one type to another (Authors to [Char])? 2. Like fromEnum gives data constructor index, is it possible with toEnum (or other way) to get the nth constructor of the given type ? eg : 2 applied to Authors (not in scope ?) would give Verne 3. tried to take 'succ' of last tag in enumeration How to detect the end of an enumeration ? Can i get the maxbound index ? Thanks, Didier. From byorgey at seas.upenn.edu Sun Dec 27 09:07:35 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Dec 27 08:41:00 2009 Subject: [Haskell-beginners] Re: Re: Design Question: fmap with two lists In-Reply-To: <1261847520.5658.0.camel@picard> References: <0016e64bba9eee1382047b80dd89@google.com> <1261702105.5686.48.camel@picard> <20091226021018.GA11240@seas.upenn.edu> <1261847520.5658.0.camel@picard> Message-ID: <20091227140735.GA24410@seas.upenn.edu> On Sat, Dec 26, 2009 at 06:12:00PM +0100, Maciej Piechotka wrote: > On Fri, 2009-12-25 at 21:10 -0500, Brent Yorgey wrote: > > There is such a class in the category-extras package, although it is > > so general that it is probably not worth the effort of trying to > > understand it unless you really need the extra abstraction. > > > > -Brent > > For the record - what is the name of it? I tried to search through > category-extras twice. Control.Functor.Bifunctor. It took me a while to find it, too (I've had to re-find it several times); I didn't actually say where to find it in my first email because I knew it would take me a long time. Unfortunately, coherent organization is not among category-extras' strengths. ;-) -Brent From patrick.leboutillier at gmail.com Sun Dec 27 09:10:21 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Sun Dec 27 08:43:48 2009 Subject: [Haskell-beginners] Enumerated types In-Reply-To: <4B376458.7010809@free.fr> References: <4B376458.7010809@free.fr> Message-ID: Hi, On Sun, Dec 27, 2009 at 8:42 AM, legajid wrote: > Hello, > > I have some trouble evaluating Enum class. > Following is my source: > > data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving > (Enum, Show) > > auths=[Buzzati .. Verne] ++ enumFrom Ray > pref=take 3 auths > -- 1 disp_pref=mapM_ (putStrLn) pref putStrLn wants a String as argument, here you are passing an Authors. Try this: disp_pref=mapM_ (putStrLn . show) pref > > auth1 = Buzzati > auth2 = succ auth1 ? ? ? -- Werber > auth3 = pred Asimov ? ? ?-- Ray > num_auth4=fromEnum Verne -- 2 > -- 2 toEnum You can use toEnum to get the nth constructor. For example: nthAuthor :: Int -> Authors nthAuthor i = toEnum i > > main= display Buzzati > display x = do > ? ? ? putStrLn (show x) > ? ? ? display (succ x) > -- 3 end of enum To use maxBound you need to make your type an instance of Bounded. You will also need to make it an instance of Eq in order to compare it. main= display Buzzati display x = do putStrLn (show x) if x == maxBound then return () else display (succ x) Patrick > > 1. could'nt match expected type [Char] against inferred type Authors > I would like to display each data constructor name on one line , giving : > Buzzati > Werber > Verne > How can i translate data from one type to another (Authors to [Char])? > > 2. Like fromEnum gives data constructor index, is it possible with toEnum > (or other way) to get the nth constructor of the given type ? > eg : 2 applied to Authors (not in scope ?) would give Verne > > 3. tried to take ?'succ' of last tag ?in ?enumeration > How to detect the end of an enumeration ? Can i get the maxbound index ? > > Thanks, > Didier. > > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From byorgey at seas.upenn.edu Sun Dec 27 09:14:45 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Dec 27 08:48:10 2009 Subject: [Haskell-beginners] Enumerated types In-Reply-To: <4B376458.7010809@free.fr> References: <4B376458.7010809@free.fr> Message-ID: <20091227141445.GB24410@seas.upenn.edu> On Sun, Dec 27, 2009 at 02:42:48PM +0100, legajid wrote: > Hello, > > I have some trouble evaluating Enum class. > Following is my source: > > data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving > (Enum, Show) > > auths=[Buzzati .. Verne] ++ enumFrom Ray > pref=take 3 auths > -- 1 disp_pref=mapM_ (putStrLn) pref This is a type error since putStrLn expects a String and pref is a list of Authors. But the 'deriving Show' means that you can use the 'show' function to convert: disp_pref = mapM_ (putStrLn . show) pref In fact, since print = putStrLn . show, you can just say disp_pref = mapM_ print pref > 2. Like fromEnum gives data constructor index, is it possible with toEnum > (or other way) to get the nth constructor of the given type ? > eg : 2 applied to Authors (not in scope ?) would give Verne Yes, with toEnum. Just use e.g. 'toEnum 2'. How does it know that you want an Author and not some other Enum type? Why, through the magic of type inference! As long as you use 'toEnum 2' in a context where an Author value is expected it will evaluate to Verne. > 3. tried to take 'succ' of last tag in enumeration > How to detect the end of an enumeration ? Can i get the maxbound index ? Yes, if you add 'Bounded' to the list of derived classes, then 'maxBound' gives you the last one. -Brent From uzytkownik2 at gmail.com Sun Dec 27 11:35:20 2009 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Sun Dec 27 11:09:11 2009 Subject: [Haskell-beginners] Re: Interrupting a thread In-Reply-To: References: Message-ID: <1261931720.5658.7.camel@picard> On Sat, 2009-12-26 at 23:11 -0600, Floptical Logic wrote: > Hi, > > I am new to concurrency in Haskell and I am having trouble > implementing the notion of interrupting a thread. > > In a new thread, call it waitNotify, I am trying to do the following: > pop a number from a stack, wait some number of seconds based on the > number popped from the stack, perform some notification, and repeat > until there are no more numbers in the stack at which point we wait > for a new number. > > These numbers will be supplied interactively by the user from main. > When the user supplies a new number, I want to interrupt whatever > waiting is happening in waitNotify, insert the number in the proper > position in the current stack, and resume waitNotify using the updated > stack. Note, here "stack" is just a generalization; it will likely > just be a list. > > What is the most idiomatic way to capture this sort of behavior in > Haskell? My two challenges are the notion of interrupting a thread, > and sharing and updating this stack between threads (main and > waitNotify). > > Thank you 1. Hmm. IMHO - maybe you should look on CHP. As far as I remeber writing/reading to channel there is blocking. 2. You mean stack (FILO) or queue (FIFO)? 3. Why don't just read lazily from input? Regards From legajid at free.fr Sun Dec 27 12:17:34 2009 From: legajid at free.fr (legajid) Date: Sun Dec 27 11:46:40 2009 Subject: [Haskell-beginners] Enumerated types In-Reply-To: References: <4B376458.7010809@free.fr> Message-ID: <4B3796AE.5040504@free.fr> Thanks. for 1, i tried mapM ( putStrLn) (show pref) but show gives only one line with all values, instead of n lines with 1 value. I now understand that show must be in the function that is mapped. for 2, ok for 3, ok with new classes in deriving. I thought that i would have to write new instances of Bounded or Eq, but now i think it's unuseful since standard functions exist in these classes. Patrick LeBoutillier a ?crit : > Hi, > > On Sun, Dec 27, 2009 at 8:42 AM, legajid wrote: > >> Hello, >> >> I have some trouble evaluating Enum class. >> Following is my source: >> >> data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving >> (Enum, Show) >> >> auths=[Buzzati .. Verne] ++ enumFrom Ray >> pref=take 3 auths >> -- 1 disp_pref=mapM_ (putStrLn) pref >> > > putStrLn wants a String as argument, here you are passing an Authors. Try this: > > disp_pref=mapM_ (putStrLn . show) pref > > >> auth1 = Buzzati >> auth2 = succ auth1 -- Werber >> auth3 = pred Asimov -- Ray >> num_auth4=fromEnum Verne -- 2 >> -- 2 toEnum >> > > You can use toEnum to get the nth constructor. For example: > > nthAuthor :: Int -> Authors > nthAuthor i = toEnum i > > >> main= display Buzzati >> display x = do >> putStrLn (show x) >> display (succ x) >> -- 3 end of enum >> > > To use maxBound you need to make your type an instance of Bounded. You > will also need to make it an instance of Eq in order to compare it. > > main= display Buzzati > display x = do > putStrLn (show x) > if x == maxBound > then return () > else display (succ x) > > > Patrick > > >> 1. could'nt match expected type [Char] against inferred type Authors >> I would like to display each data constructor name on one line , giving : >> Buzzati >> Werber >> Verne >> How can i translate data from one type to another (Authors to [Char])? >> >> 2. Like fromEnum gives data constructor index, is it possible with toEnum >> (or other way) to get the nth constructor of the given type ? >> eg : 2 applied to Authors (not in scope ?) would give Verne >> >> 3. tried to take 'succ' of last tag in enumeration >> How to detect the end of an enumeration ? Can i get the maxbound index ? >> >> Thanks, >> Didier. >> >> >> >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> >> > > > > From john.moore54 at gmail.com Sun Dec 27 13:10:54 2009 From: john.moore54 at gmail.com (John Moore) Date: Sun Dec 27 12:44:21 2009 Subject: [Haskell-beginners] parser for expressions Message-ID: <4f7ad1ad0912271010w10331434ne6958521fcce2342@mail.gmail.com> Hi, What I'm trying to do is create a parser so as when I enter say 1+1 it will return Add(Val 1)(Val 1). A couple of questions do I have to state three basic parser. As in item, fail, synbol and then combine them with below. And by the way the one below seems to be all wrong. parse :: String -> expr parse expr = [(expr,string)] expr :: Parser value expr = do t <- term do char '+' e <- expr return Add (Val t)(Val e) +++ return t (+++) :: Parser a -> Parser a -> Parser a t +++ w inp = case t inp of [] -> w inp [(v,out)] -> [(v,out)] This is what I mean by item fail and symbol type Parser s a = [s] -> [(a,[s])] item [] = [] item (c:cs) = [(c,cs)] pFail :: Parser s a pFail = \cs -> [] pSymbol :: Eq s => s -> Parser s s pSymbol a (b:bs) |a == b = [(b,bs)] |otherwise = [] I know this is a bit of a mess, but could someone explain where I should start and if I should use any of the code above. Also to point out I want to write the complete parser without using prelude and other built in functions as I will be changing as I go. John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091227/66c806cd/attachment.html From stephen.tetley at gmail.com Sun Dec 27 14:11:24 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sun Dec 27 13:44:50 2009 Subject: [Haskell-beginners] parser for expressions In-Reply-To: <4f7ad1ad0912271010w10331434ne6958521fcce2342@mail.gmail.com> References: <4f7ad1ad0912271010w10331434ne6958521fcce2342@mail.gmail.com> Message-ID: <5fdc56d70912271111k492aa21bl835e9c633a3afe4f@mail.gmail.com> Hi John Are you working from the "Monadic Parser Combinators" paper by Graham Hutton and Erik Meijer? That was written for Gofer a predecessor to Haskell which is similar Haskell but has some slight differences - particularly in Haskell you would really want to make the Parser a newtype then use can make a Monad instance. Here are some of the bits from that paper with the newtype for Parser - unfortunately it adds some clutter. I think there should be a full version converted to Haskell if you do a web search. You will certainly need the sat and char parsers from the paper - I can post them later if you can't find them through a web search: newtype Parser s a = Parser { getParser :: [s] -> [(a,[s])] } result :: a -> Parser s a result v = Parser $ \inp -> [(v,inp)] bind :: Parser s a -> (a -> Parser s b) -> Parser s b p `bind` f = Parser $ \inp -> concat [ (getParser . f) v inp' | (v,inp') <- (getParser p) inp] instance Monad (Parser s) where return a = result a mf >>= k = mf `bind` k pFail :: Parser s a pFail = Parser $ \cs -> [] pSymbol :: Eq s => s -> Parser s s pSymbol a = Parser $ \inp -> case inp of (b:bs) | a == b -> [(b,bs)] _ -> [] (+++) :: Parser s a -> Parser s a -> Parser s a t +++ w = Parser $ \inp -> case (getParser t) inp of [] -> (getParser w) inp [(v,out)] -> [(v,out)] From mutilating.cauliflowers.stephen at blacksapphire.com Sun Dec 27 14:47:56 2009 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sun Dec 27 14:21:28 2009 Subject: [Haskell-beginners] Interrupting a thread In-Reply-To: References: Message-ID: <4B37B9EC.80109@blacksapphire.com> MVars are the lowest-level operation for this kind of thing in Haskell, and they're very fast. Anything can be done with MVars but in some cases you need extra worker threads (cheap in Haskell), and you may even need to kill threads (which is a safe operation in Haskell). CHP is higher level and designed for this sort of complexity, so you might want to look at that. I'll give you the answer I know, which is a low-level MVar answer. I have *not* tried compiling this code. import Control.Concurrent import Control.Concurrent.MVar import Data.Int import System.Time type Microseconds = Int64 getSystemTime :: IO Microseconds getSystemTime = do (TOD sec pico) <- getClockTime return $! (fromIntegral sec::Int64) * 1000000 + (fromIntegral pico::Int64) `div` 1000000 type Stack a = [a] -- or whatever type you want isEmpty :: Stack a -> Bool isEmpty [] = True isEmpty _ = False pop :: Stack a -> (a, Stack a) data ScheduleInput = ModifyStack (Stack -> Stack) | WaitFor Microseconds | Timeout never = maxBound :: Microseconds schedule :: MVar ScheduleInput -> MVar a -> Stack a -> IO () schedule inpVar wnVar stack = schedule_ never stack where schedule_ :: Microseconds -> Stack -> IO () schedule_ timeout stack = do now <- getSystemTime let tillTimeout = 0 `max` (timeout - now) if tillTimeout == 0 && not (isEmpty stack) then do let (val, stack') = pop stack putMVar wnVar (PopValue val) schedule never stack' else do inp <- takeMVarWithTimeout (fromIntegral tillTimeout) inpVar case inp of ModifyStack f -> schedule_ timeout (f stack) WaitFor t -> do now <- getSystemTime schedule (t+now) stack Timeout -> schedule timeout stack readMVarWithTimeout :: Int -> MVar ScheduleInput -> IO ScheduleInput readMVar timeoutUS inpVar = do tid <- forkIO $ do threadDelay timeoutUS putMVar inpVar Timeout inp <- takeMVar inpVar killThread tid return inp waitNotify :: MVar ScheduleInput -> MVar Int -> IO () waitNotify schInp wnInp = do val <- takeMVar wnInp ...notify... let t = .... putMVar schInp $ WaitFor t -- block input for the specified period main = do schVar <- newEmptyMVar wnVar <- newEmptyMVar forkIO $ schedule schVar wnVar [] forkIO $ waitNotify wnVar schVar ... -- Modify stack according to user input inside your main IO loop putMVar schVar $ ModifyStack $ \stack -> ... I'm sure this is not exactly what you want, but at least it illustrates how you can achieve anything you like by using MVars + extra worker threads + killing threads (useful for implementing timeouts). Steve Floptical Logic wrote: > Hi, > > I am new to concurrency in Haskell and I am having trouble > implementing the notion of interrupting a thread. > > In a new thread, call it waitNotify, I am trying to do the following: > pop a number from a stack, wait some number of seconds based on the > number popped from the stack, perform some notification, and repeat > until there are no more numbers in the stack at which point we wait > for a new number. > > These numbers will be supplied interactively by the user from main. > When the user supplies a new number, I want to interrupt whatever > waiting is happening in waitNotify, insert the number in the proper > position in the current stack, and resume waitNotify using the updated > stack. Note, here "stack" is just a generalization; it will likely > just be a list. > > What is the most idiomatic way to capture this sort of behavior in > Haskell? My two challenges are the notion of interrupting a thread, > and sharing and updating this stack between threads (main and > waitNotify). > > Thank you > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From stephen.tetley at gmail.com Sun Dec 27 15:07:45 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sun Dec 27 14:41:10 2009 Subject: [Haskell-beginners] parser for expressions In-Reply-To: <4f7ad1ad0912271010w10331434ne6958521fcce2342@mail.gmail.com> References: <4f7ad1ad0912271010w10331434ne6958521fcce2342@mail.gmail.com> Message-ID: <5fdc56d70912271207qd168bc1ia25f2a1b0cf08043@mail.gmail.com> Hi John Whilst this won't have the learning value of working through parser combinators yourself, here's code that uses Parsec 2 to do want you want. Its the code from page 12 of Daan Leijen's Parsec manual [1] except it builds a syntax tree of the expression rather than evaluates it. I modified it for a query on Haskell cafe today, but only posted it off list. Some formatting might get "lost in the mail" of course. [1] http://research.microsoft.com/en-us/um/people/daan/download/parsec/parsec.pdf Best wishes Stephen module ExprSyn where import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Expr runExpr :: String -> IO () runExpr str = case runParser expr () "nofile" str of Left err -> putStrLn "Error:" >> print err Right val -> print val demo1 = runExpr "1+1" data Expr = Mul Expr Expr | Div Expr Expr | Add Expr Expr | Sub Expr Expr | Val Integer deriving (Eq,Show) expr :: Parser Expr expr = buildExpressionParser table factor "expression" table :: [[Operator Char st Expr]] table = [[op "*" Mul AssocLeft, op "/" Div AssocLeft] ,[op "+" Add AssocLeft, op "-" Sub AssocLeft] ] where op s f assoc = Infix (do{ string s; return f}) assoc factor :: Parser Expr factor = do{ char '(' ; x <- expr ; char ')' ; return x } <|> number "simple expression" number :: Parser Expr number = do{ ds <- many1 digit ; return (Val $ read ds) } "number" From mutilating.cauliflowers.stephen at blacksapphire.com Sun Dec 27 15:56:51 2009 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sun Dec 27 15:30:21 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <200912261956.11617.jon@ffconsultancy.com> References: <200912232114.24493.jon@ffconsultancy.com> <694519c50912231622i370abc4ofc25e0adb275f4a1@mail.gmail.com> <4B364F51.10009@crsr.net> <200912261956.11617.jon@ffconsultancy.com> Message-ID: <4B37CA13.7050807@blacksapphire.com> Jon, Jon Harrop wrote: > This is something that concerns me. Lots of discussions of parallelism, > including the Haskell literature I have read, neglect this critical problem > of making sure that more time is spent doing useful work than spawning tasks > (sparks). How is this solved in Haskell? Do you just put magic numbers in > that work on the machine you're currently using? It is simply not true that Haskell literature neglects the question of spark granularity - this is very basic and is always covered. Read "Real World Haskell" (available free online). There's no 'magic number'. You must explicitly write your code to give the right granule size. I don't know the exact cost of sparking, but in my experience it is quite small - so - as long as your granule is doing *some* real work, it should speed up. Jon Harrop wrote: > The parallelism is obviously not obtaining any real speedup so something is > wrong. But can anyone fix it? I've spent a bit of time measuring parallel speedup on real commercial projects, and this is what I've found: 1. ghc-6.12 performs significantly better than ghc-6.10, and has now been released, therefore don't use ghc-6.10. 2. The defaults generally work better than giving huge heap sizes. Your -K100000000 - maximum heap size per thread - will either do nothing or cause an artificial slowdown (I have observed this with the minimum heap size option). Don't use it, unless experimentation proves it makes things better. 3. +RTS -s is well worth using. It breaks the time down into MUT (mutator) and GC (garbage collector). 4. MUT parallelization is excellent, but the parallel GC is not so good. If your code is GC-heavy it can spend around half of its time garbage collecting, which doesn't parallelize so well, and this eats into the speedup. 5. There seems to be a scalability problem with the parallel gc for larger numbers of cores (namely 8). I am guessing somewhat, but my experiments tend to confirm the issue raised in Simon Marlow's (the implementor of GHC parallelization) recent paper that it's to do with "stopping the world" for gc. If GHC's lack of perfection at this point in time makes Haskell "look bad" I don't mind. I am not selling anything, so the reader at least knows they're getting the truth. I see this as one of the great advantages of open source. Progress on GHC has been very rapid in the last couple of years, and so I know we'll continue to see the speed of GHC's parallelism improving in leaps and bounds. It's actually still quite a new area, considering the difficulty of some of the technical issues and how recent it is that multicores are widely available on consumer hardware. I know you OCaml/F# guys are making great progress too. Steve From legajid at free.fr Sun Dec 27 16:03:23 2009 From: legajid at free.fr (legajid) Date: Sun Dec 27 15:32:28 2009 Subject: [Haskell-beginners] Maybe and IO Message-ID: <4B37CB9B.3070008@free.fr> Hi, My purpose is to get data from the keyboard and return a maybe value, saying "nothing" if the data entered is invalid. I get a message "could'nt match expected IO Integer against inferred type maybe integer" on line x<- getdata Why should x be Maybe ? getdatanum is, but getdata is not. Is it possible to write only one function rather than 2 distinct ones ? Thanks for your help, Didier. Here's my code getdata :: IO Integer getdata=do x<-getLine let xn=read x ::Integer return xn getdatanum :: Maybe Integer getdatanum = do x <- getdata {- if x < 5 then do return (Just x) else do return Nothing -} return (Just x) From mutilating.cauliflowers.stephen at blacksapphire.com Sun Dec 27 16:05:44 2009 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sun Dec 27 15:39:13 2009 Subject: [Haskell-beginners] Maybe and IO In-Reply-To: <4B37CB9B.3070008@free.fr> References: <4B37CB9B.3070008@free.fr> Message-ID: <4B37CC28.6060702@blacksapphire.com> Didier, See below... legajid wrote: > Hi, > My purpose is to get data from the keyboard and return a maybe value, > saying "nothing" if the data entered is invalid. > I get a message "could'nt match expected IO Integer against inferred > type maybe integer" on line x<- getdata > Why should x be Maybe ? getdatanum is, but getdata is not. > > Is it possible to write only one function rather than 2 distinct ones ? > > Thanks for your help, > Didier. > > > Here's my code > > getdata :: IO Integer > getdata=do x<-getLine > let xn=read x ::Integer > return xn > > getdatanum :: Maybe Integer > getdatanum = do > x <- getdata > {- > if x < 5 > then do > return (Just x) > else do > return Nothing > -} > return (Just x) The type of getdatanum should be IO (Maybe Integer). Maybe and IO are both monads, and that's why the error messages can be a bit confusing sometimes. Yes, you certainly can write this as one function. Steve From byorgey at seas.upenn.edu Sun Dec 27 16:24:42 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Dec 27 15:58:06 2009 Subject: [Haskell-beginners] Enumerated types In-Reply-To: <4B3796AE.5040504@free.fr> References: <4B376458.7010809@free.fr> <4B3796AE.5040504@free.fr> Message-ID: <20091227212442.GA16335@seas.upenn.edu> On Sun, Dec 27, 2009 at 06:17:34PM +0100, legajid wrote: > Thanks. > > for 1, i tried mapM ( putStrLn) (show pref) but show gives only one line > with all values, instead of n lines with 1 value. I now understand that > show must be in the function that is mapped. Right, pref is a list so (show pref) will just give you a String representing the entire list. You can do (map show pref) to give you a list of Strings, one for each value. So you could write mapM_ putStrLn (map show pref) which is actually equivalent to mapM_ (putStrLn . show) pref -Brent From tom.davie at gmail.com Sun Dec 27 18:13:48 2009 From: tom.davie at gmail.com (Tom Davie) Date: Sun Dec 27 17:47:14 2009 Subject: [Haskell-beginners] Enumerated types In-Reply-To: <4B376458.7010809@free.fr> References: <4B376458.7010809@free.fr> Message-ID: <8b70a98a0912271513u16f27471o5f8be2a3979737a@mail.gmail.com> To add to what the other guys have said, I'd like to comment on style.. re 1 (disp_pref), it's much more compositional to split that function into two parts: the pure part: showPrefs = unlines . map show $ pref and the non pure part: putStrLn The reason that this is better is that a future function can manipulate the String that showPrefs produces ? it can append, it can drop characters from it, it can reverse it, etc... This is not true of what is left over after the action of printing the string has happened. It lets you reuse that function *much* more. Bob On Sun, Dec 27, 2009 at 1:42 PM, legajid wrote: > Hello, > > I have some trouble evaluating Enum class. > Following is my source: > > data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving > (Enum, Show) > > auths=[Buzzati .. Verne] ++ enumFrom Ray > pref=take 3 auths > -- 1 disp_pref=mapM_ (putStrLn) pref > > auth1 = Buzzati > auth2 = succ auth1 -- Werber > auth3 = pred Asimov -- Ray > num_auth4=fromEnum Verne -- 2 > -- 2 toEnum > > main= display Buzzati > display x = do > putStrLn (show x) > display (succ x) > -- 3 end of enum > > 1. could'nt match expected type [Char] against inferred type Authors > I would like to display each data constructor name on one line , giving : > Buzzati > Werber > Verne > How can i translate data from one type to another (Authors to [Char])? > > 2. Like fromEnum gives data constructor index, is it possible with toEnum > (or other way) to get the nth constructor of the given type ? > eg : 2 applied to Authors (not in scope ?) would give Verne > > 3. tried to take 'succ' of last tag in enumeration > How to detect the end of an enumeration ? Can i get the maxbound index ? > > Thanks, > Didier. > > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091227/07a6a65f/attachment.html From jon at ffconsultancy.com Sun Dec 27 22:19:58 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Sun Dec 27 20:39:05 2009 Subject: [Haskell-beginners] Performance of parallel mergesort In-Reply-To: <4B37CA13.7050807@blacksapphire.com> References: <200912232114.24493.jon@ffconsultancy.com> <200912261956.11617.jon@ffconsultancy.com> <4B37CA13.7050807@blacksapphire.com> Message-ID: <200912280319.58918.jon@ffconsultancy.com> On Sunday 27 December 2009 20:56:51 you wrote: > Jon Harrop wrote: > > This is something that concerns me. Lots of discussions of parallelism, > > including the Haskell literature I have read, neglect this critical > > problem > > of making sure that more time is spent doing useful work than spawning > > tasks > > (sparks). How is this solved in Haskell? Do you just put magic numbers in > > that work on the machine you're currently using? > > It is simply not true that Haskell literature neglects the question of > spark granularity - this is very basic and is always covered. Read > "Real World Haskell" (available free online). There's no 'magic > number'. You must explicitly write your code to give the right granule > size. There is no "right granule" size. That's the whole point: the optimum is a function of the machine. If you hardcode the granularity then your code isn't future proof and isn't portable. From chapter 24 of Real World Haskell on sorting: "At this fine granularity, the cost of using par outweighs any possible usefulness. To reduce this effect, we switch to our non-parallel sort after passing some threshold." From the Sorting.hs file, parSort2 accepts a threshold "d": parSort2 :: (Ord a) => Int -> [a] -> [a] parSort2 d list@(x:xs) | d <= 0 = sort list | otherwise = force greater `par` (force lesser `pseq` (lesser ++ x:greater)) where lesser = parSort2 d' [y | y <- xs, y < x] greater = parSort2 d' [y | y <- xs, y >= x] d' = d - 1 parSort2 _ _ = [] From the SortMain.hs file, it is always invoked with the magic number "2": testFunction = parSort2 2 Moreover, their approach of subdividing a fixed number of times is suboptimal because it inhibits load balancing. Later, about parallelized IO, they give the code: chunkedReadWith :: (NFData a) => ([LB.ByteString] -> a) -> FilePath -> IO a chunkedReadWith func path = withChunks (lineChunks (numCapabilities * 4)) func path where "4" is one magic number that gets multiplied by the magic number the user supplied via the +RTS -N command-line option. They make no attempt to adapt the granularity to the machine at all and rely entirely upon magic numbers. Consequently, their parallel sort that got a 25% speedup on two cores achieves a 30% slowdown on my 8 core. > I don't know the exact cost of sparking, but in my experience it > is quite small - so - as long as your granule is doing *some* real work, > it should speed up. Can you quantify it, e.g. How many FLOPS? > Jon Harrop wrote: > > The parallelism is obviously not obtaining any real speedup so something > > is wrong. But can anyone fix it? > > I've spent a bit of time measuring parallel speedup on real commercial > projects, and this is what I've found: > > 1. ghc-6.12 performs significantly better than ghc-6.10, and has now > been released, therefore don't use ghc-6.10. Ok. > 2. The defaults generally work better than giving huge heap sizes. Your > -K100000000 - maximum heap size per thread - will either do nothing or > cause an artificial slowdown (I have observed this with the minimum heap > size option). Don't use it, unless experimentation proves it makes > things better. On the contrary, the Haskell program dies without it: $ time ./mergesort +RTS -N8 Stack space overflow: current size 8388608 bytes. Use `+RTS -Ksize' to increase it. [1]+ Done kwrite mergesort.hs real 0m33.320s user 3m29.397s sys 0m0.592s I had to add that -K command line option just to get the program to run to completion. > 3. +RTS -s is well worth using. It breaks the time down into MUT > (mutator) and GC (garbage collector). Its says 78.5% GC time (with GHC 6.10). > 4. MUT parallelization is excellent, but the parallel GC is not so good. > If your code is GC-heavy it can spend around half of its time garbage > collecting, which doesn't parallelize so well, and this eats into the > speedup. Ok. > 5. There seems to be a scalability problem with the parallel gc for > larger numbers of cores (namely 8). I am guessing somewhat, but my > experiments tend to confirm the issue raised in Simon Marlow's (the > implementor of GHC parallelization) recent paper that it's to do with > "stopping the world" for gc. Do you mean this bug: http://hackage.haskell.org/trac/ghc/ticket/3553 > If GHC's lack of perfection at this point in time makes Haskell "look > bad" I don't mind. I am not selling anything, so the reader at least > knows they're getting the truth. I see this as one of the great > advantages of open source. I'm sure we'd all rather see speedups. :-) > Progress on GHC has been very rapid in the last couple of years, and so > I know we'll continue to see the speed of GHC's parallelism improving in > leaps and bounds. It's actually still quite a new area, considering the > difficulty of some of the technical issues and how recent it is that > multicores are widely available on consumer hardware. My original intent was to test a claim someone made: that mergesort in Haskell is competitively performant and trivially parallelized. > I know you OCaml/F# guys are making great progress too. F# is production ready but OCaml is dead in the water when it comes to multicore. I'm working on an OCaml replacement called HLVM but it is early days yet. -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From dima at simonchik.net Mon Dec 28 01:40:25 2009 From: dima at simonchik.net (Dmitry Simonchik) Date: Mon Dec 28 01:14:10 2009 Subject: [Haskell-beginners] Problems with EclipseFP In-Reply-To: <1261344193.5673.1.camel@picard> References: <1261344193.5673.1.camel@picard> Message-ID: <80eb7b2e0912272240y7e2fcd9ep5a3270c56b9d8a71@mail.gmail.com> Hi I installed eclipseFP just a couple of days ago. Everything seems to work fine for me. I just followed instructions on eclipseFP homepage. Now my Eclipse recognizes hs files and does correct syntax higlighting and is able to report compilation errors on file save. But actually after 10 mins of exploration I decided to switch back to my previous editor (Kate) as it is more usefull for me :) On Mon, Dec 21, 2009 at 12:23 AM, Maciej Piechotka wrote: > Did anyone used eclipsefp? I installed version 2 but I didn't change > anything in eclipse (I haven't notice a difference - it does not > recognise .hs file, nothing about haskell in help/new project/new file > etc.). > > Regards > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091228/c6239a58/attachment.html From daniel.is.fischer at web.de Mon Dec 28 03:56:35 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 28 03:31:32 2009 Subject: [Haskell-beginners] Problems with EclipseFP In-Reply-To: <80eb7b2e0912272240y7e2fcd9ep5a3270c56b9d8a71@mail.gmail.com> References: <1261344193.5673.1.camel@picard> <80eb7b2e0912272240y7e2fcd9ep5a3270c56b9d8a71@mail.gmail.com> Message-ID: <200912280956.36126.daniel.is.fischer@web.de> Am Monday 28 December 2009 07:40:25 schrieben Sie: > But actually after 10 mins of exploration I decided to switch back to my > previous editor (Kate) as it is more usefull for me :) Best IDE I know, Kate/Kwrite + ghci :D I occasionally try something else (emacs+haskell-mode, leksah) but I always return soon. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091228/ab84b084/attachment.html From amy at nualeargais.ie Mon Dec 28 12:14:53 2009 From: amy at nualeargais.ie (=?ISO-8859-1?Q?Amy_de_Buitl=E9ir?=) Date: Mon Dec 28 11:48:21 2009 Subject: [Haskell-beginners] I need advice on design Message-ID: <77b28c350912280914o7f94b88emeb15b3f0f93c4370@mail.gmail.com> I'm building a library of components for artificial neural networks. I'm used to object-oriented languages, so I'm struggling a bit to figure out how to do a good design in a functional programming language like Haskell. Q1: I've come up with two designs, and would appreciate any advice on improvements and what approach to take. ===== Design #1 ===== class Neuron n where activate :: [Double] -> n -> Double train :: [Double] -> Double -> n -> n ...and then I would have instances of this typeclass. For example: data Perceptron = Perceptron { weights :: [Double], threshold :: Double, learningRate :: Double } deriving (Show) instance Neuron Perceptron where activate inputs perceptron = ... train inputs target perceptron = ... The disadvantage of this approach is that I need to define and name each instance of neuron before I can use it. I'd rather create a neuron on-the-fly by calling a general-purpose constructor and telling it what functions to use for activation and training. I think that would make it easier to re-use activation and training functions in all sorts of different combinations. So I came up with... ===== Design #2 ===== data Neuron = Neuron { weights :: [Double], activate :: [Double] -> Double, train :: [Double] -> Double -> Neuron } Q2: I thought there might be some way to define a function type, but the following doesn't work. Is there something along these lines that would work? type activationFunction = [Double] -> Double From byorgey at seas.upenn.edu Mon Dec 28 12:43:08 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Dec 28 12:16:29 2009 Subject: [Haskell-beginners] I need advice on design In-Reply-To: <77b28c350912280914o7f94b88emeb15b3f0f93c4370@mail.gmail.com> References: <77b28c350912280914o7f94b88emeb15b3f0f93c4370@mail.gmail.com> Message-ID: <20091228174308.GA1014@seas.upenn.edu> On Mon, Dec 28, 2009 at 05:14:53PM +0000, Amy de Buitl?ir wrote: > I'm building a library of components for artificial neural networks. > I'm used to object-oriented languages, so I'm struggling a bit to > figure out how to do a good design in a functional programming > language like Haskell. > > Q1: I've come up with two designs, and would appreciate any advice on > improvements and what approach to take. > > ===== Design #1 ===== > class Neuron n where > activate :: [Double] -> n -> Double > train :: [Double] -> Double -> n -> n Looks reasonable. > The disadvantage of this approach is that I need to define and name > each instance of neuron before I can use it. I'd rather create a > neuron on-the-fly by calling a general-purpose constructor and telling > it what functions to use for activation and training. Indeed, if you want to create new types of neurons on-the-fly you should use your second design. > ===== Design #2 ===== > data Neuron = > Neuron { > weights :: [Double], > activate :: [Double] -> Double, > train :: [Double] -> Double -> Neuron > } Mostly makes sense. Note that this is really making explicit what the type class mechanism is doing -- a type class instance corresponds to a "dictionary", a record of type class methods, which is implcitly passed around. Here you are just explicitly declaring a dictionary type for neurons. The one thing that confuses me is why you included "weights" in the explicit dictionary but not in the Neuron type class. I would think you'd want it in both or neither, I don't see any reason you'd need it in one but not the other. > Q2: I thought there might be some way to define a function type, but > the following doesn't work. Is there something along these lines that > would work? > > type activationFunction = [Double] -> Double Type names must start with an uppercase letter. type ActivationFunction = [Double] -> Double should work just fine. -Brent From daniel.is.fischer at web.de Mon Dec 28 13:10:12 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 28 12:45:35 2009 Subject: [Haskell-beginners] I need advice on design In-Reply-To: <77b28c350912280914o7f94b88emeb15b3f0f93c4370@mail.gmail.com> References: <77b28c350912280914o7f94b88emeb15b3f0f93c4370@mail.gmail.com> Message-ID: <200912281910.13503.daniel.is.fischer@web.de> Am Montag 28 Dezember 2009 18:14:53 schrieb Amy de Buitl?ir: > I'm building a library of components for artificial neural networks. > I'm used to object-oriented languages, so I'm struggling a bit to > figure out how to do a good design in a functional programming > language like Haskell. I can't say what design would be best to implement neural networks in Haskell, but > Q2: I thought there might be some way to define a function type, but > the following doesn't work. Is there something along these lines that > would work? > > type activationFunction = [Double] -> Double if the type name starts with a lower case letter, it's a type variable, so you'd want type ActivationFunction = [Double] -> Double -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091228/0a6ced2f/attachment.html From evas at mountaincable.net Mon Dec 28 14:58:39 2009 From: evas at mountaincable.net (Chris Saunders) Date: Mon Dec 28 14:32:26 2009 Subject: [Haskell-beginners] Advice on what to install Message-ID: <0FA52975B01F4A4687563947BB4423CD@chrisPC> I noticed the availability of Haskell Platform 2009.2.0.2 and did install this and when I run GHCi it says that its version is 6.10.4. Now on the GHC site I notice that the current version is 6.12. Should I have installed this more recent version or stick with what I have? Warning: many more dumb questions to come from this guy. Regards Chris Saunders -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091228/e95cbf45/attachment.html From ehamberg at gmail.com Mon Dec 28 15:04:09 2009 From: ehamberg at gmail.com (Erlend Hamberg) Date: Mon Dec 28 14:38:02 2009 Subject: [Haskell-beginners] Advice on what to install In-Reply-To: <0FA52975B01F4A4687563947BB4423CD@chrisPC> References: <0FA52975B01F4A4687563947BB4423CD@chrisPC> Message-ID: <200912282104.18528.ehamberg@gmail.com> On Monday 28. December 2009 20.58.39 Chris Saunders wrote: > Now on the GHC site I notice that the current version is 6.12. Should I > have installed this more recent version or stick with what I have? Stick with what you have. A new version of the Haskell Platform based on the new GHC version won't be out for some time. Welcome! :) -- Erlend Hamberg "Everything will be ok in the end. If its not ok, its not the end." GPG/PGP: 0xAD3BCF19 45C3 E2E7 86CA ADB7 8DAD 51E7 3A1A F085 AD3B CF19 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part. Url : http://www.haskell.org/pipermail/beginners/attachments/20091228/0ca066b4/attachment-0001.bin From xf27 at arcor.de Mon Dec 28 15:02:47 2009 From: xf27 at arcor.de (=?iso-8859-1?Q?Thomas_H=FChn?=) Date: Mon Dec 28 14:38:27 2009 Subject: [Haskell-beginners] Re: Advice on what to install References: <0FA52975B01F4A4687563947BB4423CD@chrisPC> Message-ID: <86d41y3lzs.fsf@arcor.de> "Chris Saunders" writes: > I noticed the availability of Haskell Platform > 2009.2.0.2 and did install this and when I run GHCi it says that its version is > 6.10.4. Now on the GHC site I notice that the current version is > 6.12. Should I have installed this more recent version or stick with > what I have? Warning: many more dumb questions to come from this > guy. Stick with the Haskell Platform. But if you don't and you actually manage to get not only GHC, but also cabal-install (including all prerequisites) running on Windows without much prior knowledge, make sure to write it up and tell me how to do it. Thomas From mutilating.cauliflowers.stephen at blacksapphire.com Mon Dec 28 15:09:53 2009 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Mon Dec 28 14:43:22 2009 Subject: [Haskell-beginners] Advice on what to install In-Reply-To: <0FA52975B01F4A4687563947BB4423CD@chrisPC> References: <0FA52975B01F4A4687563947BB4423CD@chrisPC> Message-ID: <4B391091.3010600@blacksapphire.com> Chris, Whatever ships with the platform is usually best. ghc-6.10 is very stable, but ghc-6.12 has only just been released and so some libraries on hackage don't work with it yet. So, 6.10.4 is the best version to use at the moment. Welcome to the list - please ask away, and I hope you have fun learning Haskell! Steve Chris Saunders wrote: > I noticed the availability of Haskell Platform 2009.2.0.2 and did > install this and when I run GHCi it says that its version is 6.10.4. > Now on the GHC site I notice that the current version is 6.12. Should I > have installed this more recent version or stick with what I have? > Warning: many more dumb questions to come from this guy. > > Regards > Chris Saunders > > > ------------------------------------------------------------------------ > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From evas at mountaincable.net Mon Dec 28 15:44:31 2009 From: evas at mountaincable.net (Chris Saunders) Date: Mon Dec 28 15:18:18 2009 Subject: [Haskell-beginners] Re: Advice on what to install In-Reply-To: <86d41y3lzs.fsf@arcor.de> References: <0FA52975B01F4A4687563947BB4423CD@chrisPC> <86d41y3lzs.fsf@arcor.de> Message-ID: <97C70A2543874C4E8429B3B4CF8F4A35@chrisPC> All the advice I received suggests that I stick with the Haskell Platform so I don't think I will attempt to install GHC 6.12 or cabal. I actually don't even really know what the Haskell Platform is - perhaps you could shed some light? Regards Chris Saunders ----- Original Message ----- From: "Thomas H?hn" To: Sent: Monday, December 28, 2009 3:02 PM Subject: [Haskell-beginners] Re: Advice on what to install > "Chris Saunders" writes: > >> I noticed the availability of Haskell Platform >> 2009.2.0.2 and did install this and when I run GHCi it says that its >> version is >> 6.10.4. Now on the GHC site I notice that the current version is >> 6.12. Should I have installed this more recent version or stick with >> what I have? Warning: many more dumb questions to come from this >> guy. > > Stick with the Haskell Platform. > > But if you don't and you actually manage to get not only GHC, but also > cabal-install (including all prerequisites) running on Windows without > much prior knowledge, make sure to write it up and tell me how to do > it. > > Thomas > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From legajid at free.fr Mon Dec 28 17:37:53 2009 From: legajid at free.fr (legajid) Date: Mon Dec 28 17:06:54 2009 Subject: [Haskell-beginners] Ghci & wxhaskell Message-ID: <4B393341.2010707@free.fr> Hello, i've downloaded and installed wshaskell (GUI for windows). All messages are ok. Running an example program, the dll cannot be found. Below are the messages when i type : ghci -package wx : GHCi, version 6.10.4: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer ... linking ... done. Loading package base ... linking ... done. Loading package syb ... linking ... done. Loading package array-0.2.0.0 ... linking ... done. Loading package containers-0.2.0.1 ... linking ... done. Loading package bytestring-0.9.1.4 ... linking ... done. Loading package Win32-2.2.0.0 ... linking ... done. Loading package filepath-1.1.0.2 ... linking ... done. Loading package old-locale-1.0.0.1 ... linking ... done. Loading package old-time-1.0.0.2 ... linking ... done. Loading package directory-1.0.0.3 ... linking ... done. Loading package process-1.0.1.1 ... linking ... done. Loading package random-1.0.0.1 ... linking ... done. Loading package haskell98 ... linking ... done. Loading package stm-2.1.1.2 ... linking ... done. Loading package wxcore-0.11.1.2 ... : can't load .so/.DLL for: wxc-msw2.8.10-0.11.1.2 (addDLL: could not load DLL) : wxc-msw2.8.10-0.11.1.2: Cette application n'a pas pu d?marrer car la configuration de l'application est incorrecte. R?installer l'application pourrait r?soudre ce probl?me. (application couldn' start because configuration is incorrect. Reinstall could solve this problem) wxc-msw2.8.10-0.11.1.2.dll has been copied to windows\system32 (windows XP) Can someone help for this installation issue? Thanks, Didier From byorgey at seas.upenn.edu Mon Dec 28 19:54:34 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Dec 28 19:27:54 2009 Subject: [Haskell-beginners] Re: Advice on what to install In-Reply-To: <97C70A2543874C4E8429B3B4CF8F4A35@chrisPC> References: <0FA52975B01F4A4687563947BB4423CD@chrisPC> <86d41y3lzs.fsf@arcor.de> <97C70A2543874C4E8429B3B4CF8F4A35@chrisPC> Message-ID: <20091229005434.GA11520@seas.upenn.edu> On Mon, Dec 28, 2009 at 03:44:31PM -0500, Chris Saunders wrote: > All the advice I received suggests that I stick with the Haskell Platform > so I don't think I will attempt to install GHC 6.12 or cabal. I actually > don't even really know what the Haskell Platform is - perhaps you could > shed some light? The Haskell Platform is a compiler along with a blessed set of standard libraries and tools (e.g. cabal-install) which are stable and have all been tested to work together---all with a convenient one-step downloader/installer. If you didn't use the Platform then you'd have to install all of these things yourself, separately. -Brent From hectorg87 at gmail.com Tue Dec 29 22:58:08 2009 From: hectorg87 at gmail.com (Hector Guilarte) Date: Tue Dec 29 22:32:49 2009 Subject: [Haskell-beginners] I need advice on design In-Reply-To: <77b28c350912280914o7f94b88emeb15b3f0f93c4370@mail.gmail.com> References: <77b28c350912280914o7f94b88emeb15b3f0f93c4370@mail.gmail.com> Message-ID: <890881128-1262145566-cardhu_decombobulator_blackberry.rim.net-1149495901-@bda567.bisx.prod.on.blackberry> Sorry for my late answer... Check this e-mail wren ng thornton sent to me (and the list) on Nov 5, 2009. Sorry I'm not giving you the direct address to the whole discusion, but I'm sending you this from my cellphone, and the e-mail too... The original discusion was on the haskell-cafe mailing list and the title was: Memory Leak - Artificial Neural Network Also, there's a package somebody uploaded a few days ago to hackage on ann's, it is called: hnn-0.1, a haskell neural network library. I hope this can be usefull to you. Hector Guilarte Here's wren ng thornton e-mail: As a more general high-level suggestion, the most efficient way to implement feedforward ANNs is to treat them as matrix multiplication problems and use matrices/arrays rather than lists. For a three layer network of N, M, and O nodes we thus: * start with an N-wide vector of inputs * multiply by the N*M matrix of weights, to get an M-vector * map sigmoid or other activation function * multiply by the M*O matrix of weights for the next layer to get an O-vector * apply some interpretation (e.g. winner-take-all) to the output There are various libraries for optimized matrix multiplication, but even just using an unboxed array for the matrices will make it much faster to traverse through things. -----Original Message----- From: Amy de Buitl?ir Date: Mon, 28 Dec 2009 17:14:53 To: Subject: [Haskell-beginners] I need advice on design I'm building a library of components for artificial neural networks. I'm used to object-oriented languages, so I'm struggling a bit to figure out how to do a good design in a functional programming language like Haskell. Q1: I've come up with two designs, and would appreciate any advice on improvements and what approach to take. ===== Design #1 ===== class Neuron n where activate :: [Double] -> n -> Double train :: [Double] -> Double -> n -> n ....and then I would have instances of this typeclass. For example: data Perceptron = Perceptron { weights :: [Double], threshold :: Double, learningRate :: Double } deriving (Show) instance Neuron Perceptron where activate inputs perceptron = ... train inputs target perceptron = ... The disadvantage of this approach is that I need to define and name each instance of neuron before I can use it. I'd rather create a neuron on-the-fly by calling a general-purpose constructor and telling it what functions to use for activation and training. I think that would make it easier to re-use activation and training functions in all sorts of different combinations. So I came up with... ===== Design #2 ===== data Neuron = Neuron { weights :: [Double], activate :: [Double] -> Double, train :: [Double] -> Double -> Neuron } Q2: I thought there might be some way to define a function type, but the following doesn't work. Is there something along these lines that would work? type activationFunction = [Double] -> Double _______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners From flopticalogic at gmail.com Wed Dec 30 19:08:39 2009 From: flopticalogic at gmail.com (Floptical Logic) Date: Wed Dec 30 18:41:54 2009 Subject: [Haskell-beginners] Interrupting a thread In-Reply-To: <4B37B9EC.80109@blacksapphire.com> References: <4B37B9EC.80109@blacksapphire.com> Message-ID: On Sun, Dec 27, 2009 at 1:47 PM, Stephen Blackheath [to Haskell-Beginners] wrote: > MVars are the lowest-level operation for this kind of thing in Haskell, > and they're very fast. Anything can be done with MVars but in some cases > you need extra worker threads (cheap in Haskell), and you may even need > to kill threads (which is a safe operation in Haskell). ?CHP is higher > level and designed for this sort of complexity, so you might want to > look at that. ?I'll give you the answer I know, which is a low-level > MVar answer. > > I have *not* tried compiling this code. > > > import Control.Concurrent > import Control.Concurrent.MVar > import Data.Int > import System.Time > > type Microseconds = Int64 > > getSystemTime :: IO Microseconds > getSystemTime = do > ? ?(TOD sec pico) <- getClockTime > ? ?return $! > ? ? ? ?(fromIntegral sec::Int64) * 1000000 + > ? ? ? ?(fromIntegral pico::Int64) `div` 1000000 > > type Stack a = [a] ?-- or whatever type you want > > isEmpty :: Stack a -> Bool > isEmpty [] = True > isEmpty _ = False > > pop :: Stack a -> (a, Stack a) > > data ScheduleInput = ModifyStack (Stack -> Stack) | WaitFor Microseconds > | Timeout > > never = maxBound :: Microseconds > > schedule :: MVar ScheduleInput -> MVar a -> Stack a -> IO () > schedule inpVar wnVar stack = schedule_ never stack > ?where > ? ?schedule_ :: Microseconds -> Stack -> IO () > ? ?schedule_ timeout stack = do > ? ? ? ?now <- getSystemTime > ? ? ? ?let tillTimeout = 0 `max` (timeout - now) > ? ? ? ?if tillTimeout == 0 && not (isEmpty stack) then do > ? ? ? ? ? ?let (val, stack') = pop stack > ? ? ? ? ? ?putMVar wnVar (PopValue val) > ? ? ? ? ? ?schedule never stack' > ? ? ? ? ?else do > ? ? ? ? ? ?inp <- takeMVarWithTimeout (fromIntegral tillTimeout) inpVar > ? ? ? ? ? ?case inp of > ? ? ? ? ? ? ? ?ModifyStack f -> schedule_ timeout (f stack) > ? ? ? ? ? ? ? ?WaitFor t ? ? ? ?-> do > ? ? ? ? ? ? ? ? ? ?now <- getSystemTime > ? ? ? ? ? ? ? ? ? ?schedule (t+now) stack > ? ? ? ? ? ? ? ?Timeout ? ? ? ?-> schedule timeout stack > > readMVarWithTimeout :: Int -> MVar ScheduleInput -> IO ScheduleInput > readMVar timeoutUS inpVar = do > ? ?tid <- forkIO $ do > ? ? ? ?threadDelay timeoutUS > ? ? ? ?putMVar inpVar Timeout > ? ?inp <- takeMVar inpVar > ? ?killThread tid > ? ?return inp > > waitNotify :: MVar ScheduleInput -> MVar Int -> IO () > waitNotify schInp wnInp = do > ? ?val <- takeMVar wnInp > ? ?...notify... > ? ?let t = .... > ? ?putMVar schInp $ WaitFor t ?-- block input for the specified period > > main = do > ? ?schVar <- newEmptyMVar > ? ?wnVar <- newEmptyMVar > ? ?forkIO $ schedule schVar wnVar [] > ? ?forkIO $ waitNotify wnVar schVar > ? ?... > ? ?-- Modify stack according to user input inside your main IO loop > ? ?putMVar schVar $ ModifyStack $ \stack -> ... > > > I'm sure this is not exactly what you want, but at least it illustrates > how you can achieve anything you like by using MVars + extra worker > threads + killing threads (useful for implementing timeouts). > > > Steve > > Floptical Logic wrote: >> Hi, >> >> I am new to concurrency in Haskell and I am having trouble >> implementing the notion of interrupting a thread. >> >> In a new thread, call it waitNotify, I am trying to do the following: >> pop a number from a stack, wait some number of seconds based on the >> number popped from the stack, perform some notification, and repeat >> until there are no more numbers in the stack at which point we wait >> for a new number. >> >> These numbers will be supplied interactively by the user from main. >> When the user supplies a new number, I want to interrupt whatever >> waiting is happening in waitNotify, insert the number in the proper >> position in the current stack, and resume waitNotify using the updated >> stack. ?Note, here "stack" is just a generalization; it will likely >> just be a list. >> >> What is the most idiomatic way to capture this sort of behavior in >> Haskell? ?My two challenges are the notion of interrupting a thread, >> and sharing and updating this stack between threads (main and >> waitNotify). >> >> Thank you >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > Thanks Stephen. That worked and things are starting to make more sense. The crux of it all was the readMVarWithTimeout function which does exactly what I want. Now I want to extend this a bit further to use StateT. I've modified the schedule function quite a bit, and now it has type schedule :: StateT MyState IO. I keep the MVar actVar in MyState as well the list (stack) of wait times. However, the type of forkIO is forkIO :: IO () -> IO ThreadId. How do I fork a new thread for schedule even though it is wrapped in the State monad? Thanks again. From joe at fixieconsulting.com Wed Dec 30 20:49:12 2009 From: joe at fixieconsulting.com (Joe Van Dyk) Date: Wed Dec 30 20:22:46 2009 Subject: [Haskell-beginners] Global variable question Message-ID: What's the appropriate way to write this in Haskell? # Ruby code, ignore the thread-unsafety for now. class Ticker @@tick = 0 def self.update! @@tick += 1 end def self.current return @@tick end end Ticker.update! # 1 Ticker.update! # 2 Ticker.current # 2 -- Joe Van Dyk http://fixieconsulting.com From byorgey at seas.upenn.edu Wed Dec 30 20:59:52 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Wed Dec 30 20:33:06 2009 Subject: [Haskell-beginners] Global variable question In-Reply-To: References: Message-ID: <20091231015951.GA27025@seas.upenn.edu> On Wed, Dec 30, 2009 at 05:49:12PM -0800, Joe Van Dyk wrote: > What's the appropriate way to write this in Haskell? > > # Ruby code, ignore the thread-unsafety for now. > class Ticker > @@tick = 0 > def self.update! > @@tick += 1 > end > def self.current > return @@tick > end > end > > Ticker.update! # 1 > Ticker.update! # 2 > Ticker.current # 2 If you really want a global ticker, use the State monad: tick :: State Int () tick = modify (+1) -- increment the counter twice then return its new value mainStuff :: State Int Int mainStuff = tick >> tick >> get -Brent From ezyang at MIT.EDU Wed Dec 30 21:05:34 2009 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Wed Dec 30 20:39:04 2009 Subject: [Haskell-beginners] Global variable question In-Reply-To: References: Message-ID: <1262224821-sup-6648@ezyang> Excerpts from Joe Van Dyk's message of Wed Dec 30 20:49:12 -0500 2009: > What's the appropriate way to write this in Haskell? Hi Joe, The Ticker class is an example of stateful computation, which we try to avoid in Haskell. What are you really trying to do? * If you a number, and you want to add to it, (+1) works plenty well. * If you are going to be making ticks, but you don't care about reading the ticks until the end of the computation, the Writer monad is of interest. * If you need to update the tick count and read it, the State monad is a good bet. * If you're interested in curiosities from imperative land, STRef, IORef and other similar creatures may be helpful. Cheers, Edward From heringtonlacey at mindspring.com Thu Dec 31 02:21:02 2009 From: heringtonlacey at mindspring.com (Dean Herington) Date: Thu Dec 31 01:54:25 2009 Subject: [Haskell-beginners] Interrupting a thread In-Reply-To: References: <4B37B9EC.80109@blacksapphire.com> Message-ID: At 6:08 PM -0600 12/30/09, Floptical Logic wrote: >On Sun, Dec 27, 2009 at 1:47 PM, Stephen Blackheath [to >Haskell-Beginners] >wrote: >> MVars are the lowest-level operation for this kind of thing in Haskell, >> and they're very fast. Anything can be done with MVars but in some cases >> you need extra worker threads (cheap in Haskell), and you may even need >> to kill threads (which is a safe operation in Haskell). CHP is higher >> level and designed for this sort of complexity, so you might want to >> look at that. I'll give you the answer I know, which is a low-level >> MVar answer. >> >> I have *not* tried compiling this code. >> >> >> import Control.Concurrent >> import Control.Concurrent.MVar >> import Data.Int >> import System.Time >> >> type Microseconds = Int64 >> >> getSystemTime :: IO Microseconds >> getSystemTime = do >> (TOD sec pico) <- getClockTime >> return $! >> (fromIntegral sec::Int64) * 1000000 + >> (fromIntegral pico::Int64) `div` 1000000 >> >> type Stack a = [a] -- or whatever type you want >> >> isEmpty :: Stack a -> Bool >> isEmpty [] = True >> isEmpty _ = False >> >> pop :: Stack a -> (a, Stack a) >> >> data ScheduleInput = ModifyStack (Stack -> Stack) | WaitFor Microseconds >> | Timeout >> >> never = maxBound :: Microseconds >> >> schedule :: MVar ScheduleInput -> MVar a -> Stack a -> IO () >> schedule inpVar wnVar stack = schedule_ never stack >> where >> schedule_ :: Microseconds -> Stack -> IO () >> schedule_ timeout stack = do >> now <- getSystemTime >> let tillTimeout = 0 `max` (timeout - now) >> if tillTimeout == 0 && not (isEmpty stack) then do >> let (val, stack') = pop stack >> putMVar wnVar (PopValue val) >> schedule never stack' >> else do >> inp <- takeMVarWithTimeout (fromIntegral tillTimeout) inpVar >> case inp of >> ModifyStack f -> schedule_ timeout (f stack) >> WaitFor t -> do >> now <- getSystemTime >> schedule (t+now) stack >> Timeout -> schedule timeout stack >> >> readMVarWithTimeout :: Int -> MVar ScheduleInput -> IO ScheduleInput >> readMVar timeoutUS inpVar = do >> tid <- forkIO $ do >> threadDelay timeoutUS >> putMVar inpVar Timeout >> inp <- takeMVar inpVar >> killThread tid >> return inp >> >> waitNotify :: MVar ScheduleInput -> MVar Int -> IO () >> waitNotify schInp wnInp = do >> val <- takeMVar wnInp >> ...notify... >> let t = .... >> putMVar schInp $ WaitFor t -- block input for the specified period >> >> main = do >> schVar <- newEmptyMVar >> wnVar <- newEmptyMVar >> forkIO $ schedule schVar wnVar [] >> forkIO $ waitNotify wnVar schVar >> ... >> -- Modify stack according to user input inside your main IO loop >> putMVar schVar $ ModifyStack $ \stack -> ... >> >> >> I'm sure this is not exactly what you want, but at least it illustrates >> how you can achieve anything you like by using MVars + extra worker >> threads + killing threads (useful for implementing timeouts). >> >> >> Steve >> >> Floptical Logic wrote: >>> Hi, >>> >>> I am new to concurrency in Haskell and I am having trouble >>> implementing the notion of interrupting a thread. >>> >>> In a new thread, call it waitNotify, I am trying to do the following: >>> pop a number from a stack, wait some number of seconds based on the >>> number popped from the stack, perform some notification, and repeat >>> until there are no more numbers in the stack at which point we wait >>> for a new number. >>> >>> These numbers will be supplied interactively by the user from main. >>> When the user supplies a new number, I want to interrupt whatever >>> waiting is happening in waitNotify, insert the number in the proper > >> position in the current stack, and resume waitNotify using the updated >>> stack. Note, here "stack" is just a generalization; it will likely >>> just be a list. >>> >>> What is the most idiomatic way to capture this sort of behavior in >>> Haskell? My two challenges are the notion of interrupting a thread, >>> and sharing and updating this stack between threads (main and >>> waitNotify). >>> >>> Thank you >>> _______________________________________________ >>> Beginners mailing list >>> Beginners@haskell.org >>> http://www.haskell.org/mailman/listinfo/beginners >>> >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > >Thanks Stephen. That worked and things are starting to make more >sense. The crux of it all was the readMVarWithTimeout function which >does exactly what I want. > >Now I want to extend this a bit further to use StateT. I've modified >the schedule function quite a bit, and now it has type schedule :: >StateT MyState IO. I keep the MVar actVar in MyState as well the list >(stack) of wait times. However, the type of forkIO is forkIO :: IO () >-> IO ThreadId. How do I fork a new thread for schedule even though >it is wrapped in the State monad? > >Thanks again. You'll want something like this: myFork :: StateT MyState IO () -> MyState -> StateT MyState IO ThreadId myFork action initialState = liftIO (forkIO (evalStateT action initialState)) Dean From flopticalogic at gmail.com Thu Dec 31 03:21:33 2009 From: flopticalogic at gmail.com (Floptical Logic) Date: Thu Dec 31 02:54:47 2009 Subject: [Haskell-beginners] Interrupting a thread In-Reply-To: References: <4B37B9EC.80109@blacksapphire.com> Message-ID: On Thu, Dec 31, 2009 at 1:21 AM, Dean Herington wrote: > At 6:08 PM -0600 12/30/09, Floptical Logic wrote: >> >> On Sun, Dec 27, 2009 at 1:47 PM, Stephen Blackheath [to >> Haskell-Beginners] >> wrote: >>> >>> ?MVars are the lowest-level operation for this kind of thing in Haskell, >>> ?and they're very fast. Anything can be done with MVars but in some cases >>> ?you need extra worker threads (cheap in Haskell), and you may even need >>> ?to kill threads (which is a safe operation in Haskell). ?CHP is higher >>> ?level and designed for this sort of complexity, so you might want to >>> ?look at that. ?I'll give you the answer I know, which is a low-level >>> ?MVar answer. >>> >>> ?I have *not* tried compiling this code. >>> >>> >>> ?import Control.Concurrent >>> ?import Control.Concurrent.MVar >>> ?import Data.Int >>> ?import System.Time >>> >>> ?type Microseconds = Int64 >>> >>> ?getSystemTime :: IO Microseconds >>> ?getSystemTime = do >>> ? ?(TOD sec pico) <- getClockTime >>> ? ?return $! >>> ? ? ? ?(fromIntegral sec::Int64) * 1000000 + >>> ? ? ? ?(fromIntegral pico::Int64) `div` 1000000 >>> >>> ?type Stack a = [a] ?-- or whatever type you want >>> >>> ?isEmpty :: Stack a -> Bool >>> ?isEmpty [] = True >>> ?isEmpty _ = False >>> >>> ?pop :: Stack a -> (a, Stack a) >>> >>> ?data ScheduleInput = ModifyStack (Stack -> Stack) | WaitFor Microseconds >>> ?| Timeout >>> >>> ?never = maxBound :: Microseconds >>> >>> ?schedule :: MVar ScheduleInput -> MVar a -> Stack a -> IO () >>> ?schedule inpVar wnVar stack = schedule_ never stack >>> ?where >>> ? ?schedule_ :: Microseconds -> Stack -> IO () >>> ? ?schedule_ timeout stack = do >>> ? ? ? ?now <- getSystemTime >>> ? ? ? ?let tillTimeout = 0 `max` (timeout - now) >>> ? ? ? ?if tillTimeout == 0 && not (isEmpty stack) then do >>> ? ? ? ? ? ?let (val, stack') = pop stack >>> ? ? ? ? ? ?putMVar wnVar (PopValue val) >>> ? ? ? ? ? ?schedule never stack' >>> ? ? ? ? ?else do >>> ? ? ? ? ? ?inp <- takeMVarWithTimeout (fromIntegral tillTimeout) inpVar >>> ? ? ? ? ? ?case inp of >>> ? ? ? ? ? ? ? ?ModifyStack f -> schedule_ timeout (f stack) >>> ? ? ? ? ? ? ? ?WaitFor t ? ? ? ?-> do >>> ? ? ? ? ? ? ? ? ? ?now <- getSystemTime >>> ? ? ? ? ? ? ? ? ? ?schedule (t+now) stack >>> ? ? ? ? ? ? ? ?Timeout ? ? ? ?-> schedule timeout stack >>> >>> ?readMVarWithTimeout :: Int -> MVar ScheduleInput -> IO ScheduleInput >>> ?readMVar timeoutUS inpVar = do >>> ? ?tid <- forkIO $ do >>> ? ? ? ?threadDelay timeoutUS >>> ? ? ? ?putMVar inpVar Timeout >>> ? ?inp <- takeMVar inpVar >>> ? ?killThread tid >>> ? ?return inp >>> >>> ?waitNotify :: MVar ScheduleInput -> MVar Int -> IO () >>> ?waitNotify schInp wnInp = do >>> ? ?val <- takeMVar wnInp >>> ? ?...notify... >>> ? ?let t = .... >>> ? ?putMVar schInp $ WaitFor t ?-- block input for the specified period >>> >>> ?main = do >>> ? ?schVar <- newEmptyMVar >>> ? ?wnVar <- newEmptyMVar >>> ? ?forkIO $ schedule schVar wnVar [] >>> ? ?forkIO $ waitNotify wnVar schVar >>> ? ?... >>> ? ?-- Modify stack according to user input inside your main IO loop >>> ? ?putMVar schVar $ ModifyStack $ \stack -> ... >>> >>> >>> ?I'm sure this is not exactly what you want, but at least it illustrates >>> ?how you can achieve anything you like by using MVars + extra worker >>> ?threads + killing threads (useful for implementing timeouts). >>> >>> >>> ?Steve >>> >>> ?Floptical Logic wrote: >>>> >>>> ?Hi, >>>> >>>> ?I am new to concurrency in Haskell and I am having trouble >>>> ?implementing the notion of interrupting a thread. >>>> >>>> ?In a new thread, call it waitNotify, I am trying to do the following: >>>> ?pop a number from a stack, wait some number of seconds based on the >>>> ?number popped from the stack, perform some notification, and repeat >>>> ?until there are no more numbers in the stack at which point we wait >>>> ?for a new number. >>>> >>>> ?These numbers will be supplied interactively by the user from main. >>>> ?When the user supplies a new number, I want to interrupt whatever >>>> ?waiting is happening in waitNotify, insert the number in the proper >> >> ?>> position in the current stack, and resume waitNotify using the updated >>>> >>>> ?stack. ?Note, here "stack" is just a generalization; it will likely >>>> ?just be a list. >>>> >>>> ?What is the most idiomatic way to capture this sort of behavior in >>>> ?Haskell? ?My two challenges are the notion of interrupting a thread, >>>> ?and sharing and updating this stack between threads (main and >>>> ?waitNotify). >>>> >>>> ?Thank you >>>> ?_______________________________________________ >>>> ?Beginners mailing list >>>> ?Beginners@haskell.org >>>> ?http://www.haskell.org/mailman/listinfo/beginners >>>> >>> ?_______________________________________________ >>> ?Beginners mailing list >>> ?Beginners@haskell.org >>> ?http://www.haskell.org/mailman/listinfo/beginners >>> >> >> Thanks Stephen. ?That worked and things are starting to make more >> sense. ?The crux of it all was the readMVarWithTimeout function which >> does exactly what I want. >> >> Now I want to extend this a bit further to use StateT. ?I've modified >> the schedule function quite a bit, and now it has type schedule :: >> StateT MyState IO. ?I keep the MVar actVar in MyState as well the list >> (stack) of wait times. ?However, the type of forkIO is forkIO :: IO () >> -> IO ThreadId. ?How do I fork a new thread for schedule even though >> it is wrapped in the State monad? >> >> Thanks again. > > You'll want something like this: > > myFork :: StateT MyState IO () -> MyState -> StateT MyState IO ThreadId > myFork action initialState = liftIO (forkIO (evalStateT action > initialState)) > > Dean > That's not quite what I'm looking for. I don't want to create a new thread in which to run the monad but rather to be able to create threads from inside the monad (as a result of running the monad). From chaddai.fouche at gmail.com Thu Dec 31 06:26:28 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Thu Dec 31 05:59:43 2009 Subject: [Haskell-beginners] Interrupting a thread In-Reply-To: References: <4B37B9EC.80109@blacksapphire.com> Message-ID: On Thu, Dec 31, 2009 at 9:21 AM, Floptical Logic wrote: >> You'll want something like this: >> >> myFork :: StateT MyState IO () -> MyState -> StateT MyState IO ThreadId >> myFork action initialState = liftIO (forkIO (evalStateT action >> initialState)) > > That's not quite what I'm looking for. ?I don't want to create a new > thread in which to run the monad but rather to be able to create > threads from inside the monad (as a result of running the monad). And that's what this code does. Do you want it to automatically use the state of the monad ? > myFork :: StateT MyState IO () -> MyState -> StateT MyState IO ThreadId > myFork action = liftIO . forkIO . evalStateT action =<< get keep in mind that nothing the thread will do will affect the state of the main thread. -- Jeda? From legajid at free.fr Thu Dec 31 06:53:05 2009 From: legajid at free.fr (legajid) Date: Thu Dec 31 06:21:55 2009 Subject: [Haskell-beginners] Data.Map, types and debug Message-ID: <4B3C90A1.6040306@free.fr> Hi, studying IO with files, i got this tutorial program. By the way, i discover the Data.Map module. Several questions then come to my mind : q1: why, in mapM_, make (sort (keys grades)) ? keys is already sorted, isn't it? q2: why, in mapM_, have grades twice (in draw then keys). I wonder if writing only draw grades, one could then extract the s and g parts in the draw function (via keys and elems). From this, i have problems with the type of grades; which is it? The insert function, using insertWith should give Map k a, but foldr seems to change this (couldn't match expected type [Map k a] against inferred type Map [String] a1 on the mapM_ line . q3: To solve the types problem, I tried to debug : i can get the types for s, marks and avg but for g, it says not in scope. How can i get this information ? q4: I also tried to type the parameter in draw (draw (x::Map k a) = ...) but i got an error : Illegal signature in pattern use -XScopedTypeVariables to permit it Since this parameter is visibly not set by default in ghci, is it a good idea to set it ? Thanks and happy new year. Didier import Data.Char import Data.Maybe import Data.List import Data.Map hiding (map ) import Text.Printf main = do src <- readFile "grades" let pairs = map (split.words ) (lines src) let grades = foldr insert empty pairs mapM_ (draw grades) (sort (keys grades)) where insert (s, g) = insertWith (++ ) s [g] split [name,mark] = (name, read mark) draw g s = printf "%s\t%s\tAverage: %f\n" s (show marks) avg where marks = findWithDefault (error "No such student") s g avg = sum marks / fromIntegral (length marks) :: Double From daniel.is.fischer at web.de Thu Dec 31 07:37:23 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Dec 31 07:12:12 2009 Subject: [Haskell-beginners] Data.Map, types and debug In-Reply-To: <4B3C90A1.6040306@free.fr> References: <4B3C90A1.6040306@free.fr> Message-ID: <200912311337.24173.daniel.is.fischer@web.de> Am Donnerstag 31 Dezember 2009 12:53:05 schrieb legajid: > Hi, > studying IO with files, i got this tutorial program. > By the way, i discover the Data.Map module. > Several questions then come to my mind : > q1: why, in mapM_, make (sort (keys grades)) ? keys is already sorted, > isn't it? It is. That is also specified in the documentation, so it's superfluous. It may be a leftover from earlier versions using a data structure which doesn't guarantee to return the keys in ascending order. > q2: why, in mapM_, have grades twice (in draw then keys). draw takes two arguments, a Map in which to look up the marks and a key to look up, the name of the student. The list of keys over which we want to mapM_ is the list of keys in the Map, (keys grades). The function we want to mapM_ is (look up marks of student in the Map grades and then output marks and average), that is (draw grades). > I wonder if writing only draw grades, one could then extract the s and g > parts in the draw function (via keys and elems). From this, i have problems > with the type of grades; which is it? The insert function, using insertWith > should give Map k a, but foldr seems to change this (couldn't match > expected type [Map k a] against inferred type Map [String] a1 on the mapM_ > line . ? I don't understand what you tried to do there. You can write a function draw1 which takes only a Map as argument so that draw1 grades is the same as mapM_ (draw grades) (keys grades) > q3: To solve the types problem, I tried to debug : i can get the types for > s, marks and avg but for g, it says not in scope. How can i get this > information ? g is a parameter of draw, so there is no entity g defined outside the definition of draw. To find the type of g, ask ghci: *Grades> :t draw draw :: (PrintfArg k, PrintfType t, Ord k) => Map k [Double] -> k -> t , since g is the first argument of draw, its type is the type to the left of the first (top level) '->', namely Map k [Double] (I have here ignored the type class constraints on k). > q4: I also tried to type the parameter in draw (draw (x::Map k a) = ...) > but i got an error : Illegal signature in pattern > use -XScopedTypeVariables to permit it > Since this parameter is visibly not set by default in ghci, is it a good > idea to set it ? If you need it. Here, you can solve the problem with a type signature on draw, e.g. draw :: Map String [Double] -> String -> IO () > > Thanks and happy new year. A vous aussi. > Didier > > > import Data.Char > > import Data.Maybe > e> import Data.List > import Data.Map hiding (map > >) import Text.Printf > > main = do > src <- readFile > File> "grades" let pairs = map > > (split.words > s>) (lines > s> src) let grades = foldr > r> insert empty pairs mapM_ > _> (draw grades) (sort (keys grades)) where > insert (s, g) = insertWith (++ > ) > s [g] split [name,mark] = (name, read > > mark) > > draw g s = printf "%s\t%s\tAverage: %f\n" s (show > > marks) avg where > marks = findWithDefault (error > r> "No such student") s g avg = sum > > marks / fromIntegral > Integral> (length > th> marks) :: Double > le> -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091231/93ca592d/attachment.html From koverton at lab49.com Thu Dec 31 11:05:07 2009 From: koverton at lab49.com (Ken Overton) Date: Thu Dec 31 10:40:54 2009 Subject: [Haskell-beginners] Is there a (^) function for exponents other than integral? Message-ID: <162FF9B889BC8E4FB7E988870897EAB5170BCB4A@Exchange02b.lab49.com> Sorry if this is from a faq list somewhere, I've been looking through the more common locations/libs and have been unable to find a way to raise numbers to a fractional exponent. Can someone help me to find such a function in haskell? Thanks, -- kov -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091231/3073ec5b/attachment-0001.html From tom.davie at gmail.com Thu Dec 31 11:20:03 2009 From: tom.davie at gmail.com (Tom Davie) Date: Thu Dec 31 10:53:17 2009 Subject: [Haskell-beginners] Is there a (^) function for exponents other than integral? In-Reply-To: <162FF9B889BC8E4FB7E988870897EAB5170BCB4A@Exchange02b.lab49.com> References: <162FF9B889BC8E4FB7E988870897EAB5170BCB4A@Exchange02b.lab49.com> Message-ID: <8b70a98a0912310820v1c1f2ff8wf85a997bf898ec71@mail.gmail.com> (**) A good place to start on things like this is Hoogle: http://www.haskell.org/hoogle Bob On Thu, Dec 31, 2009 at 4:05 PM, Ken Overton wrote: > Sorry if this is from a faq list somewhere, I've been looking through the > more common locations/libs and have been unable to find a way to raise > numbers to a fractional exponent. Can someone help me to find such a > function in haskell? > > Thanks, > > -- kov > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091231/09bb9047/attachment.html From joe at fixieconsulting.com Thu Dec 31 12:37:10 2009 From: joe at fixieconsulting.com (Joe Van Dyk) Date: Thu Dec 31 12:10:42 2009 Subject: [Haskell-beginners] Global variable question In-Reply-To: <1262224821-sup-6648@ezyang> References: <1262224821-sup-6648@ezyang> Message-ID: On Wed, Dec 30, 2009 at 6:05 PM, Edward Z. Yang wrote: > Excerpts from Joe Van Dyk's message of Wed Dec 30 20:49:12 -0500 2009: >> What's the appropriate way to write this in Haskell? > > Hi Joe, > > The Ticker class is an example of stateful computation, which we try > to avoid in Haskell. ?What are you really trying to do? > > * If you a number, and you want to add to it, (+1) works > ?plenty well. > > * If you are going to be making ticks, but you don't care about > ?reading the ticks until the end of the computation, the Writer monad > ?is of interest. > > * If you need to update the tick count and read it, the State > ?monad is a good bet. > > * If you're interested in curiosities from imperative land, STRef, IORef and > ?other similar creatures may be helpful. It's like haskell is on a personal vendetta against me to make me feel dumb. -- Joe Van Dyk http://fixieconsulting.com From darrinth at gmail.com Thu Dec 31 12:44:13 2009 From: darrinth at gmail.com (Darrin Thompson) Date: Thu Dec 31 12:17:26 2009 Subject: [Haskell-beginners] Is there a (^) function for exponents other than integral? In-Reply-To: <162FF9B889BC8E4FB7E988870897EAB5170BCB4A@Exchange02b.lab49.com> References: <162FF9B889BC8E4FB7E988870897EAB5170BCB4A@Exchange02b.lab49.com> Message-ID: On Thu, Dec 31, 2009 at 11:05 AM, Ken Overton wrote: > Sorry if this is from a faq list somewhere, I've been looking through the > more common locations/libs and have been unable to find a way to raise > numbers to a fractional exponent.?? Can someone help me to find such a > function in haskell? > (**) is in the Prelude, no? -- Darrin From velman at cox.net Thu Dec 31 18:38:00 2009 From: velman at cox.net (John Velman) Date: Thu Dec 31 18:11:13 2009 Subject: [Haskell-beginners] Global variable question In-Reply-To: References: <1262224821-sup-6648@ezyang> Message-ID: <20091231233800.GA251@cox.net> On Thu, Dec 31, 2009 at 09:37:10AM -0800, Joe Van Dyk wrote: > On Wed, Dec 30, 2009 at 6:05 PM, Edward Z. Yang wrote: > > Excerpts from Joe Van Dyk's message of Wed Dec 30 20:49:12 -0500 2009: > >> What's the appropriate way to write this in Haskell? > > > > Hi Joe, > > > > The Ticker class is an example of stateful computation, which we try > > to avoid in Haskell. ?What are you really trying to do? > > > > * If you a number, and you want to add to it, (+1) works > > ?plenty well. > > > > * If you are going to be making ticks, but you don't care about > > ?reading the ticks until the end of the computation, the Writer monad > > ?is of interest. > > > > * If you need to update the tick count and read it, the State > > ?monad is a good bet. > > > > * If you're interested in curiosities from imperative land, STRef, IORef and > > ?other similar creatures may be helpful. > > It's like haskell is on a personal vendetta against me to make me feel dumb. It's not personal. John Velman. > > > -- > Joe Van Dyk > http://fixieconsulting.com > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From joe at fixieconsulting.com Thu Dec 31 18:43:33 2009 From: joe at fixieconsulting.com (Joe Van Dyk) Date: Thu Dec 31 18:17:05 2009 Subject: [Haskell-beginners] Global variable question In-Reply-To: <20091231233800.GA251@cox.net> References: <1262224821-sup-6648@ezyang> <20091231233800.GA251@cox.net> Message-ID: On Thu, Dec 31, 2009 at 3:38 PM, John Velman wrote: > On Thu, Dec 31, 2009 at 09:37:10AM -0800, Joe Van Dyk wrote: >> On Wed, Dec 30, 2009 at 6:05 PM, Edward Z. Yang wrote: >> > Excerpts from Joe Van Dyk's message of Wed Dec 30 20:49:12 -0500 2009: >> >> What's the appropriate way to write this in Haskell? >> > >> > Hi Joe, >> > >> > The Ticker class is an example of stateful computation, which we try >> > to avoid in Haskell. ?What are you really trying to do? >> > >> > * If you a number, and you want to add to it, (+1) works >> > ?plenty well. >> > >> > * If you are going to be making ticks, but you don't care about >> > ?reading the ticks until the end of the computation, the Writer monad >> > ?is of interest. >> > >> > * If you need to update the tick count and read it, the State >> > ?monad is a good bet. >> > >> > * If you're interested in curiosities from imperative land, STRef, IORef and >> > ?other similar creatures may be helpful. >> >> It's like haskell is on a personal vendetta against me to make me feel dumb. > > > It's not personal. Feels like it though. :( From velman at cox.net Thu Dec 31 23:08:52 2009 From: velman at cox.net (John Velman) Date: Thu Dec 31 22:42:04 2009 Subject: [Haskell-beginners] Problem installing graphalyze with Cabal Message-ID: <20100101040851.GA3447@cox.net> I have Haskell Platform downloaded and installed today. When I tried to install graphalyze with cabal install, it had problems with pandoc. To make a long story fairly short, I downloaded pandoc-1.3 from hackage, and tried building it "by hand". It says it had missing dependencies of utf8-string >= 0.3, and zip-archive >=0.1.1. Tried installing them with cabal, and this worked OK. Still, pandoc setup says: jrv:pandoc-1.3 jr$ runhaskell Setup configure Configuring pandoc-1.3... Setup: At least the following dependencies are missing: utf8-string >=0.3, zip-archive >=0.1.1 jrv:pandoc-1.3 jr$ cabal install zip-archive-0.1.1.1 I _finally_ checked ghc-pkg list, and I have, among other things: /Users/jr/.ghc/i386-darwin-6.10.4/package.conf: {HOC-1.0}, {HOC-Foundation-1.0}, binary-0.5.0.1, binary-0.5.0.2, bktrees-0.2.2, darcs-2.3.0, digest-0.0.0.8, graphviz-2999.6.0.0, hashed-storage-0.3.7, haskeline-0.6.1.6, mmap-0.4.1, pandoc-1.3, polyparse-1.4, terminfo-0.3.0.2, utf8-string-0.3.5, utf8-string-0.3.6, zip-archive-0.1.1.1, zip-archive-0.1.1.4, zlib-0.5.2.0 As you see, I've ended up with two copies each (because of my messing around before I checked ghc-pkg, I guess). Well, all of them are >= the dependency requirements, If I understand correctly. What gives? How do I get rid of the extra copies? (By the way, the HOC entries are left over from an earlier time, and I'd like to get rid of those also). Thanks, John Velman