From daniel.is.fischer at web.de Sun Nov 1 00:44:07 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Nov 1 00:22:25 2009 Subject: [Haskell-beginners] Class definition syntax In-Reply-To: <200910312142.24975.shawn-haskell@willden.org> References: <200910311027.10559.shawn-haskell@willden.org> <200910312142.24975.shawn-haskell@willden.org> Message-ID: <200911010544.07399.daniel.is.fischer@web.de> First, the IArray class from Data.Array.IArray is not the real thing. Looking at the class in Data.Array.Base, we see {- | Class of immutable array types. An array type has the form @(a i e)@ where @a@ is the array type constructor (kind @* -> * -> *@), @i@ is the index type (a member of the class 'Ix'), and @e@ is the element type. The @IArray@ class is parameterised over both @a@ and @e@, so that instances specialised to certain element types can be defined. -} class IArray a e where -- | Extracts the bounds of an immutable array bounds :: Ix i => a i e -> (i,i) numElements :: Ix i => a i e -> Int unsafeArray :: Ix i => (i,i) -> [(Int, e)] -> a i e unsafeAt :: Ix i => a i e -> Int -> e unsafeReplace :: Ix i => a i e -> [(Int, e)] -> a i e unsafeAccum :: Ix i => (e -> e' -> e) -> a i e -> [(Int, e')] -> a i e unsafeAccumArray :: Ix i => (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> a i e unsafeReplace arr ies = runST (unsafeReplaceST arr ies >>= unsafeFreeze) unsafeAccum f arr ies = runST (unsafeAccumST f arr ies >>= unsafeFreeze) unsafeAccumArray f e lu ies = runST (unsafeAccumArrayST f e lu ies >>= unsafeFreeze) That's more like it, isn't it? Doesn't solve your kind problems, though. Am Sonntag 01 November 2009 04:42:24 schrieb Shawn Willden: > On Saturday 31 October 2009 08:55:56 pm Joe Fredette wrote: > > Well, I think the issue is you're thinking too OOPy... > > I understand what you're saying, but I don't think I am. > > > But let me answer the actual problem first, type classes are > > (basically) functions on types. So a type of "kind" `* -> * -> *` > > means it is a type which accepts two type variables. So: > > > > newtype Foo a b = Foo (a, b) > > Okay, that makes sense. What I'd read about kinds was considerably less > clear. Thanks. > > > newtype Board = Board IArray ... > > > > means that _you can just use the IArray types_! Well, almost, really > > what you want is a type-synonym: > > > > type Board = IArray Location ... > > > > Now you can write functions like > > > > foo :: Board -> Int > > foo = Board !! (1,2) > > > > and it will "just work" because Board _is_ an "IArray". > > > > Hope that makes sense... > > It does make sense, but it doesn't solve my problem. See, Board isn't the > only type I have (and, also, Board has to be a newtype rather than a type > synonym because it's also an instance of another class -- well, unless I > want to turn on the extension that allows instances of synonyms, and I'm > not sure what the etiquette is there), That's not much of a problem. It may not be portable (maybe it is, maybe not, I don't know), but it's nothing unsafe. Or you could use FlexibleInstances and instance OtherClass (Array Location Int) where... > and some of the others aren't just > IArrays with an aliased name, they have other data elements as well. For > example: > > data ScoredBoard = ScoredBoard { > arry :: (IArray Location String) > score :: Int > maxScore :: Int > } Would something like import Data.Array.Base data ScoreBoard i e = ScoreBoard { arry :: Array i e , score :: Int , maxScore :: Int } instance IArray ScoreBoard e where bounds sb = bounds (arry sb) numElements sb = numElements (arry sb) unsafeArray bds ass = ScoreBoard (unsafeArray bds ass) 0 0 unsafeAt sb i = unsafeAt (arry sb) i ... be an option (analogous for Board)? > > I would like to be able to use (!), (//), bound, range, etc., on those as > well, and without having to say "range (arry sb)", or having to define a > bunch of fooRange, barRange, bazRange, etc., functions. If you don't want to change the kind of Board etc, another option would be a multiparameter type class with functional dependencies or type families: With fundeps: class KindOfArrayLike a i e | a -> i, a -> e where (!) :: a -> i -> e (//) :: a -> [(i,e)] -> a ... instance KindOfArrayLike Board Location Int where (Board a) ! i = a Data.Array.IArray.! i (Board a) // upd = Board (a Data.Array.IArray.// upd) ... instance KindOfArrayLike ScoreBoard Location String where sb ! i = arry sb Data.Array.IArray.! i sb // upd = sb{ arry = arry sb Data.Array.IArray.// upd } ... With type families: class ArrayLike a where type Idx a :: * type Elt a :: * (!) :: a -> Idx a -> Elt a (//) :: a -> [(Idx a, Elt a)] -> a instance ArrayLike Board where type Idx Board = Location type Elt Board = Int (implementation as before) > > Basically I want to take this set of common array operations and overload > them for a bunch of different types. As I understand it, classes are > effectively the only way to overload in Haskell. > > Perhaps it just isn't possible to do what I want? If kind signatures must > match, then that's a problem, because different types will have different > numbers of construction parameters. > > Thanks for the help, > > Shawn. From mpm at alumni.caltech.edu Sun Nov 1 10:15:17 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sun Nov 1 09:51:39 2009 Subject: [Haskell-beginners] several questions: multi-param typeclasses, etc. Message-ID: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> I'm trying to understand multi-param typeclasses; a particular one (MonadError); and functional dependencies. For example, throwError in in the MonadError class definition: class Monad m => MonadError e m | m -> e where throwError :: e -> m a The concept of a multi-parameter class is a litte tricky. It's no longer so simple to say that "ONE type is AN instance of ONE class." Instead, it seems more appropriate to say that "in a context where e and m fulfill the criteria for class MonadError, the function throwError is available." In a sense, there is no single type that is an instance of MonadError. Is this the right way to put it? So I went looking for an instance of MonadError, in particular with use with Either. I couldn't find actual source code with an instance, but the Haddock documentation lists this: Instances: Error e => MonadError e (Either e) The code doesn't give the definition, but I suppose it would be: throwError e = Left e ??? Now I'm interested in understanding this functional dependency between m and e. For the compiler to decide that a particular instance's definition of throwError is available, it must decide that e is of class Error (it is given by class constraint) m is a Monad (Either e is such) and then this m -> e thing: I don't know how to put this into words Any explanation/clarification/correction appreciated. Thanks, Mike From byorgey at seas.upenn.edu Sun Nov 1 10:41:37 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Nov 1 10:17:54 2009 Subject: [Haskell-beginners] several questions: multi-param typeclasses, etc. In-Reply-To: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> References: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> Message-ID: <20091101154137.GA22407@seas.upenn.edu> Hi Michael, On Sun, Nov 01, 2009 at 07:15:17AM -0800, Michael Mossey wrote: > I'm trying to understand multi-param typeclasses; a particular one > (MonadError); and functional dependencies. > > For example, throwError in in the MonadError class definition: > > class Monad m => MonadError e m | m -> e where > throwError :: e -> m a > > In a sense, there is no single type that is an instance of MonadError. > > Is this the right way to put it? I think a better way to put it is that an instance of MonadError is a PAIR of types, instead of a single type. > Error e => MonadError e (Either e) > > The code doesn't give the definition, but I suppose it would be: > > throwError e = Left e ??? Right. (No pun intended ;) > Now I'm interested in understanding this functional dependency between > m and e. For the compiler to decide that a particular instance's > definition of throwError is available, it must decide that > > e is of class Error (it is given by class constraint) > m is a Monad (Either e is such) > and then this m -> e thing: I don't know how to put this into words The m -> e thing isn't a constraint that needs to be satisfied; it gives some extra information to help the compiler with inferring which instance to use. In particular, "m -> e" says "the type chosen for m DETERMINES the type chosen for e"; put another way, "there cannot be two instances with the same type for m but different types for e". So in this case you could not also make an instance MonadError String (Either e). -Brent From mpm at alumni.caltech.edu Sun Nov 1 11:32:34 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sun Nov 1 11:08:58 2009 Subject: [Haskell-beginners] several questions: multi-param typeclasses, etc. In-Reply-To: <20091101154137.GA22407@seas.upenn.edu> References: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> <20091101154137.GA22407@seas.upenn.edu> Message-ID: <4AEDB822.7020107@alumni.caltech.edu> Brent Yorgey wrote: > The m -> e thing isn't a constraint that needs to be satisfied; it > gives some extra information to help the compiler with inferring which > instance to use. In particular, "m -> e" says "the type chosen for m > DETERMINES the type chosen for e"; put another way, "there cannot be > two instances with the same type for m but different types for e". So > in this case you could not also make an instance > > MonadError String (Either e). > Thanks, Brent. Now what I'm a bit confused about: if you wrote instance (Error e) => MonadError e (Either e) and no other instance with Either e, then the compiler would have only one choice. So why would it need the extra information in the functional dependency? On the other hand, if you added instance (Error e) => MonadError String (Either e) and didn't include the functional dependency, the compiler would still run into a problem with overlapping instances and have no way to decide, which I presume is still an error. So it looks to me (no doubt because I don't understand correctly) that the functional dependency doesn't add any information or clarify any situation. Please explain! Thanks, Mike From byorgey at seas.upenn.edu Sun Nov 1 12:25:55 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Nov 1 12:02:10 2009 Subject: [Haskell-beginners] several questions: multi-param typeclasses, etc. In-Reply-To: <4AEDB822.7020107@alumni.caltech.edu> References: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> <20091101154137.GA22407@seas.upenn.edu> <4AEDB822.7020107@alumni.caltech.edu> Message-ID: <20091101172555.GA25813@seas.upenn.edu> On Sun, Nov 01, 2009 at 08:32:34AM -0800, Michael Mossey wrote: > > > Brent Yorgey wrote: >> The m -> e thing isn't a constraint that needs to be satisfied; it >> gives some extra information to help the compiler with inferring which >> instance to use. In particular, "m -> e" says "the type chosen for m >> DETERMINES the type chosen for e"; put another way, "there cannot be >> two instances with the same type for m but different types for e". So >> in this case you could not also make an instance >> >> MonadError String (Either e). >> > > Thanks, Brent. Now what I'm a bit confused about: > if you wrote > > instance (Error e) => MonadError e (Either e) > > and no other instance with Either e, then the compiler would have only one > choice. So why would it need the extra information in the functional > dependency? Because type classes are open: when compiling a module, the compiler is never allowed to assume that the instances it sees are the only instances, because there could always be another instance declared in a module it hasn't seen yet. > > On the other hand, if you added > > instance (Error e) => MonadError String (Either e) > > and didn't include the functional dependency, the compiler would still run > into a problem with overlapping instances and have no way to decide, which > I presume is still an error. True. In the case of this particular *instance*, the functional dependency doesn't really add all that much. But that doesn't mean the functional dependency on the *class* is useless; there can be other instances of the class as well. -Brent From chaddai.fouche at gmail.com Sun Nov 1 14:21:11 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Sun Nov 1 13:57:29 2009 Subject: [Haskell-beginners] several questions: multi-param typeclasses, etc. In-Reply-To: <4AEDB822.7020107@alumni.caltech.edu> References: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> <20091101154137.GA22407@seas.upenn.edu> <4AEDB822.7020107@alumni.caltech.edu> Message-ID: On Sun, Nov 1, 2009 at 5:32 PM, Michael Mossey wrote: > On the other hand, if you added > > instance (Error e) => MonadError String (Either e) > > and didn't include the functional dependency, the compiler would still run > into a problem with overlapping instances and have no way to decide, which I > presume is still an error. Right, in this case it is true, but supposing the MonadError instance for Either was rather : > instance (Error e) => MonadError (Maybe String) (Either e) There would be nothing a priori that would prevent you from writing another instance : > instance (Error e) => MonadError String (Either e) There are a certain number of case where this functional constraint is thus useful. -- Jeda? From mpm at alumni.caltech.edu Sun Nov 1 14:22:19 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sun Nov 1 13:58:48 2009 Subject: [Haskell-beginners] several questions: multi-param typeclasses, etc. In-Reply-To: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> References: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> Message-ID: <4AEDDFEB.5070509@alumni.caltech.edu> So if I understand correctly, when the compiler sees this class definition: > For example, throwError in in the MonadError class definition: > > class Monad m => MonadError e m | m -> e where > throwError :: e -> m a Then it sees this instance: > Instances: > > Error e => MonadError e (Either e) > Because (Either e) is a monad, it "fits with" the m in the class definition. (The m has the constraint Monad on it.) Knowing that, the compiler uses the functional dependency to conclude that the given instance is the only possible instance. Is that right? Another question: in Control.Monad.Error, I see the instance MonadError IOError IO which leads to the question: apparently I can throw errors in the IO monad using throwError. But there is also throw and throwIO. What is the difference? Thanks, Mike From mpm at alumni.caltech.edu Sun Nov 1 14:31:33 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sun Nov 1 14:08:09 2009 Subject: [Haskell-beginners] several questions: multi-param typeclasses, etc. In-Reply-To: References: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> <20091101154137.GA22407@seas.upenn.edu> <4AEDB822.7020107@alumni.caltech.edu> Message-ID: <4AEDE215.10709@alumni.caltech.edu> Chadda? Fouch? wrote: > On Sun, Nov 1, 2009 at 5:32 PM, Michael Mossey wrote: >> On the other hand, if you added >> >> instance (Error e) => MonadError String (Either e) >> >> and didn't include the functional dependency, the compiler would still run >> into a problem with overlapping instances and have no way to decide, which I >> presume is still an error. > > Right, in this case it is true, but supposing the MonadError instance > for Either was rather : > >> instance (Error e) => MonadError (Maybe String) (Either e) > > There would be nothing a priori that would prevent you from writing > another instance : > >> instance (Error e) => MonadError String (Either e) I think I understand that you are saying it would create a messy situation to write this second instance, and the functional constraint causes the compiler to stop with an error if it sees that second instance. Is that true? Now I have a question that probably doesn't make sense, but what I'm really doing is picking your brain. I want to see how you would rephrase it: Let's assume for a moment that two different people are involved in this code. One of them writes the class definition. Another one writes an instance. In OO, which I am more familiar with, one person will write a class with a limited API in order to help put guarantees on the correct behavior of the class. In a sense, that person is saying: "I release my class to the world to do what it will, but before doing that I put some constraints on it so no one can distort my intentions." Is this functional dependency a similar situation? Does it make sense from the "point of view" of the author of the class definition? Or is it more a practical necessity? Thanks, Mike From haskell-beginners at foo.me.uk Sun Nov 1 18:27:42 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Sun Nov 1 18:04:09 2009 Subject: [Haskell-beginners] I have created an ugly Haskell program.. Message-ID: <200911012327.43027.haskell-beginners@foo.me.uk> .. and I am positive there must be a way of beautifying it, but I am struggling. I bet there is just some lovely way of making this all shrink to three lines.. So here's the problem. I have two lists of tuples: (timestamp, value) What I would like to do in do a kind of 'zip' on two of these lists to make a list of (timestamp, (value1, value2)) with the following rules: - If the timestamps are equal it's easy - make your new element an move on - If one of the lists has a timestamp that the other doesn't, repeat an old value from the other list - If we don't have an old value yet, then don't create an element in the new list. e.g. if I ran my algorithm on these two lists d1 = [ (1,"a"), (2,"b"), (3,"c") ] d2 = [ (2,"b'"), (4,"d'") ] I would like to get result = [ (2, (b,b')), (3, (c,b')), (4, (c,d')) ] e.g. there was no data in d2 for our first element so we skipped it. Okay, so here is my code.. It works, but makes me feel a bit dirty. To explain my nomenclature 't' is 'timestamp of', 'v' is 'value of'. vx' and vy' are the 'old' values from the previous iteration in case a repeat is needed. They are Maybes because at the beginning there may be no old value. d1 = [ (1,"a"), (2,"b"), (3,"c") ] d2 = [ (2,"b'"), (4,"d'") ] t (x,y) = x v (x,y) = y js vx' vy' (x:xs) (y:ys) | t x == t y = ( (t x), (v x, v y) ) : js (Just (v x)) (Just (v y)) xs ys | t x < t y = maybe (js (Just (v x)) Nothing xs (y:ys)) (\z -> ( t x, (v x, z ) ) : ( js (Just (v x)) (Just z) xs (y:ys))) vy' | t x > t y = maybe (js Nothing (Just (v y)) (x:xs) ys) (\z -> ( t y, (z, v y ) ) : ( js (Just z) (Just (v y)) (x:xs) ys)) vx' js vx' vy' (x:xs) [] = maybe [] (\z -> ( t x, (v x, z ) ) : ( js (Just (v x)) (Just z) xs [])) vy' js vx' vy' [] (y:ys) = maybe [] (\z -> ( t y, (z, v y ) ) : ( js (Just z) (Just (v y)) [] ys )) vx' js _ _ [] [] = [] You call it with the first two arguments as Nothing to kick it off (I have a trivial wrapper function to do this) It works fine: > :t js js :: (Ord t) => Maybe a1 -> Maybe a -> [(t, a1)] -> [(t, a)] -> [(t, (a1, a))] > js Nothing Nothing d1 d2 [(2,("b","b'")),(3,("c","b'")),(4,("c","d'"))] But it just feels gross. Any advice on how to tame this beast would be greatly appreciated :) All the best, Philip From didier.jacquemart at free.fr Sun Nov 1 12:53:22 2009 From: didier.jacquemart at free.fr (Didier Jacquemart) Date: Sun Nov 1 20:56:19 2009 Subject: [Haskell-beginners] Multiple type numeric data Message-ID: <4AEDCB12.8010203@free.fr> Hello, I'm just learning Haskell and have problems with a simple calculation: Here is my code below : data Figure = Carre Int Int Int | Rond (Int, Int, Integer) -- i hope Integer allows fromInteger function for r surface_carre :: Figure -> Int surface_carre (Carre x y c)= c * c surface_rond :: Figure -> Float surface_rond (Rond (x, y, r))= 3.14 * r * r surface x = case x of Carre a b c -> surface_carre x Rond (a, b, c) -> surface_rond x a::Figure a=Carre 10 10 5 b::Figure b=Rond (20, 20, 3) When i load this program, i get the following error for the line 3.14 * r * r Couldn't match expected type Float against inferred type Integer In the expression : 3.14 *r * r ... Further, i think there's a problem with the surface function, since it's not typed. Thanks for your help. Didier. From iaefai at me.com Sun Nov 1 23:57:41 2009 From: iaefai at me.com (=?iso-8859-1?Q?i=E6fai?=) Date: Sun Nov 1 23:34:06 2009 Subject: [Haskell-beginners] Error Handling and case statements Message-ID: I have been trying to work out a problem for the last few hours with little success. In the following code, using ConfigFile, I obtain the results of the configuration file, but in the main function I am trying to get the Config type out of the case statement. I need to be able to generate that error, but it means the two branches of the case are not the same type. I am not particularly attached to this direction, I am quite willing to do any way that works. I might be adding more configuration in the future. Any ideas? i?fai -- import Network.Shed.Httpd import Network.URI import Data.Either import Data.ConfigFile as C import Control.Monad.Error import Control.Applicative import ChessBoard data Config = Config { documentRoot :: String } deriving (Read, Show) main :: IO () main = do opt <- getConf "./config" config <- case opt of Left (_, err) -> ioError (userError err) Right (config) -> config docPath <- documentRoot config putStrLn "Starting up httpd." server <- initServer 6666 request return () request :: Request -> IO Response request req = do putStrLn $ "Recieved " ++ (show $ uriPath $ reqURI req) return $ Response 404 [] "Not found." -- Mostly from Chris Done's Blog getConf :: FilePath -> IO (Either (C.CPErrorData, String) Config) getConf filePath = runErrorT $ do let cp = C.emptyCP { optionxform = id } contents <- liftIO $ readFile filePath config <- C.readstring cp contents let get = C.get config "DEFAULT" Config <$> get "Document-Root" From iaefai at me.com Mon Nov 2 00:04:03 2009 From: iaefai at me.com (=?iso-8859-1?Q?i=E6fai?=) Date: Sun Nov 1 23:40:27 2009 Subject: [Haskell-beginners] Multiple type numeric data In-Reply-To: <4AEDCB12.8010203@free.fr> References: <4AEDCB12.8010203@free.fr> Message-ID: <06D51FE2-87D5-42F7-96BD-8C01A3CF4B13@me.com> Didier, here is some code that improves your one function, it will almost compile with ghc. module Main where data Figure = Carre Int Int Int | Rond (Int, Int, Integer) -- i hope Integer allows fromInteger function for r surface_carre :: Figure -> Int surface_carre (Carre x y c)= c * c surface_rond :: Figure -> Float surface_rond (Rond (x, y, r))= 3.14 * (fromInteger (r * r)) surface x = case x of Carre a b c -> surface_carre x Rond (a, b, c) -> surface_rond x a::Figure a=Carre 10 10 5 b::Figure b=Rond (20, 20, 3) main :: IO () main = do putStrLn "Test" return () Note that surface has a problem because surface_carre returns an Int and surface_rond returns a Float. These types are incompatible. I don't think there is a more general type you can use. Can you get away with just using all the same type? - i?fai On 2009-11-01, at 12:53 PM, Didier Jacquemart wrote: > data Figure = Carre Int Int Int > | Rond (Int, Int, Integer) -- i hope Integer allows > fromInteger function for r > > surface_carre :: Figure -> Int > surface_carre (Carre x y c)= c * c > > surface_rond :: Figure -> Float > surface_rond (Rond (x, y, r))= 3.14 * r * r > > surface x = case x of > Carre a b c -> surface_carre x > Rond (a, b, c) -> surface_rond x > a::Figure > a=Carre 10 10 5 > b::Figure > b=Rond (20, 20, 3) From ml at isaac.cedarswampstudios.org Mon Nov 2 00:04:00 2009 From: ml at isaac.cedarswampstudios.org (Isaac Dupree) Date: Sun Nov 1 23:41:15 2009 Subject: [Haskell-beginners] Error Handling and case statements In-Reply-To: References: Message-ID: <4AEE6840.7090504@isaac.cedarswampstudios.org> i?fai wrote: > I have been trying to work out a problem for the last few hours with > little success. > ... > config <- case opt of > Left (_, err) -> ioError (userError err) > Right (config) -> config does changing the last line to Right (config) -> return config fix your type error? -Isaac From chaddai.fouche at gmail.com Mon Nov 2 04:15:34 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Mon Nov 2 03:51:54 2009 Subject: [Haskell-beginners] several questions: multi-param typeclasses, etc. In-Reply-To: <4AEDE215.10709@alumni.caltech.edu> References: <1754.75.50.168.229.1257088517.squirrel@mail.alumni.caltech.edu> <20091101154137.GA22407@seas.upenn.edu> <4AEDB822.7020107@alumni.caltech.edu> <4AEDE215.10709@alumni.caltech.edu> Message-ID: On Sun, Nov 1, 2009 at 8:31 PM, Michael Mossey wrote: > In OO, which I am more familiar with, one person will write a class with a > limited API in order to help put guarantees on the correct behavior of the > class. In a sense, that person is saying: "I release my class to the world > to do what it will, but before doing that I put some constraints on it so no > one can distort my intentions." > > Is this functional dependency a similar situation? Does it make sense from > the "point of view" of the author of the class definition? > > Or is it more a practical necessity? In this particular case of MonadError, I think the constraint is more of the first variety but most functional constraints are more practical than moral... The case in point being when you want to put a method in the class that don't include all the type parameters of the class in its type : you NEED to have functional constraints for Haskell to accept that the correct method can be determined with this partial information (and determine it later on). It is worth noting that many case where multi-param classes are used with a mandatory practical functional constraint are better expressed by the new indexed type family extension and a single param type class (though this is not always the case) : For instance the classic Collection type class : > class Collection collection elt | collection -> elt where > add :: elt -> collection -> collection > merge :: collection -> collection -> collection > ... (merge is the function that makes the functional constraint a practical necessity) Can be better (or at least more cleanly, depending on who you ask) expressed as : > class Collection c where > type Elt c :: * > add :: Elt c -> c -> c > merge :: c -> c -> c > ... -- Jeda? From dav.vire+haskell at gmail.com Mon Nov 2 04:49:34 2009 From: dav.vire+haskell at gmail.com (David Virebayre) Date: Mon Nov 2 04:25:51 2009 Subject: [Haskell-beginners] Multiple type numeric data In-Reply-To: <4AEDCB12.8010203@free.fr> References: <4AEDCB12.8010203@free.fr> Message-ID: <4c88418c0911020149l79af5733ld4cfd366136e7a40@mail.gmail.com> On Sun, Nov 1, 2009 at 6:53 PM, Didier Jacquemart wrote: > data Figure = Carre Int Int Int > ? ? ? ? | Rond (Int, Int, Integer) ? ?-- i hope Integer allows fromInteger > surface_carre :: Figure -> Int > surface_carre (Carre x y c)= c * c > surface_rond :: Figure -> Float > surface_rond ?(Rond (x, y, r))= 3.14 ?* r * r > surface x = case x of > ? Carre a b c ? ? -> surface_carre x > ? Rond ?(a, b, c) -> surface_rond x > a::Figure > a=Carre 10 10 5 > b::Figure > b=Rond (20, 20, 3) > When i load this program, i get the following error for the line 3.14 * r * > r > > Couldn't match expected type Float > ? ? ? ? ? against inferred type Integer > In the expression : 3.14 *r * r > ... Salut, ton probl?me c'est que la valeur de retour de surface_rond est float, mais le rayon est integer. Le fait est que Haskell ne veut pas mixer des integer avec des floats sans explicitement lui demander de les convertir. donc surface_rond (Rond (x,y,r)) = 3.14 * ( fromIntegral r) * ( fromIntegral r) mais comme on veut ?viter de calculer le fromIntegral r deux fois, il vaut mieux ?crire surface_rond (Rond (x,y,r)) = let r' = fromIntegral r in 3.14 * r' * r' Ensuite, tu vas avoir un probl?me avec la fonction surface : la valeur de retour de surface est soit int, soit float, selon si surface_carre ou surface rond est appel?e. Or, c'est invalide. Il te faut choisir un type. le plus g?n?ral ?tant float, tu as deux solutions: 1) modifier surface_carre pour que cela retourne un float 2) convertir, dans la fonction surface, la valeur de retour de surface_carre en float. Cela donne : cas 1) modifier la fonction surface_carre mais pas la fonction surface surface_carre (Carre _ _ c) = let c' = fromIntegral c in c' * c' Note que comme tu n'utilise pas les param?tres x et y, tu peux indiquer au compilateur que tu n'en a pas besoin en utilisant un _ au lieu de les nommer. cas 2) modifier la fonction surface mais pas surface_carre surface x = case x of Carre _ _ _ -> fromIntegral $ surface_carre x Rond (_, _, _) -> surface_rond x A mon avis, tu n'a pas besoin des fonctions surface_carre et surface_rond, tu peux d?finir surface comme suit. surface (Carre _ _ c ) = let c' = fromIntegral c in c' * c' surface (Rond (_ _ r) = let r' = fromIntegral r in 3.14 * r' * r' D'ailleurs par curiosit?, dans la d?finition de figure, pourquoi d?finis-tu Rond avec les param?tres entre parenth?ses ( un triple ) alors que tu ne le fais pas pour Carre ? David. From dav.vire+haskell at gmail.com Mon Nov 2 04:51:43 2009 From: dav.vire+haskell at gmail.com (David Virebayre) Date: Mon Nov 2 04:27:59 2009 Subject: [Haskell-beginners] Multiple type numeric data In-Reply-To: <4c88418c0911020149l79af5733ld4cfd366136e7a40@mail.gmail.com> References: <4AEDCB12.8010203@free.fr> <4c88418c0911020149l79af5733ld4cfd366136e7a40@mail.gmail.com> Message-ID: <4c88418c0911020151m678519dbv2231373544c94027@mail.gmail.com> 2009/11/2 David Virebayre : > Salut, ton probl?me c'est que la valeur de retour de surface_rond est > float, mais le rayon est integer. [...] Sorry for the post in French to the list, I thought Didier might like a reply in French but I didn't mean to post it to the list also. From mpm at alumni.caltech.edu Mon Nov 2 05:22:09 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Mon Nov 2 04:58:33 2009 Subject: [Haskell-beginners] I have created an ugly Haskell program.. In-Reply-To: <200911012327.43027.haskell-beginners@foo.me.uk> References: <200911012327.43027.haskell-beginners@foo.me.uk> Message-ID: <4AEEB2D1.2080703@alumni.caltech.edu> Function you seek is 'specialZip' below. 'fluff' and 'decapitate' are helpers. Not extensively tested. -- Given a list of ints that "should" all have values, fill in missing -- values using the "last" value as default. fluff :: String -> [Int] -> [(Int,String)] -> [(Int,String)] fluff last (i:is) pss@((t,s):ps) | i == t = (i,s) : fluff s is ps | i < t = (i,last) : fluff last is pss fluff last is [] = zip is (repeat last) -- Given two lists, remove enough from the front to get to two equal keys. decapitate [] _ = ([],[]) decapitate _ [] = ([],[]) decapitate xss@((tx,_):xs) yss@((ty,_):ys) | tx < ty = decapitate xs yss | ty < tx = decapitate xss ys | ty == tx = (xss,yss) specialZip d1 d2 = let (dd1,dd2) = decapitate d1 d2 -- build set of every key that should be in final list s = S.toAscList . S.fromList $ (map fst dd1) ++ (map fst dd2) in case (dd1,dd2) of ([],[]) -> [] (xs1,xs2) -> let f1 = fluff "" s xs1 -- use this set to fluff f2 = fluff "" s xs2 -- each list -- so final answer can be a simple zipWith in zipWith (\(t1,s1) (t2,s2) -> (t1,(s1,s2))) f1 f2 Philip Scott wrote: > .. and I am positive there must be a way of beautifying it, but I am > struggling. I bet there is just some lovely way of making this all shrink to > three lines.. > > So here's the problem. I have two lists of tuples: (timestamp, value) > > What I would like to do in do a kind of 'zip' on two of these lists to make a > list of (timestamp, (value1, value2)) with the following rules: > > - If the timestamps are equal it's easy - make your new element an move on > - If one of the lists has a timestamp that the other doesn't, repeat an old > value from the other list > - If we don't have an old value yet, then don't create an element in the new > list. > > e.g. if I ran my algorithm on these two lists > > d1 = [ (1,"a"), (2,"b"), (3,"c") ] > d2 = [ (2,"b'"), (4,"d'") ] > > I would like to get > > result = [ (2, (b,b')), (3, (c,b')), (4, (c,d')) ] > > e.g. there was no data in d2 for our first element so we skipped it. > > Okay, so here is my code.. It works, but makes me feel a bit dirty. To explain > my nomenclature 't' is 'timestamp of', 'v' is 'value of'. vx' and vy' are the > 'old' values from the previous iteration in case a repeat is needed. They are > Maybes because at the beginning there may be no old value. > > d1 = [ (1,"a"), (2,"b"), (3,"c") ] > d2 = [ (2,"b'"), (4,"d'") ] > > t (x,y) = x > v (x,y) = y > > js vx' vy' (x:xs) (y:ys) > | t x == t y = ( (t x), (v x, v y) ) : js (Just (v x)) (Just (v y)) xs ys > | t x < t y = > maybe (js (Just (v x)) Nothing xs (y:ys)) > (\z -> ( t x, (v x, z ) ) : ( js (Just (v x)) (Just z) xs (y:ys))) > vy' > | t x > t y = > maybe (js Nothing (Just (v y)) (x:xs) ys) > (\z -> ( t y, (z, v y ) ) : ( js (Just z) (Just (v y)) (x:xs) ys)) > vx' > js vx' vy' (x:xs) [] = > maybe [] > (\z -> ( t x, (v x, z ) ) : ( js (Just (v x)) (Just z) xs [])) > vy' > js vx' vy' [] (y:ys) = > maybe [] > (\z -> ( t y, (z, v y ) ) : ( js (Just z) (Just (v y)) [] ys )) > vx' > js _ _ [] [] = [] > > You call it with the first two arguments as Nothing to kick it off (I have a > trivial wrapper function to do this) > > It works fine: > >> :t js > js > :: (Ord t) => > Maybe a1 -> Maybe a -> [(t, a1)] -> [(t, a)] -> [(t, (a1, a))] > >> js Nothing Nothing d1 d2 > [(2,("b","b'")),(3,("c","b'")),(4,("c","d'"))] > > But it just feels gross. Any advice on how to tame this beast would be greatly > appreciated :) > > All the best, > > Philip > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From haskell-beginners at foo.me.uk Mon Nov 2 06:14:11 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Mon Nov 2 05:50:30 2009 Subject: [Haskell-beginners] I have created an ugly Haskell program.. In-Reply-To: <4AEEB2D1.2080703@alumni.caltech.edu> References: <200911012327.43027.haskell-beginners@foo.me.uk> <4AEEB2D1.2080703@alumni.caltech.edu> Message-ID: <4AEEBF03.5000307@foo.me.uk> Michael Mossey wrote: > > Function you seek is 'specialZip' below. 'fluff' and 'decapitate' are > helpers. Not extensively tested. Thanks Michael, that looks much better than mine :) From mpm at alumni.caltech.edu Mon Nov 2 06:43:25 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Mon Nov 2 06:19:48 2009 Subject: [Haskell-beginners] I have created an ugly Haskell program.. In-Reply-To: <4AEEBF03.5000307@foo.me.uk> References: <200911012327.43027.haskell-beginners@foo.me.uk> <4AEEB2D1.2080703@alumni.caltech.edu> <4AEEBF03.5000307@foo.me.uk> Message-ID: <4AEEC5DD.2010909@alumni.caltech.edu> Another solution here. The inspiration is to try to use Data.Map's fromListWith to do the main work. Notice that you can "decapitate" the useless head of each list with the single line dropWhile (not . both) . M.toAscList $ neated import Control.Arrow import qualified Data.Map as M data Combine v = LeftOnly v | RightOnly v | BothOfThem v v deriving (Show) cmb :: Combine a -> Combine a -> Combine a cmb (LeftOnly x) (RightOnly y) = BothOfThem x y cmb (RightOnly y) (LeftOnly x) = BothOfThem x y both (_,(BothOfThem _ _ )) = True both _ = False chain _ last2 ((t,LeftOnly v):xs) = (t,(v,last2)) : chain v last2 xs chain last1 _ ((t,RightOnly v):xs) = (t,(last1,v)) : chain last1 v xs chain _ _ ((t,BothOfThem v w):xs) = (t,(v,w)) : chain v w xs chain _ _ [] = [] specialZip d1 d2 = let neated = M.fromListWith cmb $ map (second LeftOnly) d1 ++ map (second RightOnly) d2 dr = dropWhile (not . both) . M.toAscList $ neated in chain "" "" dr Philip Scott wrote: > Michael Mossey wrote: >> >> Function you seek is 'specialZip' below. 'fluff' and 'decapitate' are >> helpers. Not extensively tested. > > Thanks Michael, that looks much better than mine :) > > From daniel.is.fischer at web.de Mon Nov 2 07:15:03 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Nov 2 06:53:20 2009 Subject: [Haskell-beginners] Error Handling and case statements In-Reply-To: References: Message-ID: <200911021315.03829.daniel.is.fischer@web.de> Am Montag 02 November 2009 05:57:41 schrieb i?fai: > I have been trying to work out a problem for the last few hours with ? > little success. > > In the following code, using ConfigFile, I obtain the results of the ? > configuration file, but in the main function I am trying to get the ? > Config type out of the case statement. I need to be able to generate ? > that error, but it means the two branches of the case are not the same ? > type. > > I am not particularly attached to this direction, I am quite willing ? > to do any way that works. I might be adding more configuration in the ? > future. > > Any ideas? > > i?fai > -- > import Network.Shed.Httpd > import Network.URI > > import Data.Either > import Data.ConfigFile as C > > import Control.Monad.Error > import Control.Applicative > > import ChessBoard > > data Config = Config { documentRoot :: String } deriving (Read, Show) > > > > main :: IO () > main = do > ? ? ?opt <- getConf "./config" > ? ? ?config <- case opt of > ? ? ? ? ?Left (_, err) -> ioError (userError err) > ? ? ? ? ?Right (config) -> ?config > > ? ? ?docPath <- documentRoot config Wrong type here, documentRoot config :: String > ? ? ?putStrLn "Starting up httpd." > ? ? ?server <- initServer 6666 request > ? ? ?return () main = do opt <- getConf "./config" case opt of Left (_,err) -> ioError (userError err) Right config -> do let docPath = documentRoot config putStrLn "Starting up httpd." server <- initServer 6666 request return () -- though if you don't use the server later, it would be better to replace the last two lines with just "initServer 6666 request" Perhaps better to separate getting the config from using it: main = do opt <- getConf "./config" case opt of Left (_,err) -> ioError (userError err) Right config -> workWith config workWith config = do let docPath = documentRoot config putStrLn ... > ???????? > request :: Request -> IO Response > request req = do > ? ? ?putStrLn $ "Recieved " ++ (show $ uriPath $ reqURI req) > ? ? ?return $ Response 404 [] "Not found." > > -- Mostly from Chris Done's Blog > getConf :: FilePath -> IO (Either (C.CPErrorData, String) Config) > getConf filePath = runErrorT $ do > ????????let cp = C.emptyCP { optionxform = id } > ????????contents <- liftIO $ readFile filePath > ????????config <- C.readstring cp contents > ????????let get = C.get config "DEFAULT" > ????????Config <$> get "Document-Root" From byorgey at seas.upenn.edu Mon Nov 2 11:48:09 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Nov 2 11:24:23 2009 Subject: [Haskell-beginners] I have created an ugly Haskell program.. In-Reply-To: <200911012327.43027.haskell-beginners@foo.me.uk> References: <200911012327.43027.haskell-beginners@foo.me.uk> Message-ID: <20091102164809.GA11592@seas.upenn.edu> On Sun, Nov 01, 2009 at 11:27:42PM +0000, Philip Scott wrote: > .. and I am positive there must be a way of beautifying it, but I am > struggling. I bet there is just some lovely way of making this all shrink to > three lines.. > > So here's the problem. I have two lists of tuples: (timestamp, value) > > What I would like to do in do a kind of 'zip' on two of these lists to make a > list of (timestamp, (value1, value2)) with the following rules: > > - If the timestamps are equal it's easy - make your new element an move on > - If one of the lists has a timestamp that the other doesn't, repeat an old > value from the other list > - If we don't have an old value yet, then don't create an element in the new > list. Ask yourself: What Would Conal Do (WWCD)? Conal Elliott is always trying to get people to think about the semantic essence of their problems, so let's try it. What are we REALLY trying to do here? What are those lists of tuples, REALLY? Well, it seems to me that the lists of tuples are really just representing *functions* on some totally ordered domain. The list-of-pairs representation takes advantage of the fact that these functions tend to be constant on whole intervals of the domain; we only need a tuple to mark the *beginning* of a constant interval. The fact that we want to take a value from the last old timestamp when we don't have a certain timestamp in the list reflects the fact that the function takes on that value over the whole *interval* from the timestamp when it occurred to whenever the next timestamp is. So, let's try converting these lists of pairs to actual functions: asFunc :: (Ord a) => [(a,b)] -> (a -> Maybe b) asFunc is a = fmap snd . listToMaybe . reverse . takeWhile ((<=a) . fst) $ is Simple -- we just scan through the list looking for the right interval. Now the combining function is just a matter of converting the lists to functions, and applying those functions to each index we want in the output list (discarding any Nothings). combine :: (Ord a) => [(a,b)] -> [(a,c)] -> [(a,(b,c))] combine is js = catMaybes . flip map ixs $ \a -> fmap ((,) a) (liftA2 (,) (asFunc is a) (asFunc js a)) where ixs = sort . nub $ map fst is ++ map fst js Done! Now, you might object that this is much more inefficient than the other solutions put forth. That is very true. Converting to a function with 'asFunc' means that we do a linear-time lookup in the list every time we call the function, so this is O(n^2) overall instead of O(n). Building the list of indices ixs in the code above is also O(n^2) instead of O(n). However, I still find it very helpful to think about the essence of the problem like this: elegant yet inefficient code is a much better starting place than the other way around! From here there are several possibilities: maybe this version is efficient enough, if you'll only be working with small lists. Or you can also try to optimize, taking advantage of the fact that we always call the functions built by asFunc with a sequence of strictly increasing inputs. I might make a sort of "iterator" object which acts like a function (a -> Maybe b), but keeps some extra state so that as long as you call it with strictly increasing values of a, you get back a Maybe b (and a new iterator) in constant time. Of course, this is really what the other solutions are doing: but thinking about it this way has helped to structure the solution in a (hopefully) more clear and elegant way. -Brent From aditya.siram at gmail.com Mon Nov 2 14:34:05 2009 From: aditya.siram at gmail.com (aditya siram) Date: Mon Nov 2 14:10:18 2009 Subject: [Haskell-beginners] Finding documentation when Hackage is down. Message-ID: <594f78210911021134y72e7bd11t17cf3d4202530217@mail.gmail.com> Hi all, I use Hackage (through Hayoo sometimes) primarily for viewing API documentation. How can I store API docs for cabal-installed packages locally so I am not slowed down when Hackage goes down? -deech -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091102/a75726d8/attachment.html From mlesniak at uni-kassel.de Mon Nov 2 14:46:23 2009 From: mlesniak at uni-kassel.de (Michael Lesniak) Date: Mon Nov 2 14:22:38 2009 Subject: [Haskell-beginners] Finding documentation when Hackage is down. In-Reply-To: <594f78210911021134y72e7bd11t17cf3d4202530217@mail.gmail.com> References: <594f78210911021134y72e7bd11t17cf3d4202530217@mail.gmail.com> Message-ID: <5f8b37690911021146u74c3aedave6a55f5791470f93@mail.gmail.com> Hello, I find http://holumbus.fh-wedel.de/hayoo/hayoo.html very helpful :-) - Michael From aditya.siram at gmail.com Mon Nov 2 14:48:08 2009 From: aditya.siram at gmail.com (aditya siram) Date: Mon Nov 2 14:24:22 2009 Subject: [Haskell-beginners] Finding documentation when Hackage is down. In-Reply-To: <5f8b37690911021146u74c3aedave6a55f5791470f93@mail.gmail.com> References: <594f78210911021134y72e7bd11t17cf3d4202530217@mail.gmail.com> <5f8b37690911021146u74c3aedave6a55f5791470f93@mail.gmail.com> Message-ID: <594f78210911021148x23a5506bm4577753f19616575@mail.gmail.com> Yes, but it is my understanding that Hayoo connects to Hackage, so when Hackage is down, so is Hayoo :) -deech On Mon, Nov 2, 2009 at 2:46 PM, Michael Lesniak wrote: > Hello, > > I find http://holumbus.fh-wedel.de/hayoo/hayoo.html very helpful :-) > > - Michael > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091102/f77cce54/attachment.html From daniel.is.fischer at web.de Mon Nov 2 14:57:19 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Nov 2 14:39:30 2009 Subject: [Haskell-beginners] Finding documentation when Hackage is down. In-Reply-To: <594f78210911021134y72e7bd11t17cf3d4202530217@mail.gmail.com> References: <594f78210911021134y72e7bd11t17cf3d4202530217@mail.gmail.com> Message-ID: <200911022057.20272.daniel.is.fischer@web.de> Am Montag 02 November 2009 20:34:05 schrieb aditya siram: > Hi all, > I use Hackage (through Hayoo sometimes) primarily for viewing API > documentation. How can I store API docs for cabal-installed packages > locally so I am not slowed down when Hackage goes down? > > -deech In your ~/.cabal/config file, uncomment the line -- documentation: True (or was it "-- documentation:" originally? In which case you'd have to write the "True" yourself.) Then cabal install will build haddocks for each package it installs and put the docs in the standard place (~/.cabal/share/doc/ for user installs, I think; /usr/local/share/doc for global installs, IIRC). From byorgey at seas.upenn.edu Mon Nov 2 16:10:16 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Nov 2 15:46:30 2009 Subject: [Haskell-beginners] Finding documentation when Hackage is down. In-Reply-To: <594f78210911021148x23a5506bm4577753f19616575@mail.gmail.com> References: <594f78210911021134y72e7bd11t17cf3d4202530217@mail.gmail.com> <5f8b37690911021146u74c3aedave6a55f5791470f93@mail.gmail.com> <594f78210911021148x23a5506bm4577753f19616575@mail.gmail.com> Message-ID: <20091102211016.GA27450@seas.upenn.edu> I'm pretty sure this isn't true: Hayoo has its own index (which is periodically rebuilt from Hackage, but it doesn't need to connect to Hackage normally). Of course, if Hayoo gives you links to documentation on Hackage in its search results, THOSE won't work... -Brent On Mon, Nov 02, 2009 at 02:48:08PM -0500, aditya siram wrote: > Yes, but it is my understanding that Hayoo connects to Hackage, so when > Hackage is down, so is Hayoo :) > -deech > > On Mon, Nov 2, 2009 at 2:46 PM, Michael Lesniak wrote: > > > Hello, > > > > I find http://holumbus.fh-wedel.de/hayoo/hayoo.html very helpful :-) > > > > - Michael > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From gjk.liu at gmail.com Mon Nov 2 22:21:03 2009 From: gjk.liu at gmail.com (Liu Jian) Date: Mon Nov 2 21:57:16 2009 Subject: [Haskell-beginners] about model checking of haskell program Message-ID: <8c2dc7030911021921l243c4da2vf7d4044a56aa15b6@mail.gmail.com> Dear, Is there any work about "model checking haskell program"? in my opinion, think the haskell as a specification language, then we can check it or transform it to other specification language (such as, promela), so can be analyzed. cheers, Liu Jian ---- email to: gjk.liu@gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091102/86280fb0/attachment.html From mpm at alumni.caltech.edu Tue Nov 3 21:26:17 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Tue Nov 3 21:02:35 2009 Subject: [Haskell-beginners] I have created an ugly Haskell program.. In-Reply-To: <20091102164809.GA11592@seas.upenn.edu> References: <200911012327.43027.haskell-beginners@foo.me.uk> <20091102164809.GA11592@seas.upenn.edu> Message-ID: <4AF0E649.60908@alumni.caltech.edu> Thanks, Brent, for this way of looking at it. If you want n log n behavior you could write asFunc to use a Map for lookup. -Mike Brent Yorgey wrote: > > Ask yourself: What Would Conal Do (WWCD)? Conal Elliott is always > trying to get people to think about the semantic essence of their > problems, so let's try it. > > What are we REALLY trying to do here? What are those lists of tuples, > REALLY? Well, it seems to me that the lists of tuples are really just > representing *functions* on some totally ordered domain. The > list-of-pairs representation takes advantage of the fact that these > functions tend to be constant on whole intervals of the domain; we > only need a tuple to mark the *beginning* of a constant interval. The > fact that we want to take a value from the last old timestamp when we > don't have a certain timestamp in the list reflects the fact that the > function takes on that value over the whole *interval* from the > timestamp when it occurred to whenever the next timestamp is. > > So, let's try converting these lists of pairs to actual functions: > > > asFunc :: (Ord a) => [(a,b)] -> (a -> Maybe b) > asFunc is a = fmap snd . listToMaybe . reverse . takeWhile ((<=a) . fst) $ is > > > Simple -- we just scan through the list looking for the right > interval. > From mpm at alumni.caltech.edu Tue Nov 3 21:29:46 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Tue Nov 3 21:06:11 2009 Subject: [Haskell-beginners] order of monad transformers Message-ID: <4AF0E71A.5090202@alumni.caltech.edu> How does one consider the best ordering of monad transformers? For example, if I'm combining ErrorT, StateT (or State), and WriterT (or Writer)? But not just this specific example---what principles can one consult to determine ordering? Thanks, Mike From stephen.tetley at gmail.com Wed Nov 4 04:49:02 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Wed Nov 4 04:25:14 2009 Subject: [Haskell-beginners] order of monad transformers In-Reply-To: <4AF0E71A.5090202@alumni.caltech.edu> References: <4AF0E71A.5090202@alumni.caltech.edu> Message-ID: <5fdc56d70911040149j6d718b27v835e34acdbdd528@mail.gmail.com> > {-# LANGUAGE GeneralizedNewtypeDeriving #-} Hello Mike If the is a principal as such, I'd suggest that's working out the return type that you want your run function to have. Or more plainly - work out what you want the result to be. Thats a bit gnomic of course, so here are two examples with ErrorT (for failure) and WriterT (for logging), the ErrMsg type is contrived slightly to be a distinct type. This message should be literate Haskell if my mail service likes me: > module Transforming where > import Control.Monad.Error > import Control.Monad.Identity > import Control.Monad.Writer > type Log = String > newtype ErrMsg = ErrMsg { getMsg :: String } deriving Show > newtype EWI a = EWI { > getEWI :: ErrorT ErrMsg (WriterT Log Identity) a } > deriving (Functor, Monad, MonadWriter Log, MonadError ErrMsg) The run functions are pretty /natural/ just the run functions of the monad transformer stack in the reverse order. Note the /outer tupling/ over the Either type in the run function - runEWI always returns a log regardless of whether the computation fails with an error... [ without embellishments: (Either _ _,_) ] > runEWI :: EWI a -> (Either ErrMsg a, Log) > runEWI ma = runIdentity (runWriterT (runErrorT (getEWI ma))) > newtype WEI a = WEI { > getWEI :: WriterT Log (ErrorT ErrMsg Identity) a } > deriving (Functor, Monad, MonadWriter Log, MonadError ErrMsg) Note the Either type has an inner tuple in the run function - runWEI returns a log /only/ when the computation succeeds otherwise it fails with just an error... [ without embellishments: Either _ (_,_) ] > runWEI :: WEI a -> Either ErrMsg (a, Log) > runWEI ma = runIdentity (runErrorT (runWriterT (getWEI ma))) Support code > instance Error ErrMsg where > noMsg = ErrMsg "" > strMsg = ErrMsg From stephen.tetley at gmail.com Wed Nov 4 05:13:13 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Wed Nov 4 04:49:21 2009 Subject: [Haskell-beginners] order of monad transformers In-Reply-To: <5fdc56d70911040149j6d718b27v835e34acdbdd528@mail.gmail.com> References: <4AF0E71A.5090202@alumni.caltech.edu> <5fdc56d70911040149j6d718b27v835e34acdbdd528@mail.gmail.com> Message-ID: <5fdc56d70911040213s6b598a9drff09d5ff7a338236@mail.gmail.com> Apologies - the paragraph of the last message was riddled with typos, it should read: If there is a principal as such, I'd suggest that it's working out the return type you want your run function to have. Or more plainly - work out what you want the result to be. > > If the is a principal as such, I'd suggest that's working > out the return type that you want your run function to have. > Or more plainly - work out what you want the result to be. > Best wishes Stephen From byorgey at seas.upenn.edu Wed Nov 4 07:42:02 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Wed Nov 4 07:18:09 2009 Subject: [Haskell-beginners] order of monad transformers In-Reply-To: <4AF0E71A.5090202@alumni.caltech.edu> References: <4AF0E71A.5090202@alumni.caltech.edu> Message-ID: <20091104124202.GA29790@seas.upenn.edu> On Tue, Nov 03, 2009 at 06:29:46PM -0800, Michael Mossey wrote: > How does one consider the best ordering of monad transformers? For example, > if I'm combining ErrorT, StateT (or State), and WriterT (or Writer)? But > not just this specific example---what principles can one consult to > determine ordering? As Stephen has illustrated, the principle is that the effects of _inner_ transformers can "override" the effects of _outer_ transformers. (This has often seemed unintuitive and "backwards" to me, but that's the way it is.) For example, consider StateT s (FooT ...): if FooT has a failure mode, when a computation fails you don't even get a state anymore. Or if FooT has some sort of backtracking effect, the state will get rewound along with the rest of the computation. On the other hand, FooT (StateT s ....) will still compute a state even when the FooT fails, and the state will be preserved even when the computation backtracks. -Brent From mpm at alumni.caltech.edu Wed Nov 4 07:50:15 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Wed Nov 4 07:26:26 2009 Subject: [Haskell-beginners] order of monad transformers In-Reply-To: <5fdc56d70911040149j6d718b27v835e34acdbdd528@mail.gmail.com> References: <4AF0E71A.5090202@alumni.caltech.edu> <5fdc56d70911040149j6d718b27v835e34acdbdd528@mail.gmail.com> Message-ID: <4AF17887.7030604@alumni.caltech.edu> Thanks Stephen and Brent! I will try working out the examples you gave. I don't immediate comprehend Brent's explanation, but I think I will need to actually code and run some examples and then I'll probably get it. Thanks, Mike From apfelmus at quantentunnel.de Wed Nov 4 12:21:17 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Wed Nov 4 11:58:12 2009 Subject: [Haskell-beginners] Re: I have created an ugly Haskell program.. In-Reply-To: <20091102164809.GA11592@seas.upenn.edu> References: <200911012327.43027.haskell-beginners@foo.me.uk> <20091102164809.GA11592@seas.upenn.edu> Message-ID: Brent Yorgey wrote: > Ask yourself: What Would Conal Do (WWCD)? Conal Elliott is always > trying to get people to think about the semantic essence of their > problems, so let's try it. > > What are we REALLY trying to do here? What are those lists of tuples, > REALLY? Well, it seems to me that the lists of tuples are really just > representing *functions* on some totally ordered domain. > [...] > > So, let's try converting these lists of pairs to actual functions: > > > asFunc :: (Ord a) => [(a,b)] -> (a -> Maybe b) > asFunc is a = fmap snd . listToMaybe . reverse . takeWhile ((<=a) . fst) $ is > > [...] > > Now, you might object that this is much more inefficient than the > other solutions put forth. That is very true. [...] > > However, I still find it very helpful to think about the essence > of the problem like this: elegant yet inefficient code is a much > better starting place than the other way around! [...] > > You can also try to optimize, taking advantage of the fact that we > always call the functions built by asFunc with a sequence of strictly > increasing inputs. I am with Brent and Conal here. Now, to continue, ask yourself: What Would Conal Do Next (WWCDN)? What are we really trying to do here? What is this function, really, considering that we are only evaluating it at a strictly increasing sequence of inputs? Well, it seems to me that it is some special kind of function, best captured as an *abstract data type*. In particular, the function is something which I will call a "time series". In other words, the input is to be thought of as time. data Time t = Moment t | Infinity deriving (Eq,Ord,Show) The inclusion of infinity will turn out to be very convenient. Now, the time series is a function that has a value x1 in the distant past, until a time t1 where it begins to have the value x2 , again until a time t2 where it switches to x3 and so on, until a value xn that is kept until infinity. In Haskell, this looks like this function t | -Infinity <= t && t < t1 = x1 | t1 <= t && t < t2 = x2 | t2 <= t && t < t3 = x3 | ... | t1 <= t && t < Infinity = xn and pictorially, something like this: ____ xn _____ ____ x2 ____ | | |____ x3 ____ ... | _____ x1 ____| -Inf t1 t2 ... tn Inf Of course, we can implement this abstract data type with a list of pairs (tk,xk) newtype TimeSeries t a = TS { unTS :: [(a,Time t)] } deriving (Show) and our goal is to equip this data type with a few natural operations that can be used to implement Philip's zip-like function. The first two operations are progenitor :: TimeSeries t a -> a progenitor = fst . head . unTS which returns the value from the distant past and beginning :: TimeSeries t a -> Time t beginning = snd . head . unTS which returns the first point in time when the function changes its value. These correspond to the operation head on lists. The next operation is called `forgetTo` t and will throw away all values and changes before and including a given time t . forgetTo :: Ord t => TimeSeries t a -> Time t -> TimeSeries t a forgetTo (TS xs) Infinity = TS [last xs] forgetTo (TS xs) t = TS $ dropWhile ((<= t) . snd) xs This roughly corresponds to tail , but takes advantage of the time being continuous. Last but not least, we need a way to create a time series forever :: a -> TimeSeries t a forever x = TS [(x,Infinity)] and we need to add values to a time series, which can be done with an operation called prepend that adds a new beginning and replaces the progenitor . -- We assume that t < beginning xs prepend :: a -> Time t -> TimeSeries t a -> TimeSeries t a prepend x Infinity _ = TS [(x,Infinity)] prepend x t (TS xs) = TS $ (x,t) : xs These operations correspond to [] and (:) for lists. The key about these operations is that they have a description / intuition that is *independent* of the implementation of times series. At no point do we need to know how exactly TimeSeries is implemented to understand what these five operations do. Now, Philip's desired zip-like function is straightforward to implement: zipSeries :: Ord t => TimeSeries t a -> TimeSeries t b -> TimeSeries t (a,b) zipSeries xs ys = prepend (progenitor xs, progenitor ys) t $ zipSeries (xs `forgetTo` t) (ys `forgetTo` t) where t = min (beginning xs) (beginning ys) and you may want to convince yourself of its correctness by appealing to the intuition behind time series. Regards, apfelmus -- http://apfelmus.nfshost.com From plarrive at sfu.ca Wed Nov 4 19:02:47 2009 From: plarrive at sfu.ca (Patrick Larrivee-Woods) Date: Wed Nov 4 18:35:11 2009 Subject: [Haskell-beginners] Does System.Directory work on Windows XP? Message-ID: <4AF21627.5030208@sfu.ca> Hi, I"m having trouble getting the System.Directory module in ghci on a Windows XP machine. Whenever I call a function like getCurrentDirectory or getDirectoryContents I get no results back. I was wondering if anyone knows why this is happening, or if someone can point me to a module that works on Windows. Here's an example of what I get: ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.4.2, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base-1.0 ... linking ... done. Prelude> :module System.Directory Prelude System.Directory> getCurrentDirectory Prelude System.Directory> getDirectoryContents "." Prelude System.Directory> getDirectoryContents "c:\\perl" Prelude System.Directory> From jason.dusek at gmail.com Wed Nov 4 19:02:49 2009 From: jason.dusek at gmail.com (Jason Dusek) Date: Wed Nov 4 18:38:54 2009 Subject: [Haskell-beginners] Does System.Directory work on Windows XP? In-Reply-To: <4AF21627.5030208@sfu.ca> References: <4AF21627.5030208@sfu.ca> Message-ID: <42784f260911041602h32aa484cg391e8ad3f583a592@mail.gmail.com> Could you try a recent version of GHC and let us know if you still have trouble? -- Jason Dusek From plarrive at sfu.ca Wed Nov 4 19:14:59 2009 From: plarrive at sfu.ca (Patrick Larrivee-Woods) Date: Wed Nov 4 18:47:18 2009 Subject: [Haskell-beginners] Does System.Directory work on Windows XP? In-Reply-To: <42784f260911041602h32aa484cg391e8ad3f583a592@mail.gmail.com> References: <4AF21627.5030208@sfu.ca> <42784f260911041602h32aa484cg391e8ad3f583a592@mail.gmail.com> Message-ID: <4AF21903.3070009@sfu.ca> With 6.10.4 it works fine. Thanks for your help, I hadn't even realized I was using an older version. Cheers, Patrick Jason Dusek wrote: > Could you try a recent version of GHC and let us know if you > still have trouble? > > -- > Jason Dusek > From daniel.is.fischer at web.de Wed Nov 4 19:59:12 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Nov 4 19:36:43 2009 Subject: [Haskell-beginners] Does System.Directory work on Windows XP? In-Reply-To: <4AF21903.3070009@sfu.ca> References: <4AF21627.5030208@sfu.ca> <42784f260911041602h32aa484cg391e8ad3f583a592@mail.gmail.com> <4AF21903.3070009@sfu.ca> Message-ID: <200911050159.12432.daniel.is.fischer@web.de> Am Donnerstag 05 November 2009 01:14:59 schrieb Patrick Larrivee-Woods: > With 6.10.4 it works fine. Thanks for your help, I hadn't even realized > I was using an older version. > > Cheers, > Patrick Just to explain: getDirectoryContents "." is an IO action producing a String. In newer GHC releases (I don't remember whther that change came with 6.6 or 6.8), when you invoke an IO action from the ghci-prompt, if the value returned from the action has not type (), by default it is bound to the variable 'it' and printed out (since it's not unconditionally a good thing to do that - consider readFile "HUGEFile.txt" - it can be disabled via ghci> :set -fno-print-bind-result - re-enable with -fprint-bind-result). Before, the action was simply run and its result not printed out, to use the result of an IO action, you had to use ghci> res <- getDirectoryContents "." ghci> print res or ghci> getDirectoryContents "." >>= mapM_ putStrLn or whatever. If you still have 6.4.2 installed, you can try it out (but do your real work with the newer, it produces better code). > > Jason Dusek wrote: > > Could you try a recent version of GHC and let us know if you > > still have trouble? > > > > -- > > Jason Dusek From aleks.dimitrov at googlemail.com Thu Nov 5 06:01:11 2009 From: aleks.dimitrov at googlemail.com (Aleksandar Dimitrov) Date: Thu Nov 5 05:37:15 2009 Subject: [Haskell-beginners] Lazy file IO & Space leaks/waste Message-ID: <20091105110110.GA7313@bylha.uni-tuebingen.de> Hello list, I'm currently writing a small linguistic corpus analyzer. My input file is only 25MB, but profiling shows that the overall amount of allocation over the program's runtime is several GB. That's a little too much - adding to that is the fact that the program is abysmally slow, so I'm suspecting a space leak somewhere. I'm using the ByteString.Lazy.Char8 class in order to work efficiently with lazy IO and I must admit that I'm very inexperienced with predicting runtime and space behaviour of lazy IO :-( It worked well in the past, but I'm stuck now. The program can be found here: http://hpaste.org/fastcgi/hpaste.fcgi/view?id=11863#a11863 The important bits are as follows: > mf :: [C.ByteString] -> StdWord > mf [] = Word [] C.empty > mf s = Word (tail s) (head s) > > f' = mf . reverse . C.words > main :: IO () > main = do > corpus_name <- liftM head getArgs > corpus <- liftM (Corpus . (map f') . C.lines) $ C.readFile corpus_name > print $ length (content corpus) > let interesting = filterForInterestingTags interestingTags corpus > print $ show (freqMap interesting) freqMap also uses foldr' to fold the corpus it is given into a Data.Map, but according to the profiling output, that's not where the bad stuff happens. Here's the interesting parts of the profiling output: > analyse +RTS -p -RTS corpus/bnc-samp.tt > > total time = 30.46 secs (1523 ticks @ 20 ms) > total alloc = 14,871,619,904 bytes (excludes profiling overheads) > > COST CENTRE MODULE no. entries %time %alloc %time %alloc > > MAIN MAIN 1 0 0.0 0.0 100.0 100.0 > main Main 221 0 0.0 0.0 0.0 0.0 > CAF Main 206 14 0.1 0.1 100.0 100.0 > showsPrec_aSF Main 223 1 0.0 0.0 0.0 0.0 > interestingTags Main 218 1 0.0 0.0 0.0 0.0 > f' Main 216 1 0.0 0.0 0.0 0.0 > mf Main 217 1 0.0 0.0 0.0 0.0 > main Main 212 1 2.4 4.4 99.9 99.9 > f' Main 219 0 89.0 91.5 90.2 92.7 > mf Main 220 2427450 1.2 1.2 1.2 1.2 > filterForInterestingTags Main 215 1 5.4 0.1 5.4 0.1 > freqMap Main 214 1 0.6 0.5 2.0 2.7 > compare_aRL Main 222 1141996 1.4 2.2 1.4 2.2 Obviously the main cost centre seems to be f' (which I've factored out in order to view it separately as a cost centre.) It's not the call to reverse that makes it slow (removing it doesn't affect the run time.) Interestingly, it prints out the first statement (length) very quickly, then takes a lot of time. I've removed the call to freqMap, and it seems that GHC is smart enough to drop the call to f' completely, because only the length ever gets evaluated. But the freqMap also needs the processing from f', and that's where the bad stuff starts happening. Should I look into DeepSeq? I've tried adding strictness to the functions by hand, and also to the data structures, but that didn't seem to help so far. So I'm looking for solutions to make this faster. I'm guessing that a smart `seq` somewhere might help, but I don't know where :-\ As a side note: how can I find out how the run-time data structures look like in memory? I.e. I want to know *what* exactly stays around as thunks in memory so that I can focus better on where to add strictness or redirect the program flow. Ideally, only a very smart part of the file should ever be in memory, with processing happening incrementally! Thanks for any pointers! Aleks -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available Url : http://www.haskell.org/pipermail/beginners/attachments/20091105/5917de71/attachment.bin From nathanmholden at gmail.com Thu Nov 5 21:05:22 2009 From: nathanmholden at gmail.com (Nathan M. Holden) Date: Thu Nov 5 20:41:31 2009 Subject: [Haskell-beginners] if ands Message-ID: <200911052105.22124.nathanmholden@gmail.com> If you have an if statement like if (a&&b) then fun else fun' and a is false, does GHC actually bother to check b? From jfredett at gmail.com Thu Nov 5 21:09:13 2009 From: jfredett at gmail.com (Joe Fredette) Date: Thu Nov 5 20:45:19 2009 Subject: [Haskell-beginners] if ands In-Reply-To: <200911052105.22124.nathanmholden@gmail.com> References: <200911052105.22124.nathanmholden@gmail.com> Message-ID: <0C6944E9-12D2-4E97-8358-46F3CAAB17CF@gmail.com> No, consider the definition of (&&) -- I hope this is the def from the prelude. If it's not, then it's probably isomorphic... (&&) :: Bool -> Bool -> Bool True && x = x False && _ = False Since (&&) ignores it's second argument if the first is false, then it will "Short circuit" (like most `&` operators in other languages) due to lazy evaluation. /Joe On Nov 5, 2009, at 9:05 PM, Nathan M. Holden wrote: > If you have an if statement like > > if (a&&b) then fun else fun' > > and a is false, does GHC actually bother to check b? > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From keithshep at gmail.com Thu Nov 5 21:12:49 2009 From: keithshep at gmail.com (Keith Sheppard) Date: Thu Nov 5 20:48:52 2009 Subject: [Haskell-beginners] if ands In-Reply-To: <200911052105.22124.nathanmholden@gmail.com> References: <200911052105.22124.nathanmholden@gmail.com> Message-ID: <92e42b740911051812j2042cf78pb6f587b6049051bf@mail.gmail.com> Also, an nice way to check how evaluation works in ghci is to do something like: > if False && error "error here" then "it's true" else "it's false" This expression will evaluate as "it's false" without any "error here" error message appearing On Thu, Nov 5, 2009 at 9:05 PM, Nathan M. Holden wrote: > If you have an if statement like > > if (a&&b) then fun else fun' > > and a is false, does GHC actually bother to check b? > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- keithsheppard.name From ryantemple145 at googlemail.com Wed Nov 4 07:04:08 2009 From: ryantemple145 at googlemail.com (Ryan Temple) Date: Thu Nov 5 21:42:31 2009 Subject: [Haskell-beginners] N-ary tree search problems Message-ID: <33ff8d520911040404h2db6f4c8k473e1b87e2b35dd6@mail.gmail.com> I'm making a general purpose N-ary tree and im coming up with "unexpected '=' on line 17" as an error. I have spent a fair while trying to work out why this isn't accepting the case that an Empty gtree returns false for any member search. i realise this is probably a very trivial error but any help would be appreciated: module GTrees where data Gtree = Empty | Leaf String | Node String [Gtree] deriving (Show) --Tests if a given string is a member of the tree gtreeMember :: (Ord a) => a -> Gtree a -> Bool gtreeMember y Empty = False -- line 17 gtreeMember y (Leaf x) = (x==y) gtreeMember y (Node x tree) |x==y = True |otherwise gtreeMember tree This is the code up to the point of the error with the error line highlighted -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091104/18de551b/attachment.html From iaefai at me.com Thu Nov 5 22:10:04 2009 From: iaefai at me.com (=?iso-8859-1?Q?i=E6fai?=) Date: Thu Nov 5 21:46:15 2009 Subject: [Haskell-beginners] N-ary tree search problems In-Reply-To: <33ff8d520911040404h2db6f4c8k473e1b87e2b35dd6@mail.gmail.com> References: <33ff8d520911040404h2db6f4c8k473e1b87e2b35dd6@mail.gmail.com> Message-ID: Try to make sure things are lined up properly, like the Empty and Left, and why are some gtreeMember indented? On 2009-11-04, at 7:04 AM, Ryan Temple wrote: > I'm making a general purpose N-ary tree and im coming up with > "unexpected > '=' on line 17" as an error. I have spent a fair while trying to > work out > why this isn't accepting the case that an Empty gtree returns false > for any > member search. i realise this is probably a very trivial error but > any help > would be appreciated: > > module GTrees where > > data Gtree = Empty | > Leaf String | > Node String [Gtree] > deriving (Show) > > --Tests if a given string is a member of the tree > > gtreeMember :: (Ord a) => a -> Gtree a -> Bool > gtreeMember y Empty = False -- line 17 > gtreeMember y (Leaf x) = (x==y) > gtreeMember y (Node x tree) > |x==y = True > |otherwise gtreeMember tree > > This is the code up to the point of the error with the error line > highlighted > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From nathanmholden at gmail.com Fri Nov 6 00:31:05 2009 From: nathanmholden at gmail.com (Nathan M. Holden) Date: Fri Nov 6 00:07:10 2009 Subject: [Haskell-beginners] Show Floats Message-ID: <200911060031.05956.nathanmholden@gmail.com> I have been working on a small library that will typeset notes in LaTeX for me, since I tend to have haphazard typesetting while I write, but while I read I like to have standards. Anyways, I defined a datatype data Color = RGB { name :: [Char], r :: Float, g :: Float, b :: Float, matchText :: [[Char]], targetText :: [Char]} deriving(Show,Eq,Read) I wanted to be able to have a piece of code that said "\\definecolor{"++name++"}{rgb}{"++show r++","++show g++","++show b++"}" but because I have numbers below 0.1, it outputs as 2.0e-2, which is useless. I wrote a function that would output useful numbers, but it's REALLY bad Haskell: fToInt :: Float -> Int fToInt f = if f >= 10 then fToInt (f-10.0) else if (f >= 9) then 9 else if (f >= 8) then 8 else if (f >= 7) then 7 else if (f >= 6) then 6 else if (f >= 5) then 5 else if (f >= 4) then 4 else if (f >= 3) then 3 else if (f >= 2) then 2 else if (f >= 1) then 1 else 0 It takes up 11 lines in a module that's only got 74! (128 if you count the module to translate the notes into a .tex file) how would I write this better? From iaefai at me.com Fri Nov 6 00:36:06 2009 From: iaefai at me.com (=?iso-8859-1?Q?i=E6fai?=) Date: Fri Nov 6 00:12:23 2009 Subject: [Haskell-beginners] Show Floats In-Reply-To: <200911060031.05956.nathanmholden@gmail.com> References: <200911060031.05956.nathanmholden@gmail.com> Message-ID: <74DAF871-6666-4A07-A07A-CA2E4E675D6C@me.com> Look at the 'floor' function. It would simplify a lot of cases for sure. But I suspect there is a better way to do that function as a whole. On 2009-11-06, at 12:31 AM, Nathan M. Holden wrote: > I have been working on a small library that will typeset notes in > LaTeX for > me, since I tend to have haphazard typesetting while I write, but > while I read > I like to have standards. > > Anyways, I defined a datatype > > data Color = RGB { > name :: [Char], > r :: Float, > g :: Float, > b :: Float, > matchText :: [[Char]], > targetText :: [Char]} > deriving(Show,Eq,Read) > > I wanted to be able to have a piece of code that said > > "\\definecolor{"++name++"}{rgb}{"++show r++","++show g++","++show > b++"}" > > but because I have numbers below 0.1, it outputs as 2.0e-2, which is > useless. I wrote a function that would output useful numbers, but > it's REALLY > bad Haskell: > > fToInt :: Float -> Int > fToInt f = if f >= 10 then fToInt (f-10.0) > else if (f >= 9) then 9 > else if (f >= 8) then 8 > else if (f >= 7) then 7 > else if (f >= 6) then 6 > else if (f >= 5) then 5 > else if (f >= 4) then 4 > else if (f >= 3) then 3 > else if (f >= 2) then 2 > else if (f >= 1) then 1 else 0 > > It takes up 11 lines in a module that's only got 74! (128 if you > count the > module to translate the notes into a .tex file) > > how would I write this better? > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From nathanmholden at gmail.com Fri Nov 6 00:59:26 2009 From: nathanmholden at gmail.com (Nathan M. Holden) Date: Fri Nov 6 00:35:32 2009 Subject: [Haskell-beginners] Show Floats Message-ID: <200911060059.26931.nathanmholden@gmail.com> Um... well, I solved my own problem. It turns out that my 20-30 minutes of searching for a way to \definecolor in terms of 0-255 instead of 0.0-1.0 were just 5 minutes short of finding out a way to do it. This is embarrassing. From dav.vire+haskell at gmail.com Fri Nov 6 02:32:15 2009 From: dav.vire+haskell at gmail.com (David Virebayre) Date: Fri Nov 6 02:08:19 2009 Subject: [Haskell-beginners] Show Floats In-Reply-To: <200911060059.26931.nathanmholden@gmail.com> References: <200911060059.26931.nathanmholden@gmail.com> Message-ID: <4c88418c0911052332v580c1a91k479e3d8ccb613f01@mail.gmail.com> On Fri, Nov 6, 2009 at 6:59 AM, Nathan M. Holden wrote: > Um... well, I solved my own problem. > > It turns out that my 20-30 minutes of searching for a way to \definecolor > in > terms of 0-255 instead of 0.0-1.0 were just 5 minutes short of finding out > a > way to do it. > > This is embarrassing. > If you have this problem again, you can use printf : GHCi, version 6.10.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer ... linking ... done. Loading package base ... linking ... done. Prelude> import Text.Printf Prelude Text.Printf> let f=0.001 Prelude Text.Printf> f 1.0e-3 Prelude Text.Printf> printf "%5.4f\n" f 0.0010 Prelude Text.Printf> > _______________________________________________ > 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/20091106/b74b4f83/attachment.html From johannes.laire at gmail.com Fri Nov 6 02:39:40 2009 From: johannes.laire at gmail.com (Johannes Laire) Date: Fri Nov 6 02:15:44 2009 Subject: [Haskell-beginners] Show Floats In-Reply-To: <4c88418c0911052332v580c1a91k479e3d8ccb613f01@mail.gmail.com> References: <200911060059.26931.nathanmholden@gmail.com> <4c88418c0911052332v580c1a91k479e3d8ccb613f01@mail.gmail.com> Message-ID: <5f271a760911052339r3bd79aban85ded4970cb39330@mail.gmail.com> On Fri, Nov 6, 2009 at 9:32 AM, David Virebayre wrote: > On Fri, Nov 6, 2009 at 6:59 AM, Nathan M. Holden > wrote: >> >> Um... well, I solved my own problem. >> >> It turns out that my 20-30 minutes of searching for a way to \definecolor >> in >> terms of 0-255 instead of 0.0-1.0 were just 5 minutes short of finding out >> a >> way to do it. >> >> This is embarrassing. > > If you have this problem again, you can use printf : There's also Numeric: http://www.haskell.org/ghc/docs/latest/html/libraries/base/Numeric.html Prelude> Numeric.showFFloat (Just 4) 0.001 "" "0.0010" -- Johannes Laire From deniz.a.m.dogan at gmail.com Fri Nov 6 04:03:16 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Fri Nov 6 03:39:38 2009 Subject: [Haskell-beginners] if ands In-Reply-To: <92e42b740911051812j2042cf78pb6f587b6049051bf@mail.gmail.com> References: <200911052105.22124.nathanmholden@gmail.com> <92e42b740911051812j2042cf78pb6f587b6049051bf@mail.gmail.com> Message-ID: <7b501d5c0911060103n3f54d8a7m55da916879c18afe@mail.gmail.com> 2009/11/6 Keith Sheppard : > Also, an nice way to check how evaluation works in ghci is to do something like: > >> if False && error "error here" then "it's true" else "it's false" > > This expression will evaluate as "it's false" without any "error here" > error message appearing > > On Thu, Nov 5, 2009 at 9:05 PM, Nathan M. Holden > wrote: >> If you have an if statement like >> >> if (a&&b) then fun else fun' >> >> and a is false, does GHC actually bother to check b? > Note that Haskell is far from the only programming language that is smart about this. I actually can't think of a single programming language implementation that I know of which isn't this smart... For what it's worth, Haskell (and others) is smart about ORs as well. In (x || y), y will only be evaluated if x is False. -- Deniz Dogan From stephen.tetley at gmail.com Fri Nov 6 04:15:20 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Nov 6 03:51:25 2009 Subject: [Haskell-beginners] N-ary tree search problems In-Reply-To: References: <33ff8d520911040404h2db6f4c8k473e1b87e2b35dd6@mail.gmail.com> Message-ID: <5fdc56d70911060115o4db4f36bh67dea12c4a270c88@mail.gmail.com> Hello Ryan As iaefai said, consistent indentation is the key. But you also have a problem with the type signature of gtreeMember gtreeMember :: (Ord a) => a -> Gtree a -> Bool The part ** Gtree a ** insists that you Gtree has a parametric type - think of list - [a] where a is type parameter, then concretely a list can hold any type e.g. [Int] a list of Int, [Bool] a list of Bool, and so on... However your Gtree type is not parametric - elements can only be **String**. So you need to change the signature of gtreeMember so that it explicitly uses Strings and correct Gtree so it doesn't have a type parameter: gtreeMember :: String -> Gtree -> Bool As there is no longer a type variable you no longer need the type constraint - Ord a. That gets things to work, but as you want a general purpose tree this specialization to Strings for the element isn't really what you need. Following on you would want to change the Gtree data type to be polymorphic on element, whence it will have a parametric type signature: data Gtree a = Empty | Leaf a | Node a [Gtree a] deriving (Show) (Trivia - I've changed the style to be have the line for each alternative constructor start with | which is more conventional, your tastes may vary. Ideally the pipes should line up with the equals, but as I'm typing with a variable width font I can't be sure). Note the ** Gtree a ** in the initial part of the data declaration, also note the ** Gtree a** in the recursive part of the Node constructor. Best wishes Stephen > On 2009-11-04, at 7:04 AM, Ryan Temple wrote: >> >> data Gtree = Empty | >> ? ? ? ? ? ?Leaf String | >> ? ? ? ? ? ?Node String [Gtree] >> ? ? ? ? ? ?deriving (Show) >> >> --Tests if a given string is a member of the tree >> >> gtreeMember :: (Ord a) => a -> Gtree a -> Bool >> ?gtreeMember y Empty = False ?-- line 17 >> ?gtreeMember y (Leaf x) = (x==y) >> ?gtreeMember y (Node x tree) >> ? ? |x==y = True >> ? ? |otherwise gtreeMember tree From nicolas.pouillard at gmail.com Fri Nov 6 04:25:22 2009 From: nicolas.pouillard at gmail.com (Nicolas Pouillard) Date: Fri Nov 6 04:01:25 2009 Subject: [Haskell-beginners] Lazy file IO & Space leaks/waste In-Reply-To: <20091105110110.GA7313@bylha.uni-tuebingen.de> References: <20091105110110.GA7313@bylha.uni-tuebingen.de> Message-ID: <1257499449-sup-6380@peray> Excerpts from Aleksandar Dimitrov's message of Thu Nov 05 12:01:11 +0100 2009: > Hello list, > > I'm currently writing a small linguistic corpus analyzer. My input file is only > 25MB, but profiling shows that the overall amount of allocation over the > program's runtime is several GB. That's a little too much - adding to that is > the fact that the program is abysmally slow, so I'm suspecting a space leak > somewhere. > > I'm using the ByteString.Lazy.Char8 class in order to work efficiently with lazy > IO and I must admit that I'm very inexperienced with predicting runtime and > space behaviour of lazy IO :-( It worked well in the past, but I'm stuck now. > > The program can be found here: > http://hpaste.org/fastcgi/hpaste.fcgi/view?id=11863#a11863 I've added a revision of your code and some highlights. The main one is to suggest foldl' instead of foldr'. However without the input text helping to improve is harder. -- Nicolas Pouillard http://nicolaspouillard.fr From stephen.tetley at gmail.com Fri Nov 6 04:36:39 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Nov 6 04:12:42 2009 Subject: [Haskell-beginners] if ands In-Reply-To: <7b501d5c0911060103n3f54d8a7m55da916879c18afe@mail.gmail.com> References: <200911052105.22124.nathanmholden@gmail.com> <92e42b740911051812j2042cf78pb6f587b6049051bf@mail.gmail.com> <7b501d5c0911060103n3f54d8a7m55da916879c18afe@mail.gmail.com> Message-ID: <5fdc56d70911060136u1bc81d59hac4b2392cc02f85c@mail.gmail.com> As Haskell uses lazy evaluation so (&&) and if can be functions, as Joe Fredette said previously. In say Lisp which is strict if has to be a primitive / special form and (&&) is likely definable only with if (or implemented as another primitive). In some senses Haskell doesn't need to be smart to be 'smart'. Best wishes Stephen 2009/11/6 Deniz Dogan : > 2009/11/6 Keith Sheppard : > Note that Haskell is far from the only programming language that is > smart about this. I actually can't think of a single programming > language implementation that I know of which isn't this smart... > > For what it's worth, Haskell (and others) is smart about ORs as well. > In (x || y), y will only be evaluated if x is False. > From Christian.Maeder at dfki.de Fri Nov 6 05:00:51 2009 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Fri Nov 6 04:36:55 2009 Subject: [Haskell-beginners] Re: N-ary tree search problems In-Reply-To: <33ff8d520911040404h2db6f4c8k473e1b87e2b35dd6@mail.gmail.com> References: <33ff8d520911040404h2db6f4c8k473e1b87e2b35dd6@mail.gmail.com> Message-ID: <4AF3F3D3.4040806@dfki.de> Ryan Temple schrieb: > I'm making a general purpose N-ary tree and im coming up with > "unexpected '=' on line 17" as an error. I have spent a fair while > trying to work out why this isn't accepting the case that an Empty gtree > returns false for any member search. i realise this is probably a very > trivial error but any help would be appreciated: > > module GTrees where > > data Gtree = Empty | > Leaf String | > Node String [Gtree] > deriving (Show) You may want to consider a node with a singleton list as "Leaf" and a node with an empty list as "Empty" (if the additional "String" for "Node" does not harm for an empty tree). > --Tests if a given string is a member of the tree > > gtreeMember :: (Ord a) => a -> Gtree a -> Bool > gtreeMember y Empty = False -- line 17 > gtreeMember y (Leaf x) = (x==y) > gtreeMember y (Node x tree) > |x==y = True > |otherwise gtreeMember tree After proper indentation and deciding if Gtree is polymorphic or not in the signature and data type, this last line will not work: 1. there must be a "=" following "otherwise" 2. gtreeMember expects two arguments 3. the variable "tree" is a list of Gtrees whereas gtreeMember only works for a single Gtree. HTH Christian From apfelmus at quantentunnel.de Fri Nov 6 06:06:57 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Fri Nov 6 05:43:25 2009 Subject: [Haskell-beginners] Re: Lazy file IO & Space leaks/waste In-Reply-To: <20091105110110.GA7313@bylha.uni-tuebingen.de> References: <20091105110110.GA7313@bylha.uni-tuebingen.de> Message-ID: Aleksandar Dimitrov wrote: > The important bits are as follows: > >> mf :: [C.ByteString] -> StdWord >> mf [] = Word [] C.empty >> mf s = Word (tail s) (head s) >> >> f' = mf . reverse . C.words > >> main :: IO () >> main = do >> corpus_name <- liftM head getArgs >> corpus <- liftM (Corpus . (map f') . C.lines) $ C.readFile corpus_name >> print $ length (content corpus) >> let interesting = filterForInterestingTags interestingTags corpus >> print $ show (freqMap interesting) > > [...] > > Ideally, only a very smart part of the file should ever be in memory, with > processing happening incrementally! The print $ length (content corpus) statement seems contradictory to your goal? After all, the whole file is read into the corpus variable to calculate its length . Regards, apfelmus -- http://apfelmus.nfshost.com From luislupe at gmail.com Fri Nov 6 08:58:16 2009 From: luislupe at gmail.com (Luis P. Mendes) Date: Fri Nov 6 08:34:18 2009 Subject: [Haskell-beginners] Is Haskell for me? Message-ID: Hi, I'd like to have some points of view on this subject. I need to start a project on neural analysis and genetic algorithms that will process many millions of records in a Linux X86_64 box (some development also in a X32 computer). Maybe I'll use fuzzy logic, or case-based reasoning, or decision trees, too. Recently, I finished a small project on genetic algorithms with Python, but since run-time is very important, my next project will need a fast language. Either I'll go to C++ or similar language or I'll try a functiional language - Haskell. Apart from some features in Python, I've never programmed thinking in a functional way. I'd like to avoid having to learn C++. I'd like to concentrate in getting the work done and Haskell seems like a solution. But... My questions are: - Is Haskell able to read (also write to a point) data from databases in a fast and reliable way? (MySql or PostgreSQL) - how could I program something like this in Haskell: .. generate random population .. for each one of the population: .. for time period 1 to ten million: .. evaluate method 1, 2, 3, 4, 5, 6, .... ..evaluate fitness of each one .. generate new population based on results of previous generation It seems relatively intuitive for me to program this in an imperative language. But what about in Haskell? - Is Haskell suitable to process data like this in a fast way (aproximate to C++?) - In order for Haskell to be fast, coding is done in a 'natural' way or with use of special hidden details of the language? - Although I always liked math, I no longer have the knowledge I used to have several years ago. Is this important to help program in this funcional language? - Are there graphical packages available to plot results or is it easy to connect it to a Python (or C) library? - Is code easily reusable in different future projects? Since it has no objects... how can it be done? Sorry for all these questions, but I really need to know about this and that's why I want to read answers from knowledgeable people. Luis From luca_ciciriello at hotmail.com Fri Nov 6 09:33:41 2009 From: luca_ciciriello at hotmail.com (Luca Ciciriello) Date: Fri Nov 6 09:09:45 2009 Subject: [Haskell-beginners] Is Haskell for me? In-Reply-To: References: Message-ID: Hi. Why not? A friend of mine is a resercher in AI and is an expert in Neural network (solution spaces, matrices, etc). His programming language is Haskell. He is very happy to use Haskell (on MacOS X) in its reserach. Personally I use Haskell with Postgres using HDBC or calling the postgress function in pqlib using the Haskell FFI (may favourite way). I'm also an experienced C++ programmer (12 years) and I can say that C++ is a very complex language to learn from scratch and master it. Now I'm finding a little bit hard to switch from an imperative language to a functional language. Anyway Haskell is a very beautiful and elegant and powerful language that you can use for everything. About using a GUI, I've never used one on Mac. Sorry. I know that exist a Haskell extension called GTK2HS (see: http://www.haskell.org/gtk2hs/). If you want to use GHC (the de-facto compiler for Haskell), the code produced is very fast and you have a very powerful support for concurrency and parallelism. For further information go to: http://www.haskell.org/ghc/ where you can find a lot of useful documentation and answers to ur questions. Luca. > Date: Fri, 6 Nov 2009 13:58:16 +0000 > From: luislupe@gmail.com > To: beginners@haskell.org > Subject: [Haskell-beginners] Is Haskell for me? > > Hi, > > I'd like to have some points of view on this subject. > > I need to start a project on neural analysis and genetic algorithms > that will process many millions of records in a Linux X86_64 box (some > development also in a X32 computer). Maybe I'll use fuzzy logic, or > case-based reasoning, or decision trees, too. > > Recently, I finished a small project on genetic algorithms with > Python, but since run-time is very important, my next project will > need a fast language. Either I'll go to C++ or similar language or > I'll try a functiional language - Haskell. > Apart from some features in Python, I've never programmed thinking in > a functional way. > I'd like to avoid having to learn C++. I'd like to concentrate in > getting the work done and Haskell seems like a solution. But... > > My questions are: > - Is Haskell able to read (also write to a point) data from databases > in a fast and reliable way? (MySql or PostgreSQL) > > - how could I program something like this in Haskell: > .. generate random population > .. for each one of the population: > .. for time period 1 to ten million: > .. evaluate method 1, 2, 3, 4, 5, 6, .... > ..evaluate fitness of each one > .. generate new population based on results of previous generation > > It seems relatively intuitive for me to program this in an imperative > language. But what about in Haskell? > > - Is Haskell suitable to process data like this in a fast way > (aproximate to C++?) > > - In order for Haskell to be fast, coding is done in a 'natural' way > or with use of special hidden details of the language? > > - Although I always liked math, I no longer have the knowledge I used > to have several years ago. Is this important to help program in this > funcional language? > > - Are there graphical packages available to plot results or is it easy > to connect it to a Python (or C) library? > > - Is code easily reusable in different future projects? Since it has > no objects... how can it be done? > > Sorry for all these questions, but I really need to know about this > and that's why I want to read answers from knowledgeable people. > > > Luis > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners _________________________________________________________________ New Windows 7: Simplify what you do everyday. Find the right PC for you. http://www.microsoft.com/uk/windows/buy/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091106/851a2e23/attachment.html From mauricio.antunes at gmail.com Fri Nov 6 10:28:41 2009 From: mauricio.antunes at gmail.com (=?ISO-8859-1?Q?Maur=ED=ADcio_CA?=) Date: Fri Nov 6 10:05:10 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: References: Message-ID: > - how could I program something like this in Haskell: .. > generate random population Since Haskell is a "pure" language, after you attribute a value to a variable they are glued together forever. So, the language itself can't have such a thing as a random number. (Here, someone with technical knowledge will probably correct me, but you get the poing.) Dealing with this (and other "outside world" stuff) requires learning how to deal with a special type construct called "Monad". It's the major step you will have to as a Haskell begginer. It's, though, extremely interesting, and extremely powerfull after you understand it. > - Although I always liked math, I no longer have the knowledge > I used to have several years ago. Is this important to help > program in this funcional language? No. But if you like math, you're probably going to find links to really interesting math while you learn. > (...) is it easy to connect it to a Python (or C) library? To C libraries the answer is yes. Actually, if I want to do C, I prefer to do it in Haskell :) A friend of mine, who uses neural networks in his MSc work, was impressed that in half an hour I could get better results using a low-level binding from libfann to Haskell (link below) than his own hand written code. http://hackage.haskell.org/package/bindings-fann > - Is code easily reusable in different future projects? Since it > has no objects... how can it be done? Yes, to a point you may find too radical at first. Even the most basic constructs are usually combinations of other pieces. After some time, you will start any code you write by searching pieces to join together instead of writing everything yourself. It is, though, usually easier to write code from scratch in Haskell than reuse code in imperative languages :) Biased opinions, of course, but I hope they help. Best, Maur?cio From matthias.guedemann at ovgu.de Fri Nov 6 11:22:04 2009 From: matthias.guedemann at ovgu.de (Matthias Guedemann) Date: Fri Nov 6 11:00:48 2009 Subject: [Haskell-beginners] Applicative Parsec Message-ID: <1257523871-sup-7114@pc44es141.cs.uni-magdeburg.de> Hi, what is the benefit if you use Applicative for Parsec instead of Monad? I wrote a converter from a textfile format to a csv file. In order to get more familiar with Haskell I wrote it using Parsec. At first I had some difficulties and the monadic version seemed easier, but now it works as Applicative version and Parsec seems really straightforward. For me, the Applicative version looks more functional and the monadic version looks more imperative. It seems that Applicative is enough for Parsers (think I remember a citation somewhere), but does it have a real advantage? best regards, Matthias -- __________________________________________________________ ___ __ __ Dipl. Inf. Matthias Guedemann / __\/ _\ /__\ Computer Systems in Engineering / / \ \ /_\ Otto-von-Guericke Universitaet Magdeburg / /___ _\ \//__ Tel.: 0391 / 67-19359 \____/ \__/\__/ __________________________________________________________ From byorgey at seas.upenn.edu Fri Nov 6 11:49:05 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Fri Nov 6 11:25:05 2009 Subject: [Haskell-beginners] Applicative Parsec In-Reply-To: <1257523871-sup-7114@pc44es141.cs.uni-magdeburg.de> References: <1257523871-sup-7114@pc44es141.cs.uni-magdeburg.de> Message-ID: <20091106164905.GA27242@seas.upenn.edu> On Fri, Nov 06, 2009 at 05:22:04PM +0100, Matthias Guedemann wrote: > > I wrote a converter from a textfile format to a csv file. In order to get more > familiar with Haskell I wrote it using Parsec. > At first I had some difficulties and the monadic version seemed easier, but now > it works as Applicative version and Parsec seems really straightforward. > > For me, the Applicative version looks more functional and the monadic version > looks more imperative. Indeed; thta's a good way of putting it. Applicative looks more functional since it corresponds to function application, but a special sort of function application that carries along some sort of "context". > It seems that Applicative is enough for Parsers (think I > remember a citation somewhere), but does it have a real advantage? The Monad interface gives strictly more power: it allows you to give names to intermediate results, and *decide what to do* later based on those intermediate results. With Applicative, the actions that you perform must be fixed ahead of time. For example, consider parsing a file which contains a positive integer, followed by that many letters. For example, 3xyz 12abcdefghijkl are two instances of this format. In order to parse this, a monadic interface is required, since the result of parsing the number must be used to decide how many things to parse after that. However, for *many* purposes, an Applicative parsing interface is all you need. And if Applicative is enough, it's usually nicer/more elegant than Monad. (And using the least powerful/most general thing that works for your purpose is usually good style anyway.) -Brent From thestonetable at gmail.com Fri Nov 6 11:52:48 2009 From: thestonetable at gmail.com (Cory Knapp) Date: Fri Nov 6 11:29:08 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: References: Message-ID: <4AF45460.8060809@gmail.com> I'm certainly not an expert on Haskell, and my studies over the last year have prevented me from really working in Haskell (or any language) much, but... Maur??cio CA wrote: > > - how could I program something like this in Haskell: .. > > generate random population > > Since Haskell is a "pure" language, after you attribute a value > to a variable they are glued together forever. So, the language > itself can't have such a thing as a random number. (Here, someone > with technical knowledge will probably correct me, but you get > the poing.) Dealing with this (and other "outside world" stuff) > requires learning how to deal with a special type construct > called "Monad". It's the major step you will have to as a Haskell > begginer. It's, though, extremely interesting, and extremely > powerfull after you understand it. I don't think you need that deep of an understanding of monads in order to write random code. You need a basic understanding of "monads as computations", and you need to know how to use do notation, which should feel very much like programming in an imperative language. On the other hand, the rest of the algorithm Luis mentioned is *very* natural in Haskell once you learn how to deal with lists. > > > - Although I always liked math, I no longer have the knowledge > > I used to have several years ago. Is this important to help > > program in this funcional language? > > No. But if you like math, you're probably going to find links to > really interesting math while you learn. I Definitely agree. Being a math student, one of the things I like about Haskell is how it's a "down to earth" example of some very high level concepts showing up-- without necessarily needing to learn all the math that's there. (I spend more time learning the math than the Haskell, but that's a result of my biases, not need.) Now, your other (related) questions: - Is Haskell suitable to process data like this in a fast way (aproximate to C++?) - In order for Haskell to be fast, coding is done in a 'natural' way or with use of special hidden details of the language? Idiomatic Haskell won't be as fast as idiomatic C++, but it will blow Python away. Since I assume you'll be working with large data sets, lazy evaluation may actually make your life much easier. If you really are pushing for lightening fast code, you can do some Don Stewart style hacking, or you can link to C using the foreign function interface. I have no experience with either, but I've heard nothing but the best about Haskell/C interaction. Cheers, Cory From b.lehnert at gmx.de Fri Nov 6 11:58:23 2009 From: b.lehnert at gmx.de (Bernhard Lehnert) Date: Fri Nov 6 11:34:26 2009 Subject: [Haskell-beginners] Is Haskell for me? In-Reply-To: References: Message-ID: <1257526703.4976.16.camel@sol> Hi! Am Freitag, den 06.11.2009, 13:58 +0000 schrieb Luis P. Mendes: > - Is Haskell able to read (also write to a point) data from databases > in a fast and reliable way? (MySql or PostgreSQL) You might want to check out these links: http://software.complete.org/software/projects/show/hdbc http://software.complete.org/static/hdbc-odbc/doc//HDBC-odbc/Database-HDBC-ODBC.html http://sites.google.com/site/haskell/notes/connecting-to-mysql-with-haskell http://www.volker-wysk.de/mysql-hs/ > - how could I program something like this in Haskell: > .. generate random population > .. for each one of the population: > .. for time period 1 to ten million: > .. evaluate method 1, 2, 3, 4, 5, 6, .... > ..evaluate fitness of each one > .. generate new population based on results of previous generation You will have to change your thinking a lot. Forget about "for each one of the population". Think "Map a function to the list which contains the population". When I started I thought I knew map from Python - and in fact I did underestimate "map" all the time in Python. For time 1 to ten million evaluate a method? No - map "evaluate fitness" to the list [1..10000000] (Don't worry about big numbers - it's all lazily evaluated. "Generate new population based on previous generation"? It's just recursion and where will you find better recursion than in a functional language? > - Are there graphical packages available to plot results or is it easy > to connect it to a Python (or C) library? There are some graphical packages, but if everything else fails: Do fast computing in Haskell and plot the results using Python. > - Is code easily reusable in different future projects? Since it has > no objects... how can it be done? You do not reuse objects, you reuse functions - that's why they call it functional and yes > Sorry for all these questions, but I really need to know about this > and that's why I want to read answers from knowledgeable people. Sorry, I'm a beginner myself and would not actually call myself "knowledgeable". However, the learning curve is steep and lots of things that seem to be very complicated are soon very logic! You'll need some time to get the new ideas. If you got that, it's really worthwhile! Greets, Bernhard From deniz.a.m.dogan at gmail.com Fri Nov 6 11:58:50 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Fri Nov 6 11:35:12 2009 Subject: [Haskell-beginners] Applicative Parsec In-Reply-To: <20091106164905.GA27242@seas.upenn.edu> References: <1257523871-sup-7114@pc44es141.cs.uni-magdeburg.de> <20091106164905.GA27242@seas.upenn.edu> Message-ID: <7b501d5c0911060858g621cd442m7df5d018ad4fa379@mail.gmail.com> 2009/11/6 Brent Yorgey : > On Fri, Nov 06, 2009 at 05:22:04PM +0100, Matthias Guedemann wrote: >> >> I wrote a converter from a textfile format to a csv file. In order to get more >> familiar with Haskell I wrote it using Parsec. >> At first I had some difficulties and the monadic version seemed easier, but now >> it works as Applicative version and Parsec seems really straightforward. >> >> For me, the Applicative version looks more functional and the monadic version >> looks more imperative. > > Indeed; thta's a good way of putting it. ?Applicative looks more > functional since it corresponds to function application, but a special > sort of function application that carries along some sort of > "context". > >> It seems that Applicative is enough for Parsers (think I >> remember a citation somewhere), but does it have a real advantage? > > The Monad interface gives strictly more power: it allows you to give > names to intermediate results, and *decide what to do* later based on > those intermediate results. ?With Applicative, the actions that you > perform must be fixed ahead of time. > > For example, consider parsing a file which contains a positive > integer, followed by that many letters. ?For example, > > ?3xyz > ?12abcdefghijkl > > are two instances of this format. ?In order to parse this, a monadic > interface is required, since the result of parsing the number must be > used to decide how many things to parse after that. > > However, for *many* purposes, an Applicative parsing interface is all > you need. ?And if Applicative is enough, it's usually nicer/more > elegant than Monad. (And using the least powerful/most general thing > that works for your purpose is usually good style anyway.) > > -Brent > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > In Hughes' and Swierstra's paper "Polish Parsers, Step by Step" (2003) it says that Parsec's monadic interface can not be used for online production of results. I don't know why or whether this even is true anymore. -- Deniz Dogan From shawn-haskell at willden.org Fri Nov 6 12:19:50 2009 From: shawn-haskell at willden.org (Shawn Willden) Date: Fri Nov 6 11:55:54 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <4AF45460.8060809@gmail.com> References: <4AF45460.8060809@gmail.com> Message-ID: <200911061019.50935.shawn-haskell@willden.org> On Friday 06 November 2009 09:52:48 am Cory Knapp wrote: > Idiomatic Haskell won't be as fast as idiomatic C++, but it will blow > Python away. Based on the little bit of stuff I've done, I think I'd characterize it this way: C++ will be maybe twice as fast as Haskell. Maybe a little more, maybe a little less, depending on a lot of details. For heavy computation, Python will be a couple orders of magnitude slower than both. IOW, Haskell is slower than C++ but it's in the same ballpark. Would anyone disagree? Shawn. From RafaelGCPP.Linux at gmail.com Fri Nov 6 13:08:32 2009 From: RafaelGCPP.Linux at gmail.com (Rafael Gustavo da Cunha Pereira Pinto) Date: Fri Nov 6 12:44:37 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <200911061019.50935.shawn-haskell@willden.org> References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> Message-ID: <351ff25e0911061008pde33b52g8f3ec85738f79a20@mail.gmail.com> WARNING: THIS IS A VERY LONG REPLY Luis, If you are in a hurry skip to the point where I give advices ;-) ----------------------------------------SKIP IF YOU LIKE TO---------------------------------------------------- I'll ask some more questions!! :-P - Nothing beats Assembly in speed. Why isn't everyone programming in Assembly?? - Python gives me the flexibility for fast prototyping, because it easily connects to C and Java libraries Why isn't every enterprise service bus (ESB) implementation written in Python?? - Ruby has Rails!! One of most successful MVC frameworks ever. Why isn't every system written in Ruby on Rails? Basically, what I am trying to say is that even though Haskell is not blazing fast, it can be made fast enough for you, given you use the right algorithms and optimizations. For this to happen, you must first understand, the functional paradigm, the language and how the compiler optimizes your code. For the rest of your questions: - Is Haskell able to read (also write to a point) data from databases in a fast and reliable way? (MySql or PostgreSQL) Yes, there is a lot of ways. Look at Hackage (HackageDB)for database related packages - how could I program something like this in Haskell: .. generate random population .. for each one of the population: .. for time period 1 to ten million: .. evaluate method 1, 2, 3, 4, 5, 6, .... ..evaluate fitness of each one .. generate new population based on results of previous generation It seems relatively intuitive for me to program this in an imperative language. But what about in Haskell? It looks rather imperative to me, either. You can implement imperative things on the IO and State monads, but I would really suggest you rethink the algorithm. - Is Haskell suitable to process data like this in a fast way (aproximate to C++?) How fast, again, depends on the algorithm. Haskell programs look like a collection of mathematical functions. One could write a program like a composition of functions: main= count . words . readfile and then define functions individually... - In order for Haskell to be fast, coding is done in a 'natural' way or with use of special hidden details of the language? The natural way makes you code right, but you have to think every step you do, since a badly organized recursion, or the excess of lazyness can make your program hog on memory and/or go dead slow. - Although I always liked math, I no longer have the knowledge I used to have several years ago. Is this important to help program in this funcional language? The math needed in your first steps is not hard. After you started learning Haskell you will most certainly step on Monads. These might require some abstract algebra, if you want to understand what's behind the curtains. Refrain yourself from trying to understand them using math and take a look on Philip Wadler's "Monads for functional programming" - Are there graphical packages available to plot results or is it easy to connect it to a Python (or C) library? Hackage is the way to go. - Is code easily reusable in different future projects? Since it has no objects... how can it be done? Like all other languages, it all depends on YOU. Haskell has no objects, but it has polymorphic functions, which are just as powerful. It also has type classes, which are almost like C++ object classes, but completely different. Type classes can restrict or increase polymorphism, depending on how you use them. There are also MANY extensions implemented on GHC that expand the type system to its limit. ---------------------------------------- END OF SKIP BLOCK---------------------------------------------------- Is Haskell for you? I can't answer, but I can give some advice: 1) If you are in a hurry, go for what you know (C++, Java, Python, Assembly...) 2) If you really want to dig in, dig in. Learning Haskell is a wonderful experience and can dramatically change your way of programming. Think of a mind altering experience!!! 3) Even though it is hard to write great programs at first, in the end it is very rewarding. As your programming style improves, you'll see how elegant algorithms are implemented in functional programming. I still consider myself a beginner, but I can assure you Haskell is a great language for functional programming. Best regards, Rafael Gustavo da Cunha Pereira Pinto -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091106/82db49e7/attachment-0001.html From matthias.guedemann at ovgu.de Fri Nov 6 13:20:11 2009 From: matthias.guedemann at ovgu.de (Matthias Guedemann) Date: Fri Nov 6 12:58:56 2009 Subject: [Haskell-beginners] Applicative Parsec In-Reply-To: <20091106164905.GA27242@seas.upenn.edu> References: <1257523871-sup-7114@pc44es141.cs.uni-magdeburg.de> <20091106164905.GA27242@seas.upenn.edu> Message-ID: <1257531159-sup-2695@pc44es141.cs.uni-magdeburg.de> Hi Brent, thanks for the illustrative example. > For example, consider parsing a file which contains a positive > integer, followed by that many letters. For example, > > 3xyz > 12abcdefghijkl > > are two instances of this format. In order to parse this, a monadic > interface is required, since the result of parsing the number must be > used to decide how many things to parse after that. I see, but as long as I want to parse context free grammars, it is sufficient? > However, for *many* purposes, an Applicative parsing interface is all > you need. And if Applicative is enough, it's usually nicer/more > elegant than Monad. (And using the least powerful/most general thing > that works for your purpose is usually good style anyway.) I agree, and EBNF practically translates itself (modulo some try lookaheads) best regards, Matthias -- __________________________________________________________ ___ __ __ Dipl. Inf. Matthias Guedemann / __\/ _\ /__\ Computer Systems in Engineering / / \ \ /_\ Otto-von-Guericke Universitaet Magdeburg / /___ _\ \//__ Tel.: 0391 / 67-19359 \____/ \__/\__/ __________________________________________________________ From nefigah at gmail.com Fri Nov 6 13:25:49 2009 From: nefigah at gmail.com (Jordan Cooper) Date: Fri Nov 6 13:01:50 2009 Subject: [Haskell-beginners] Thank you, everyone Message-ID: <301488c50911061025u34589fb9g36f6858e58caecf@mail.gmail.com> Just thought I'd give props to everyone on this list -- both askers and answerers. It's been quite helpful for me to read everything, even when I'm not dealing with the same issues. Every online community should strive to be as considerate, intelligent, and all-around helpful as this one. Have a happy weekend! From daniel.is.fischer at web.de Fri Nov 6 13:44:39 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Nov 6 13:23:52 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <200911061019.50935.shawn-haskell@willden.org> References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> Message-ID: <200911061944.39392.daniel.is.fischer@web.de> Am Freitag 06 November 2009 18:19:50 schrieb Shawn Willden: > On Friday 06 November 2009 09:52:48 am Cory Knapp wrote: > > Idiomatic Haskell won't be as fast as idiomatic C++, but it will blow > > Python away. > > Based on the little bit of stuff I've done, I think I'd characterize it > this way: C++ will be maybe twice as fast as Haskell. Maybe a little > more, maybe a little less, depending on a lot of details. Difficult waters. Depending on a lot of things, (rather idiomatic) Haskell is between a little faster (that's rare, however) and *much* slower than C (or C++, but I can only strongly advise against using that; pick C, C# or Java if you want to use a fast, halfway sensible imperative language. C++ consistently chose what I find the worst parts of both worlds - YMMV). Two things should be noted: - it's easy, especially if one isn't yet experienced, to write Haskell code that is much slower than C because of the wrong choice of data structures or not making things strict in the right places. - but if that happens, you have a good chance of quickly getting help to get up to speed here or on #haskell. That said, a factor of 2-3 relative to C is usually achievable without low-level tweaking, sometimes better, sometimes worse. > For heavy > computation, Python will be a couple orders of magnitude slower than both. For not very large values of 'couple': don't expect a factor of more than 100 - that's extremely rare. > > IOW, Haskell is slower than C++ but it's in the same ballpark. Yes, as a general rule, that's it. > > Would anyone disagree? Bulat? > > Shawn. From chaddai.fouche at gmail.com Fri Nov 6 14:53:25 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Fri Nov 6 14:29:26 2009 Subject: [Haskell-beginners] if ands In-Reply-To: <7b501d5c0911060103n3f54d8a7m55da916879c18afe@mail.gmail.com> References: <200911052105.22124.nathanmholden@gmail.com> <92e42b740911051812j2042cf78pb6f587b6049051bf@mail.gmail.com> <7b501d5c0911060103n3f54d8a7m55da916879c18afe@mail.gmail.com> Message-ID: On Fri, Nov 6, 2009 at 10:03 AM, Deniz Dogan wrote: >>> If you have an if statement like >>> >>> if (a&&b) then fun else fun' >>> >>> and a is false, does GHC actually bother to check b? >> > > Note that Haskell is far from the only programming language that is > smart about this. I actually can't think of a single programming > language implementation that I know of which isn't this smart... > > For what it's worth, Haskell (and others) is smart about ORs as well. > In (x || y), y will only be evaluated if x is False. Right, almost every programming language act this way, which is why (&&) and (||) are sometimes called short-circuit boolean operators. What's interesting is not that Haskell does it for (&&) and (||), it's that those operators aren't primitives in Haskell but normal functions defined in the Prelude, their behavior is just lazy evaluation at work... That's also why you can write the functions and() and or() as easily as : and :: [Bool] -> Bool and = foldr (&&) True or :: [Bool] -> Bool or = foldr (||) False And get a nice short-circuiting behavior.... -- Jeda? From jli at circularly.org Fri Nov 6 15:22:24 2009 From: jli at circularly.org (John Li) Date: Fri Nov 6 14:58:28 2009 Subject: [Haskell-beginners] type classes, java interfaces in type systems space Message-ID: <20091106202224.GA16282@circularly.org> Hi all, I've been trying to get a feel for the space of programming languages, and in particular, different sorts of type systems. In hopes of clarifying and correcting my thoughts, please bear with me while I ramble for a while, and correct and direct me towards enlightening resources. Abstraction is good, boilerplate is bad, and we'd like to write general code that works for different "sorts" of things. Parametric polymorphism and interfaces are 2 common ways to do this, and fit together well with current strong, static type systems. Parametric polymorphism enables abstraction by allowing functions to operate on a particular "containing" type, but arbitrary "contained" types, exemplified by the many well-known list functions. Abstraction is achieved because the desired functionality only depends on the specific structure (interface?) of the "outer" type. This is essentially exactly what generics in Java are. Interfaces (I use the term in the Java sense, though I'm not fully comfortable with the details) allow one to write code that works with any type, as long as that type provides the functionality specified in an interface. So, type classes in Haskell provide similar functionality to interfaces in Java. It seems like parametric polymorphism is a more restricted case of type classes. Map could perhaps be something like: map :: (Consable xs x, Consable ys y) => (x -> y) -> xs -> ys class Consable xs x where cons :: (x, xs) -> xs decons :: xs -> (x, xs) (I think functional dependencies could be used to link xs and x in the type system?) The Functor class seems similar, but I'm not sure if I see that it's exactly the same. Clojure's "seq" abstraction (implemented for most (all?) of its built-in collection types as well as Java Iterables, etc.) requires "first", "rest", and "cons". Through this interface, Clojure implements map, filter, reverse, etc. once, but they work for all its collections. Thanks for your patience! -John From magnus at therning.org Fri Nov 6 15:43:27 2009 From: magnus at therning.org (Magnus Therning) Date: Fri Nov 6 15:19:31 2009 Subject: [Haskell-beginners] if ands In-Reply-To: <7b501d5c0911060103n3f54d8a7m55da916879c18afe@mail.gmail.com> References: <200911052105.22124.nathanmholden@gmail.com> <92e42b740911051812j2042cf78pb6f587b6049051bf@mail.gmail.com> <7b501d5c0911060103n3f54d8a7m55da916879c18afe@mail.gmail.com> Message-ID: <4AF48A6F.2090500@therning.org> On 06/11/09 09:03, Deniz Dogan wrote: > 2009/11/6 Keith Sheppard : >> Also, an nice way to check how evaluation works in ghci is to do something like: >> >>> if False && error "error here" then "it's true" else "it's false" >> >> This expression will evaluate as "it's false" without any "error here" >> error message appearing >> >> On Thu, Nov 5, 2009 at 9:05 PM, Nathan M. Holden >> wrote: >>> If you have an if statement like >>> >>> if (a&&b) then fun else fun' >>> >>> and a is false, does GHC actually bother to check b? >> > > Note that Haskell is far from the only programming language that is > smart about this. I actually can't think of a single programming > language implementation that I know of which isn't this smart... > > For what it's worth, Haskell (and others) is smart about ORs as well. > In (x || y), y will only be evaluated if x is False. IIRC Pascal isn't "smart" about it. /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/20091106/d04f14f2/signature.bin From gaius at gaius.org.uk Fri Nov 6 15:48:53 2009 From: gaius at gaius.org.uk (Gaius Hammond) Date: Fri Nov 6 15:24:54 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <200911061019.50935.shawn-haskell@willden.org> References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> Message-ID: On 6 Nov 2009, at 17:19, Shawn Willden wrote: > Based on the little bit of stuff I've done, I think I'd characterize > it this > way: C++ will be maybe twice as fast as Haskell. Maybe a little > more, maybe > a little less, depending on a lot of details. For heavy > computation, Python > will be a couple orders of magnitude slower than both. To be fair, Python offloads its heavy lifting to C libraries - NumPy and SciPy run at very close to full C speed on large datasets. This is also how Matlab works. Unladen Swallow is an upcoming JIT compiler for Python. Where Haskell shines for computation is when you can leverage lazy evaluation. Cheers, G From byorgey at seas.upenn.edu Fri Nov 6 16:41:34 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Fri Nov 6 16:17:34 2009 Subject: [Haskell-beginners] Applicative Parsec In-Reply-To: <1257531159-sup-2695@pc44es141.cs.uni-magdeburg.de> References: <1257523871-sup-7114@pc44es141.cs.uni-magdeburg.de> <20091106164905.GA27242@seas.upenn.edu> <1257531159-sup-2695@pc44es141.cs.uni-magdeburg.de> Message-ID: <20091106214134.GA20855@seas.upenn.edu> On Fri, Nov 06, 2009 at 07:20:11PM +0100, Matthias Guedemann wrote: > > Hi Brent, > > thanks for the illustrative example. > > > For example, consider parsing a file which contains a positive > > integer, followed by that many letters. For example, > > > > 3xyz > > 12abcdefghijkl > > > > are two instances of this format. In order to parse this, a monadic > > interface is required, since the result of parsing the number must be > > used to decide how many things to parse after that. > > I see, but as long as I want to parse context free grammars, it is > sufficient? Well, technically, if you want to be able to do any choice at all, you need Alternative in addition to Applicative (this is what provides the <|> choice operator). But intuitively, yes, I expect that you should be able to parse any context-free grammar using only Alternative. -Brent From hyangfji at gmail.com Fri Nov 6 16:47:06 2009 From: hyangfji at gmail.com (Hong Yang) Date: Fri Nov 6 16:23:07 2009 Subject: [Haskell-beginners] Help for type matching Message-ID: I have the following code: $$$$$$$$ module Main where import System.Environment (getArgs) import Text.CSV.ByteString import qualified Data.ByteString.Lazy.Char8 as L main = do [args] <- getArgs file <- L.readFile args let result = parseCSV file case result of Nothing -> putStrLn "Error when parsing!" Just contents -> do putStrLn "parsing OK!" -- map_header_records contents $$$$$$$$ which yielded the error as follows: Couldn't match expected type `Data.ByteString.Internal.ByteString' against inferred type `L.ByteString' In the first argument of `parseCSV', namely `file' In the expression: parseCSV file In the definition of `result': result = parseCSV file readFile in the Data.ByteString.Lazy.Char8 module returns ByteString type. Since the module is qualified as L, L.readFile returns L.ByteString. But parseCSV expects a ByteString. Sometimes this is annoying, because it makes type matching difficult (at least for me, a beginner). I really wish Haskell can intelligently treat L.ByteString, M.ByteString, and whatever X.ByteString the same as ByteString, and match them. Can someone tell me how to solve the above problem? Thanks, Hong -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091106/0cea5c2f/attachment-0001.html From felipe.lessa at gmail.com Fri Nov 6 16:58:30 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Fri Nov 6 16:34:30 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> Message-ID: On 11/6/09, Gaius Hammond wrote: > To be fair, Python offloads its heavy lifting to C libraries - NumPy > and SciPy run at very close to full C speed on large datasets. This is > also how Matlab works. Unladen Swallow is an upcoming JIT compiler for > Python. > > Where Haskell shines for computation is when you can leverage lazy > evaluation. *If* you can offload most of your work to SciPy. Depending on what you do this is at least difficult. I don't know how much of a neural network can be represented as big fat matrix :). -- Felipe. From debatem1 at gmail.com Fri Nov 6 18:37:30 2009 From: debatem1 at gmail.com (geremy condra) Date: Fri Nov 6 18:13:37 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> Message-ID: On Fri, Nov 6, 2009 at 4:58 PM, Felipe Lessa wrote: > On 11/6/09, Gaius Hammond wrote: >> To be fair, Python offloads its heavy lifting to C libraries - NumPy >> and SciPy run at very close to full C speed on large datasets. This is >> also how Matlab works. Unladen Swallow is an upcoming JIT compiler for >> Python. >> >> Where Haskell shines for computation is when you can leverage lazy >> evaluation. > > *If* you can offload most of your work to SciPy. Depending on what you > do this is at least difficult. I don't know how much of a neural > network can be represented as big fat matrix :). > > -- > Felipe. Neural networking can be easily handled in both Python and C. I've used my own Graphine graph theory package for it and found that it was quite easy and reasonably fast, and certainly LEDA is a very high performance, pretty easy-to-use library. There's no need to coerce ANNs into a matrix form if you don't want to. Geremy Condra From hyangfji at gmail.com Fri Nov 6 18:57:47 2009 From: hyangfji at gmail.com (Hong Yang) Date: Fri Nov 6 18:33:48 2009 Subject: [Haskell-beginners] Re: Help for type matching In-Reply-To: References: Message-ID: My mistake. I did not read the Text.CSV.ByteString document carefully. parseCSV requires a strict ByteString, but I was feeding a lazy one. Have a good weekend! Hong On Fri, Nov 6, 2009 at 3:47 PM, Hong Yang wrote: > I have the following code: > > $$$$$$$$ > module Main where > > import System.Environment (getArgs) > import Text.CSV.ByteString > import qualified Data.ByteString.Lazy.Char8 as L > > main = do > [args] <- getArgs > file <- L.readFile args > let result = parseCSV file > case result of > Nothing -> putStrLn "Error when parsing!" > Just contents -> do > putStrLn "parsing OK!" > -- map_header_records contents > $$$$$$$$ > > which yielded the error as follows: > > Couldn't match expected type `Data.ByteString.Internal.ByteString' > against inferred type `L.ByteString' > In the first argument of `parseCSV', namely `file' > In the expression: parseCSV file > In the definition of `result': result = parseCSV file > > readFile in the Data.ByteString.Lazy.Char8 module returns ByteString type. > Since the module is qualified as L, L.readFile returns L.ByteString. But > parseCSV expects a ByteString. Sometimes this is annoying, because it makes > type matching difficult (at least for me, a beginner). I really wish Haskell > can intelligently treat L.ByteString, M.ByteString, and whatever > X.ByteString the same as ByteString, and match them. > > Can someone tell me how to solve the above problem? > > Thanks, > > Hong > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091106/5814097b/attachment.html From apfelmus at quantentunnel.de Sat Nov 7 03:53:07 2009 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Sat Nov 7 03:29:28 2009 Subject: [Haskell-beginners] Re: Applicative Parsec In-Reply-To: <1257531159-sup-2695@pc44es141.cs.uni-magdeburg.de> References: <1257523871-sup-7114@pc44es141.cs.uni-magdeburg.de> <20091106164905.GA27242@seas.upenn.edu> <1257531159-sup-2695@pc44es141.cs.uni-magdeburg.de> Message-ID: Matthias Guedemann wrote: > Hi Brent, > > thanks for the illustrative example. > >> For example, consider parsing a file which contains a positive >> integer, followed by that many letters. For example, >> >> 3xyz >> 12abcdefghijkl >> >> are two instances of this format. In order to parse this, a monadic >> interface is required, since the result of parsing the number must be >> used to decide how many things to parse after that. > > I see, but as long as I want to parse context free grammars, it is > sufficient? Yep. The monadic version can handle context-sensitive grammars. Incidentally, this is why the Utrecht parsing libraries ( uu-parsinglib ) only offers an applicative interface. Regards, apfelmus -- http://apfelmus.nfshost.com From mpm at alumni.caltech.edu Sat Nov 7 12:44:48 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sat Nov 7 12:20:57 2009 Subject: [Haskell-beginners] maybe this could be improved? Message-ID: <1268.75.50.149.126.1257615888.squirrel@mail.alumni.caltech.edu> I've got some code which could be made simpler, I hope. the problem is this: I am implementing a software sampling synthesizer. For a given musical instrument, like piano, there are sound samples in memory. One purchases or creates sample sets. To save time money & resources, most sample sets are not complete---they have samples for only some of the pitches. Perhaps every third pitch has a sample. For the software to produce the sound for a non-included pitch, the software finds the closest included sample and plays it back slightly slower/faster to get the target pitch. That leads to the following code. Any ideas for improvement are welcome. The problem is that there are many cases to check: an empty map? the requested pitch less than all available pitches, greater than all available, or somewhere between? I am specifically writing this to run in O( log n) time. (It would be simpler as O(n).) This particular algorithm probably doesn't need to run in O(log n) time, but I want to do it as an educational experience---I will have other applications that need to use Map in O(log n) time. import Control.Monad.Identity import Control.Monad.Error import Control.Monad import qualified Data.Map as M type Pitch = Int type Sample = String type SampleMap = M.Map Pitch Sample -- Given a SampleMap and a Pitch, find the Pitch in the SampleMap -- which is closest to the supplied Pitch and return that. Also -- handle case of null map by throwing an error. findClosestPitch :: SampleMap -> Pitch -> ErrorT String Identity Pitch findClosestPitch samples inPitch = do when (M.null samples) $ throwError "Was given empty sample table." case M.splitLookup inPitch samples of (_,Just _,_ ) -> return inPitch (m1,_ ,m2) | (M.null m1) && not (M.null m2) -> case1 | not (M.null m1) && (M.null m2) -> case2 | otherwise -> case3 where case1 = return . fst . M.findMin $ m2 case2 = return . fst . M.findMax $ m1 case3 = return $ closest (fst . M.findMax $ m1) (fst . M.findMin $ m2) closest a b = if abs (a - inPitch) < abs (b - inPitch) then a else b From streborg at hotmail.com Sat Nov 7 17:05:34 2009 From: streborg at hotmail.com (Glurk) Date: Sat Nov 7 16:41:55 2009 Subject: [Haskell-beginners] Installing packages in Ubuntu Message-ID: Hi, I'm a beginner to both Cabal and Linux. I'm a bit confused as to whether I need to be using Cabal when installng packages. I'm running Ubuntu 9.10, and from the Synaptic Package Manager, I can select various Haskell packages to install - will this install the package correctly, or is there something I need to do in Cabal as well ? Thanks ! :) From magnus at therning.org Sat Nov 7 17:50:21 2009 From: magnus at therning.org (Magnus Therning) Date: Sat Nov 7 17:26:20 2009 Subject: [Haskell-beginners] Installing packages in Ubuntu In-Reply-To: References: Message-ID: On Sat, Nov 7, 2009 at 10:05 PM, Glurk wrote: > Hi, > > I'm a beginner to both Cabal and Linux. > I'm a bit confused as to whether I need to be using Cabal when installng > packages. > > I'm running Ubuntu 9.10, and from the Synaptic Package Manager, I can select > various Haskell packages to install - will this install the package correctly, > or is there something I need to do in Cabal as well ? > > Thanks ! :) IMNSHO, cabal (the tool) is primarily for systems with broken, or non-existing package managers (read Windows). For other systems, including Ubuntu, people should use the native packaging system as far as possible, only reverting to cabal when that fails (for whatever reason). So, in short, use Synaptic until you come to a situation where you need something that isn't packaged for Ubuntu yet. Even then I'd suggest you first check for a source package in Debian. Only if everything else fails should you reach for cabal. /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe From korpios at korpios.com Sat Nov 7 18:03:56 2009 From: korpios at korpios.com (Tom Tobin) Date: Sat Nov 7 17:39:53 2009 Subject: [Haskell-beginners] Installing packages in Ubuntu In-Reply-To: References: Message-ID: On Sat, Nov 7, 2009 at 4:50 PM, Magnus Therning wrote: > IMNSHO, cabal (the tool) is primarily for systems with broken, or > non-existing package managers (read Windows). ?For other systems, > including Ubuntu, people should use the native packaging system as far > as possible, only reverting to cabal when that fails (for whatever > reason). I strongly disagree with this sentiment. OS package managers tend to lag behind in releases, assuming they have your package at all; this problem is severely compounded when you're dealing with a lesser-used language like Haskell. I always use cabal (which, IMHO, is a much better tool than similar tools for other languages, e.g., Python's easy_install), and believe OS package manager use should be discouraged for Haskell. (I'll grant that cabal needs an "uninstall" command, as well as a working "upgrade all".) From jeedward at yahoo.com Sun Nov 8 08:52:25 2009 From: jeedward at yahoo.com (John Edward) Date: Sun Nov 8 08:28:23 2009 Subject: [Haskell-beginners] MULTICONF-10 Call for papers Message-ID: <803359.38547.qm@web45910.mail.sp1.yahoo.com> MULTICONF-10 Call for papers ? The 2010 multi-conference (MULTICONF-10) (website: http://www.promoteresearch.org) will be held during July 12-14, 2010 in Orlando, Florida, USA. The primary goal of MULTICONF is to promote research and developmental activities in computer science, information technology, control engineering, and related fields. Another goal is to promote the dissemination of research to a multidisciplinary audience and to facilitate communication among researchers, developers, practitioners in different fields. The following conferences are planned to be organized as part of MULTICONF-10. ? International Conference on Artificial Intelligence and Pattern Recognition (AIPR-10) ?International Conference on Automation, Robotics and Control Systems (ARCS-10) International Conference on Bioinformatics, Computational Biology, Genomics and Chemoinformatics (BCBGC-10) International Conference on Computer Networks (CN-10) International Conference on Enterprise Information Systems and Web Technologies (EISWT-10) International Conference on High Performance Computing Systems (HPCS-10) International Conference on Information Security and Privacy (ISP-10) International Conference on Image and Video Processing and Computer Vision (IVPCV-10) International Conference on Software Engineering Theory and Practice (SETP-10) International Conference on Theoretical and Mathematical Foundations of Computer Science (TMFCS-10) ? We invite draft paper submissions. Please see the website http://www.promoteresearch.org for more details. ? Sincerely John Edward Publicity committee -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091108/1e9dcd07/attachment-0001.html From john.moore54 at gmail.com Sun Nov 8 12:53:48 2009 From: john.moore54 at gmail.com (John Moore) Date: Sun Nov 8 12:29:43 2009 Subject: [Haskell-beginners] parse String -> Expression Message-ID: <4f7ad1ad0911080953t17ffd10co237995d6a6ce5043@mail.gmail.com> Hi, I'm trying to find a way to parseRPN (Reverse Polish Numbers) to expressions rather than to just numbers. e.g. I want the answer to be in the form (Multiply (Val 2) (Val 3)) rather than just the answer. Are these anyway near the steps parseRPN :: String->Expression This is a lot more complicated then I thought.!!! First do we have to read in a string is this (IsString) fromString :: String -> a Then this goes on a stack pushStack :: a -> Stack -> Stack (Takes a value and puts in on a stack) Later we pop it off popStack :: Stack -> (a,Stack) -- takes the value of the stack and leaves the stack Do we also have to define taking off the stack such as head(popstack) or fst(popstack) if we do we would probably have one for putting it onto a stack. Do we then turn the value into an Expression.? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091108/4fec4429/attachment.html From felipe.lessa at gmail.com Sun Nov 8 13:49:37 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sun Nov 8 13:25:38 2009 Subject: [Haskell-beginners] parse String -> Expression In-Reply-To: <4f7ad1ad0911080953t17ffd10co237995d6a6ce5043@mail.gmail.com> References: <4f7ad1ad0911080953t17ffd10co237995d6a6ce5043@mail.gmail.com> Message-ID: <20091108184937.GA22844@kira.casa> On Sun, Nov 08, 2009 at 05:53:48PM +0000, John Moore wrote: > Hi, > I'm trying to find a way to parseRPN (Reverse Polish Numbers) to > expressions rather than to just numbers. e.g. I want the answer to be in the > form > > (Multiply (Val 2) (Val 3)) rather than just the answer. You don't need to code all the parser by hand. You can use, for example, Parsec parsers. Spoilers ahead!!! If your data type is data Expr a = Multiply (Expr a) (Expr a) | Val a then you may write something like expression :: Parser a -> Parser (Expr a) expression valParser = spaces >> (mult <|> val) where expr = expression valParser mult = char "*" >> (Multiply <$> expr <*> expr) val = Val <$> valParser using Parsec for a concrete example. HTH, -- Felipe. From felipe.lessa at gmail.com Sun Nov 8 13:53:00 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sun Nov 8 13:28:59 2009 Subject: [Haskell-beginners] parse String -> Expression In-Reply-To: <20091108184937.GA22844@kira.casa> References: <4f7ad1ad0911080953t17ffd10co237995d6a6ce5043@mail.gmail.com> <20091108184937.GA22844@kira.casa> Message-ID: <20091108185300.GB22844@kira.casa> On Sun, Nov 08, 2009 at 04:49:37PM -0200, Felipe Lessa wrote: > You don't need to code all the parser by hand. You can use, for > example, Parsec parsers. IOW, you may use the language's implicit stack instead of building your own. -- Felipe. From daniel.is.fischer at web.de Sun Nov 8 14:00:10 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Nov 8 13:37:32 2009 Subject: [Haskell-beginners] parse String -> Expression In-Reply-To: <4f7ad1ad0911080953t17ffd10co237995d6a6ce5043@mail.gmail.com> References: <4f7ad1ad0911080953t17ffd10co237995d6a6ce5043@mail.gmail.com> Message-ID: <200911082000.11449.daniel.is.fischer@web.de> Am Sonntag 08 November 2009 18:53:48 schrieb John Moore: > Hi, > I'm trying to find a way to parseRPN (Reverse Polish Numbers) to > expressions rather than to just numbers. e.g. I want the answer to be in > the form > > (Multiply (Val 2) (Val 3)) rather than just the answer. > I'd suggest using something like type Stack = [Expression] parseRPN :: Parser Expression parseRPN = rpn [] parseVal :: Parser Expression parseVal = do num <- parseNumber return (Val num) rpn :: Stack -> Parser Expression rpn stack = (do char '+' case stack of (x:y:ts) -> rpn (Add x y:ts) _ -> parsecFail "BinOp requires two values on Stack") <|> (do char '*' case stack of (x:y:ts) -> rpn (Multiply x y:ts) _ -> parsecFail "BinOp requires two values on Stack") <|> ... <|> (do v <- parseVal rpn (v:stack)) <|> (do eof case stack of [x] -> return x _ -> parsecFail "No parse") -- You could also use the userstate of Parsec for the stack > > > Are these anyway near the steps > parseRPN :: String->Expression > > This is a lot more complicated then I thought.!!! > > First do we have to read in a string is this (IsString) > > fromString :: String -> a > > Then this goes on a stack > > pushStack :: a -> Stack -> Stack (Takes a value and puts in on a stack) > > Later we pop it off > > popStack :: Stack -> (a,Stack) -- takes the value of the stack and leaves > the stack > > Do we also have to define taking off the stack such as head(popstack) or > fst(popstack) if we do we would probably have one for putting it onto a > stack. > > Do we then turn the value into an Expression.? From nathanmholden at gmail.com Sun Nov 8 14:14:06 2009 From: nathanmholden at gmail.com (Nathan M. Holden) Date: Sun Nov 8 13:50:04 2009 Subject: [Haskell-beginners] Re: Installing packages in Ubuntu Message-ID: <200911081414.06456.nathanmholden@gmail.com> I can't say that you NEED to be using Cabal. I have it, and I'm also an Ubuntu newbie. You can download the bootstrap installer, you'll need to install (via runghc Setup configure, runghc Setup build, runghc Install) the most recent HTML package, and parsec 2.x to get it to run. Then just add an alias (or, I did) so you don't have to write a super-long command to run Cabal. Running Kubuntu 9.10 On Sunday 08 November 2009 08:28:24 am beginners-request@haskell.org wrote: > Message: 6 > Date: Sat, 7 Nov 2009 22:05:34 +0000 (UTC) > From: Glurk > Subject: [Haskell-beginners] Installing packages in Ubuntu > To: beginners@haskell.org > Message-ID: > Content-Type: text/plain; charset=us-ascii > > Hi, > > I'm a beginner to both Cabal and Linux. > I'm a bit confused as to whether I need to be using Cabal when installng > packages. > > I'm running Ubuntu 9.10, and from the Synaptic Package Manager, I can > select various Haskell packages to install - will this install the package > correctly, or is there something I need to do in Cabal as well ? > > Thanks ! :) From mauricio.antunes at gmail.com Sun Nov 8 15:19:39 2009 From: mauricio.antunes at gmail.com (=?ISO-8859-1?Q?Maur=ED=ADcio_CA?=) Date: Sun Nov 8 14:55:57 2009 Subject: [Haskell-beginners] Re: Installing packages in Ubuntu In-Reply-To: References: Message-ID: > I'm a beginner to both Cabal and Linux. > I'm a bit confused as to whether I need to be using Cabal when installng > packages. There's no real confront between then, as cabal will default to install its packages in your home directory. Follow this rule in Ubuntu: install what's available from Ubuntu repositories (using Synaptic) and, whenever you want, need or feel like doing it, install from cabal. If something goes wrong for any reason, just rm ~/.cabal and you get back to what you have in a fresh install. (If you are a begginer in Haskell: also do use cabal system to package your own programs. This will give you a good understandment on how the package system work, and let you more confortable to experiment with advanced language features.) Best, Maur?cio From denis.firsov at gmail.com Sat Nov 7 17:01:46 2009 From: denis.firsov at gmail.com (Denis Firsov) Date: Sun Nov 8 23:27:17 2009 Subject: [Haskell-beginners] Simple haskell problem ! Help please Message-ID: <5874e6730911071401t280bc718m4e94514f58e2ad40@mail.gmail.com> Hi ! I am beginner in Haskell and have problems with this problem: compress :: Eq a => [a] -> [(a, Int)] If you have string "AAABCCC" it transforms it to : {A, 3} {B,1} {C,3} Could you help me with it ? Thank you in advance ! From jfredett at gmail.com Sun Nov 8 23:56:37 2009 From: jfredett at gmail.com (Joe Fredette) Date: Sun Nov 8 23:32:32 2009 Subject: [Haskell-beginners] Simple haskell problem ! Help please In-Reply-To: <5874e6730911071401t280bc718m4e94514f58e2ad40@mail.gmail.com> References: <5874e6730911071401t280bc718m4e94514f58e2ad40@mail.gmail.com> Message-ID: Here are some hints to consider: 1. There are two ways to think about this -- pattern matching on a list, or higher-order functions 2. The former will require thinking about several cases, a. What is a "compressed" empty list? b. How many elements do we need to look at at once? c. What happens if the first and the next element are the same? d. What if they're different? 3. Higher order functions over the list might be easier, consider the `takeWhile` and `dropWhile` functions, as well as the `group` function, there are several ways to use these functions to solve the problem. HTH /Joe On Nov 7, 2009, at 5:01 PM, Denis Firsov wrote: > Hi ! I am beginner in Haskell and have problems with this problem: > compress :: Eq a => [a] -> [(a, Int)] > If you have string "AAABCCC" it transforms it to : {A, 3} {B,1} {C,3} > > Could you help me with it ? > Thank you in advance ! > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From timothyea at comcast.net Mon Nov 9 03:07:38 2009 From: timothyea at comcast.net (Tim Attwood) Date: Mon Nov 9 02:44:00 2009 Subject: [Haskell-beginners] Re: Simple haskell problem ! Help please In-Reply-To: <5874e6730911071401t280bc718m4e94514f58e2ad40@mail.gmail.com> References: <5874e6730911071401t280bc718m4e94514f58e2ad40@mail.gmail.com> Message-ID: > Hi ! I am beginner in Haskell and have problems with this problem: > compress :: Eq a => [a] -> [(a, Int)] > If you have string "AAABCCC" it transforms it to : {A, 3} {B,1} {C,3} > > Could you help me with it ? > Thank you in advance ! This is straightforward with a list comprehension and the group function. import Data.List compress s = [(head g, length g) | g <- group s] From iaefai at me.com Mon Nov 9 04:01:43 2009 From: iaefai at me.com (=?iso-8859-1?Q?i=E6fai?=) Date: Mon Nov 9 03:37:41 2009 Subject: [Haskell-beginners] Either Monadic Trouble Message-ID: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> With the below code, I am getting an error that I cannot resolve? Chess.hs:52:82: Couldn't match expected type `Map [Char] [Char]' against inferred type `Either ParseError ConfigMap' In the third argument of `findWithDefault', namely `c' In the `documentRoot' field of a record In the first argument of `return', namely `Config {documentRoot = (findWithDefault "web" "Document- Root" c)}' The specific code is: getConf :: FilePath -> IO (Either ParseError Config) getConf filePath = return $ do c <- readConfig filePath -- (Either ParseError ConfigMap) return Config { documentRoot = Map.findWithDefault "web" "Document-Root" c } The type of c should be Either ParseError ConfigMap, which by my understanding of the Either monad would cause the c to be the Right side stripped, or skipped if Left. Full source for the module is below, and full project is hosted at http://patch-tag.com/r/iaefai/chess For some general information, I am replacing ConfigFile dependancy with a Parsec based config parser (I call it SimpleConfig) that suits my needs - it came from http://www.serpentine.com/blog/2007/01/31/parsing-a-simple-config-file-in-haskell/ originally and I modified it. On windows ConfigFile's dependancy on a posix regex library was causing trouble, so this is the effort to get rid of that dependancy. Any thoughts would be useful. There is one associated thought? The original function used to get configuration back to the program is -- Mostly from Chris Done's Blog getConf :: FilePath -> IO (Either (C.CPErrorData, String) Config) getConf filePath = runErrorT $ do let cp = C.emptyCP { optionxform = id } contents <- liftIO $ readFile filePath config <- C.readstring cp contents let get = C.get config "DEFAULT" Config <$> get "Document-Root" I noted it used <$> and in the code that I retrieved originally from Chris Done's blog (no longer able to find it) used <*> for additional items. I would like some easy method of constructing the new Config structure in my new code, especially if it can be done without the record syntax like this thing gets away with. I am not sure how this thing associated "Document-Root" with documentRoot mind you. Thank you again. i?fai. -- import Network.Shed.Httpd import Network.URI import Data.List.Split import Data.Either import Data.Map as Map import Text.ParserCombinators.Parsec import Control.Monad.Error import Control.Applicative import System.Directory import ChessBoard import SimpleConfig data Config = Config { documentRoot :: String } deriving (Read, Show) main :: IO () main = do let docPath = "" let config = Config { documentRoot = "" } putStrLn $ "Using document root: " ++ docPath putStrLn "Starting up httpd on port 6666" server <- initServer 6666 (request config) return () request :: Config -> Request -> IO Response request config req = do putStrLn $ "Recieved " ++ (show $ uriPath $ reqURI req) case url of "ajax" : _ -> return $ Response 404 [] "Not found." _ -> do str <- readFile ((documentRoot config) ++ uri) return $ Response 200 [] str where url = drop 1 $ splitOn "/" uri uri = uriPath $ reqURI req getConf :: FilePath -> IO (Either ParseError Config) getConf filePath = return $ do c <- readConfig filePath -- (Either ParseError ConfigMap) return Config { documentRoot = Map.findWithDefault "web" "Document-Root" c } -- **** ERROR From hjgtuyl at chello.nl Mon Nov 9 05:10:07 2009 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Mon Nov 9 04:46:01 2009 Subject: [Haskell-beginners] Either Monadic Trouble In-Reply-To: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> References: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> Message-ID: Either is not a monad, you can check this by typing :i Either in GHCi; you will not see a line like instance Monad Either in the result. Compare this to :i Maybe getConf could be something like: getConf :: FilePath -> IO (Either ParseError Config) getConf filePath = do c <- readConfig filePath -- (Either ParseError ConfigMap) return $ case c of Right c' -> Right $ Config $ Map.findWithDefault "web" "Document-Root" c' Left _ -> c Met vriendelijke groet, Henk-Jan van Tuyl -- http://Van.Tuyl.eu/ http://members.chello.nl/hjgtuyl/tourdemonad.html -- On Mon, 09 Nov 2009 10:01:43 +0100, i?fai wrote: > With the below code, I am getting an error that I cannot resolve? > > > Chess.hs:52:82: > Couldn't match expected type `Map [Char] [Char]' > against inferred type `Either ParseError ConfigMap' > In the third argument of `findWithDefault', namely `c' > In the `documentRoot' field of a record > In the first argument of `return', namely > `Config {documentRoot = (findWithDefault "web" "Document-Root" > c)}' > > > The specific code is: > > getConf :: FilePath -> IO (Either ParseError Config) > getConf filePath > = return $ do > c <- readConfig filePath -- (Either ParseError ConfigMap) > return Config { documentRoot = Map.findWithDefault "web" > "Document-Root" c } > > > The type of c should be Either ParseError ConfigMap, which by my > understanding of the Either monad would cause the c to be the Right side > stripped, or skipped if Left. > > Full source for the module is below, and full project is hosted at > http://patch-tag.com/r/iaefai/chess > > For some general information, I am replacing ConfigFile dependancy with > a Parsec based config parser (I call it SimpleConfig) that suits my > needs - it came from > > http://www.serpentine.com/blog/2007/01/31/parsing-a-simple-config-file-in-haskell/ > originally and I modified it. On windows ConfigFile's dependancy on a > posix regex library was causing trouble, so this is the effort to get > rid of that dependancy. > > Any thoughts would be useful. > > There is one associated thought? > > The original function used to get configuration back to the program is > -- Mostly from Chris Done's Blog getConf :: FilePath -> IO (Either > (C.CPErrorData, String) Config) > getConf filePath = runErrorT $ do > let cp = C.emptyCP { optionxform = id } > contents <- liftIO $ readFile filePath > config <- C.readstring cp contents > let get = C.get config "DEFAULT" > Config <$> get "Document-Root" > > I noted it used <$> and in the code that I retrieved originally from > Chris Done's blog (no longer able to find it) used <*> for additional > items. I would like some easy method of constructing the new Config > structure in my new code, especially if it can be done without the > record syntax like this thing gets away with. I am not sure how this > thing associated "Document-Root" with documentRoot mind you. > > Thank you again. > i?fai. > > -- From nicolas.pouillard at gmail.com Mon Nov 9 06:40:38 2009 From: nicolas.pouillard at gmail.com (Nicolas Pouillard) Date: Mon Nov 9 06:16:32 2009 Subject: [Haskell-beginners] Either Monadic Trouble In-Reply-To: References: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> Message-ID: <1257766690-sup-7742@peray> Excerpts from Henk-Jan van Tuyl's message of Mon Nov 09 11:10:07 +0100 2009: > > Either is not a monad, you can check this by typing > :i Either > in GHCi; you will not see a line like > instance Monad Either > in the result. Compare this to > :i Maybe In fact the Either Monad instance is defined in the 'transformers' (or 'mtl') packages. However for this reason among others you may want to use the 'attempt'[1] package instead of Either. [1]: http://hackage.haskell.org/package/attempt-0.0.0 -- Nicolas Pouillard http://nicolaspouillard.fr From es at ertes.de Mon Nov 9 15:44:44 2009 From: es at ertes.de (Ertugrul Soeylemez) Date: Mon Nov 9 15:21:00 2009 Subject: [Haskell-beginners] Re: Either Monadic Trouble References: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> <1257766690-sup-7742@peray> Message-ID: <20091109214444.42847dba@tritium.xx> Nicolas Pouillard wrote: > > Either is not a monad, you can check this by typing > > :i Either > > in GHCi; you will not see a line like > > instance Monad Either > > in the result. Compare this to > > :i Maybe > > In fact the Either Monad instance is defined in the 'transformers' (or > 'mtl') packages. Either is still not a monad. Have a look at its kind. Greets, Ertugrul. -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From nicolas.pouillard at gmail.com Mon Nov 9 16:00:02 2009 From: nicolas.pouillard at gmail.com (Nicolas Pouillard) Date: Mon Nov 9 15:35:53 2009 Subject: [Haskell-beginners] Re: Either Monadic Trouble In-Reply-To: <20091109214444.42847dba@tritium.xx> References: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> <1257766690-sup-7742@peray> <20091109214444.42847dba@tritium.xx> Message-ID: <1257800088-sup-1148@peray> Excerpts from Ertugrul Soeylemez's message of Mon Nov 09 21:44:44 +0100 2009: > Nicolas Pouillard wrote: > > > > Either is not a monad, you can check this by typing > > > :i Either > > > in GHCi; you will not see a line like > > > instance Monad Either > > > in the result. Compare this to > > > :i Maybe > > > > In fact the Either Monad instance is defined in the 'transformers' (or > > 'mtl') packages. > > Either is still not a monad. Have a look at its kind. OK, right Either is not but (Either e), where e must be in the Error type class. -- Nicolas Pouillard http://nicolaspouillard.fr From legajid at free.fr Mon Nov 9 16:46:19 2009 From: legajid at free.fr (legajid) Date: Mon Nov 9 16:19:02 2009 Subject: [Haskell-beginners] What is the best practice for code] Message-ID: <4AF88DAB.7000400@free.fr> Hello, i wanted to write a program that searches for all combinations of some numbers, the sum of which is a given value. So, i started writing my program, creating a function for each separate phase : creating list of triples, selecting valuable ones, filtering the result. Looking at my code, i've reduced it several ways; the last version holds on one single line of code. Please, from the 3 versions i established, which one is " better"? What are the criterias of a "good" code ? What about using many anonymous functions? I think there are other solutions than those i propose. Following is my code {- First solution -} nombres=[9,8..1] -- all combinations ftoutes xx = [(x, y, z) | x <- xx, y <- xx, z <- xx] -- keep valuable ones futiles xyz = [(x, y, z) | (x,y,z) <- xyz, y < x, z < y ] -- filter f_flt (x,y, z) = (x+y+z) == 19 -- final result f = filter (f_flt) (futiles (ftoutes nombres )) {- Second solution -} futiles2 xx = [(x, y, z) | x <- xx, y <- xx, z <- xx, y < x, z < y] f2 = filter (\(x,y,z) -> (x+y+z)==19) (futiles2 nombres ) {- Third solution -} f3 = filter (\(x,y,z) -> (x+y+z)==19) ((\ xx -> [(x, y, z) | x <- xx, y <- xx, z <- xx, y < x, z < y]) nombres ) Thanks for your advice Didier. From john.moore54 at gmail.com Mon Nov 9 17:05:43 2009 From: john.moore54 at gmail.com (John Moore) Date: Mon Nov 9 16:41:35 2009 Subject: [Haskell-beginners] turning a value into an expression Message-ID: <4f7ad1ad0911091405i58bfc339g1776768243fa7f79@mail.gmail.com> Hi, How do I turn a value into an expression I want to do for e.g. 8 - 1 turn it into (subtract (Val8) (Val1) Any ideas J -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091109/973318cf/attachment.html From deniz.a.m.dogan at gmail.com Mon Nov 9 17:48:38 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Mon Nov 9 17:24:50 2009 Subject: [Haskell-beginners] turning a value into an expression In-Reply-To: <4f7ad1ad0911091405i58bfc339g1776768243fa7f79@mail.gmail.com> References: <4f7ad1ad0911091405i58bfc339g1776768243fa7f79@mail.gmail.com> Message-ID: <7b501d5c0911091448mff920c2m1048d2596896037d@mail.gmail.com> 2009/11/9 John Moore : > Hi, > ?? How do I turn a value into an expression > I want to do for e.g. 8 - 1 turn it into (subtract (Val8) (Val1) > > Any ideas > > J > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > import Prelude hiding ((-)) data Val a = Val a deriving Show data Expr a b = Subtract a b deriving Show (-) :: Num a => a -> a -> Expr (Val a) (Val a) x - y = Subtract (Val x) (Val y) > 4 - 3 Subtract (Val 4) (Val 3) -- Deniz Dogan From iaefai at me.com Mon Nov 9 18:05:04 2009 From: iaefai at me.com (=?iso-8859-1?Q?i=E6fai?=) Date: Mon Nov 9 17:41:01 2009 Subject: [Haskell-beginners] Re: Either Monadic Trouble In-Reply-To: <1257800088-sup-1148@peray> References: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> <1257766690-sup-7742@peray> <20091109214444.42847dba@tritium.xx> <1257800088-sup-1148@peray> Message-ID: <97C85097-DB8E-4EF2-AAFD-7EDDA76188D9@me.com> This is all very confusing. You say that it is defined in the transformers. Does this mean it is possible to use the code I am trying to get to work to do what I want? You also mention the attempt package, I must admit that I am not entirely sure how to use it either. Note that I haven't done a lot of error handling in haskell (the extent usually involved Maybe) - i?fai. On 2009-11-09, at 4:00 PM, Nicolas Pouillard wrote: > Excerpts from Ertugrul Soeylemez's message of Mon Nov 09 21:44:44 > +0100 2009: >> Nicolas Pouillard wrote: >> >>>> Either is not a monad, you can check this by typing >>>> :i Either >>>> in GHCi; you will not see a line like >>>> instance Monad Either >>>> in the result. Compare this to >>>> :i Maybe >>> >>> In fact the Either Monad instance is defined in the >>> 'transformers' (or >>> 'mtl') packages. >> >> Either is still not a monad. Have a look at its kind. > > OK, right Either is not but (Either e), where e must be in > the Error type class. > > -- > Nicolas Pouillard > http://nicolaspouillard.fr > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From nicolas.pouillard at gmail.com Mon Nov 9 18:12:56 2009 From: nicolas.pouillard at gmail.com (Nicolas Pouillard) Date: Mon Nov 9 17:48:47 2009 Subject: [Haskell-beginners] Re: Either Monadic Trouble In-Reply-To: <97C85097-DB8E-4EF2-AAFD-7EDDA76188D9@me.com> References: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> <1257766690-sup-7742@peray> <20091109214444.42847dba@tritium.xx> <1257800088-sup-1148@peray> <97C85097-DB8E-4EF2-AAFD-7EDDA76188D9@me.com> Message-ID: <1257808266-sup-4646@peray> Excerpts from i?fai's message of Tue Nov 10 00:05:04 +0100 2009: > This is all very confusing. You say that it is defined in the > transformers. Does this mean it is possible to use the code I am > trying to get to work to do what I want? Yes by importing Control.Monad.Error > You also mention the attempt package, I must admit that I am not > entirely sure how to use it either. Note that I haven't done a lot of > error handling in haskell (the extent usually involved Maybe) A new version should be released (on Haskell Cafe) pretty soon, some documentation links will be provided as well. If you find the documentation not clear enough then let me know. -- Nicolas Pouillard http://nicolaspouillard.fr From byorgey at seas.upenn.edu Mon Nov 9 20:18:34 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Nov 9 19:54:24 2009 Subject: [Haskell-beginners] What is the best practice for code] In-Reply-To: <4AF88DAB.7000400@free.fr> References: <4AF88DAB.7000400@free.fr> Message-ID: <20091110011834.GA3427@seas.upenn.edu> On Mon, Nov 09, 2009 at 10:46:19PM +0100, legajid wrote: > > {- Second solution -} > futiles2 xx = [(x, y, z) | x <- xx, y <- xx, z <- xx, y < x, z < y] > f2 = filter (\(x,y,z) -> (x+y+z)==19) (futiles2 nombres ) > > {- Third solution -} > f3 = filter (\(x,y,z) -> (x+y+z)==19) ((\ xx -> [(x, y, z) | x <- xx, y <- > xx, z <- xx, y < x, z < y]) nombres ) I think the second solution is best (the third solution seems hard to read). Shorter code is usually better, but avoid long lines that are hard to scan. Here's another possibility: f4 = filter (\(x,y,z) -> x+y+z == 19) [(x,y,z) | x <- [9,8..1], y <- reverse [1..x-1], z <- reverse [1..y-1]] This way you only generate (x,y,z) where x > y > z, and avoid all the wasted work of generating triples and then throwing them away. -Brent From byorgey at seas.upenn.edu Mon Nov 9 20:21:12 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Nov 9 19:57:02 2009 Subject: [Haskell-beginners] turning a value into an expression In-Reply-To: <4f7ad1ad0911091405i58bfc339g1776768243fa7f79@mail.gmail.com> References: <4f7ad1ad0911091405i58bfc339g1776768243fa7f79@mail.gmail.com> Message-ID: <20091110012112.GB3427@seas.upenn.edu> On Mon, Nov 09, 2009 at 10:05:43PM +0000, John Moore wrote: > Hi, > How do I turn a value into an expression > I want to do for e.g. 8 - 1 turn it into (subtract (Val8) (Val1) > > Any ideas Is this a homework problem? One good approach would be to make a data type Expr which represents expressions. It will have a constructor Val, a constructor Subtract, etc., one constructor for each operation you want to have in your expressions. Then make Expr an instance of the Num type class. -Brent From michael at snoyman.com Tue Nov 10 00:04:12 2009 From: michael at snoyman.com (Michael Snoyman) Date: Mon Nov 9 23:40:04 2009 Subject: [Haskell-beginners] Re: Either Monadic Trouble In-Reply-To: <1257808266-sup-4646@peray> References: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> <1257766690-sup-7742@peray> <20091109214444.42847dba@tritium.xx> <1257800088-sup-1148@peray> <97C85097-DB8E-4EF2-AAFD-7EDDA76188D9@me.com> <1257808266-sup-4646@peray> Message-ID: <29bf512f0911092104s3c58fe77qec186e50b1165559@mail.gmail.com> On Tue, Nov 10, 2009 at 1:12 AM, Nicolas Pouillard < nicolas.pouillard@gmail.com> wrote: > Excerpts from i?fai's message of Tue Nov 10 00:05:04 +0100 2009: > > This is all very confusing. You say that it is defined in the > > transformers. Does this mean it is possible to use the code I am > > trying to get to work to do what I want? > > Yes by importing Control.Monad.Error > > > You also mention the attempt package, I must admit that I am not > > entirely sure how to use it either. Note that I haven't done a lot of > > error handling in haskell (the extent usually involved Maybe) > > A new version should be released (on Haskell Cafe) pretty soon, > some documentation links will be provided as well. If you find > the documentation not clear enough then let me know. > > Update: attempt-0.0.1 *has* been released. Michael -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091109/365c7696/attachment.html From chaddai.fouche at gmail.com Tue Nov 10 04:16:48 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Tue Nov 10 03:52:38 2009 Subject: [Haskell-beginners] What is the best practice for code] In-Reply-To: <4AF88DAB.7000400@free.fr> References: <4AF88DAB.7000400@free.fr> Message-ID: On Mon, Nov 9, 2009 at 10:46 PM, legajid wrote: > {- ? ?Third solution ?-} > f3 = filter (\(x,y,z) -> (x+y+z)==19) ((\ xx -> [(x, y, z) | x <- xx, y <- > xx, z <- xx, y < x, z < y]) nombres ) If you want to use list comprehension just use it for all filtering necessary : (Si tu veux utiliser les list comprehension utilises les donc pour tout filtrage n?cessaire :) > f3 = [(x, y, z) | x <- nombres, y <- nombres, z <- nombres, y < x, z < y, x+y+z == 19] Alternatively, you may try to express the same thing without the list comprehension : (Tu peux aussi essayer d'exprimer la m?me chose avec des fonctions seulement :) > f4 = filter (\[x,y,z] -> z < y && y < x && x+y+z == 19) . replicateM 3 $ nombres It is almost always better (performance-wise) to only generate the correct solutions rather than generate all then filter (though if you can improve the modularity and/or clarity of your code by separating the two steps it's worth considering), so in your case : (Il est presque toujours pr?f?rable (du point de vue des performances) de g?n?rer uniquement les solutions correctes plut?t que de g?n?rer toutes les possibilit?s puis de les filtrer (encore que si ?a te permet d'am?liorer la modularit? ou la clart? de ton code ?a vaut le coup de se poser la question), donc dans ton cas ?a donnerait :) > f5 = reverse [(x, y, z) | x <- [3..9], y <- [2 .. x-1], let z = 19 - x - y, y > z, z > 0] -- Jeda? From haskell-beginners at foo.me.uk Tue Nov 10 04:28:23 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Tue Nov 10 04:04:17 2009 Subject: [Haskell-beginners] Double Trouble Message-ID: <4AF93237.6060300@foo.me.uk> Hi Folks, I'd just like to say thank you very much for your patient answers to my questions so far; it has been a real help on my Haskell adventure. Once I am become a Haskell god like y'all I will endeavour to repay the debt. My current puzzle is doubles. I've extensively scoured the net and found various mentions of the same problem, but as far as I can see no answers; which I can't quite believe as it must be something people do all the time. I need to interface my Haskell program with an existing C++ one over a TCP socket. I need to feed the C++ program doubles in standard 64-bit network order IEEE 765-1985 format, but if I serialize a double using Data.Binary I get something which has altogeather too many bytes (I read somewhere it is an int and a long for the exponent and mantissa). Any advice (or pointers to old threads, it isn't very easy to search the list archives) will be compensated for by a credit note for milk and cookies next time you are in the Cambridge, UK area :) - Philip From gtener at gmail.com Tue Nov 10 04:43:55 2009 From: gtener at gmail.com (=?UTF-8?Q?Krzysztof_Skrz=C4=99tnicki?=) Date: Tue Nov 10 04:19:46 2009 Subject: [Haskell-beginners] Double Trouble In-Reply-To: <4AF93237.6060300@foo.me.uk> References: <4AF93237.6060300@foo.me.uk> Message-ID: <220e47b40911100143q37c3629dy2493fb6fe18f7c82@mail.gmail.com> Perhaps this module will help: http://hackage.haskell.org/package/data-binary-ieee754 Regards Krzysztof Skrz?tnicki On Tue, Nov 10, 2009 at 10:28, Philip Scott wrote: > Hi Folks, > > I'd just like to say thank you very much for your patient answers to my > questions so far; it has been a real help on my Haskell adventure. Once I am > become a Haskell god like y'all I will endeavour to repay the debt. > > My current puzzle is doubles. I've extensively scoured the net and found > various mentions of the same problem, but as far as I can see no answers; > which I can't quite believe as it must be something people do all the time. > > I need to interface my Haskell program with an existing C++ one over a TCP > socket. I need to feed the C++ program doubles in standard 64-bit network > order IEEE 765-1985 format, but if I serialize a double using Data.Binary I > get something which > has altogeather too many bytes (I read somewhere it is an int and a long for > the exponent and mantissa). > > Any advice (or pointers to old threads, it isn't very easy to search the > list archives) will be compensated for by a credit note for milk and cookies > next time you are in the Cambridge, UK area :) > > - Philip > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From haskell-beginners at foo.me.uk Tue Nov 10 05:02:03 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Tue Nov 10 04:37:57 2009 Subject: [Haskell-beginners] Double Trouble In-Reply-To: <220e47b40911100143q37c3629dy2493fb6fe18f7c82@mail.gmail.com> References: <4AF93237.6060300@foo.me.uk> <220e47b40911100143q37c3629dy2493fb6fe18f7c82@mail.gmail.com> Message-ID: <4AF93A1B.6000009@foo.me.uk> Hi ho, > Perhaps this module will help: > > http://hackage.haskell.org/package/data-binary-ieee754 > > >> I need to interface my Haskell program with an existing C++ one over a TCP >> socket. I need to feed the C++ program doubles in standard 64-bit network >> order IEEE 765-1985 format, but if I serialize a double using Data.Binary I >> get something which >> has altogeather too many bytes (I read somewhere it is an int and a long for >> the exponent and mantissa). >> Thank you very much; I will take a look at that! I have no idea how I missed it, I went through every package on hackage that had 'binary' in the name, I must have sailed right past :) - Philip From daniel.is.fischer at web.de Tue Nov 10 10:13:52 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Nov 10 09:51:16 2009 Subject: [Haskell-beginners] Either Monadic Trouble In-Reply-To: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> References: <49F7C1FC-4B1F-4E7E-9585-FCAF5983EF40@me.com> Message-ID: <200911101613.52219.daniel.is.fischer@web.de> Am Montag 09 November 2009 10:01:43 schrieb i?fai: > With the below code, I am getting an error that I cannot resolve? Everybody was so busy discussing whether Either (or rather (Either e)) is a monad that nobody looked at the code, so: > > > Chess.hs:52:82: > Couldn't match expected type `Map [Char] [Char]' > against inferred type `Either ParseError ConfigMap' > In the third argument of `findWithDefault', namely `c' > In the `documentRoot' field of a record > In the first argument of `return', namely > `Config {documentRoot = (findWithDefault "web" "Document- > Root" c)}' > > > The specific code is: > > getConf :: FilePath -> IO (Either ParseError Config) > getConf filePath > = return $ do > c <- readConfig filePath -- (Either ParseError ConfigMap) I believe the type of readConfig is FilePath -> IO (Either ParseError ConfigMap) , thus the binding of c, (c <-), still takes place in IO and c is one of (Left parseerror) or (Right configmap), hence c is not a suitable argument for findWithDefault. > return Config { documentRoot = Map.findWithDefault "web" > "Document-Root" c } The inner return also lives in IO, so had c a suitable type, your getConf would have type FilePath -> IO (IO something). I think you want getConf filePath = do r <- readConfig filePath return $ do c <- r -- *now* we're using the monad (Either ParseError) return Config{ documentRoot = Map.findWithDefault "web" "Document-Root" c } (if you have instance Monad (Either ParseError) in scope) or the equivalent using Pattern matching on the result of readConfig filePath. > > > The type of c should be Either ParseError ConfigMap, which by my > understanding of the Either monad would cause the c to be the Right > side stripped, or skipped if Left. > > Full source for the module is below, and full project is hosted at > http://patch-tag.com/r/iaefai/chess > > For some general information, I am replacing ConfigFile dependancy > with a Parsec based config parser (I call it SimpleConfig) that suits > my needs - it came from > > http://www.serpentine.com/blog/2007/01/31/parsing-a-simple-config-file-in-h >askell/ originally and I modified it. On windows ConfigFile's dependancy on > a posix regex library was causing trouble, so this is the effort to get rid > of that dependancy. > > Any thoughts would be useful. > > There is one associated thought? > > The original function used to get configuration back to the program is > -- Mostly from Chris Done's Blog > getConf :: FilePath -> IO (Either (C.CPErrorData, String) Config) > getConf filePath = runErrorT $ do > let cp = C.emptyCP { optionxform = id } > contents <- liftIO $ readFile filePath > config <- C.readstring cp contents > let get = C.get config "DEFAULT" > Config <$> get "Document-Root" > > I noted it used <$> and in the code that I retrieved originally from > Chris Done's blog (no longer able to find it) used <*> for additional > items. I would like some easy method of constructing the new Config > structure in my new code, especially if it can be done without the > record syntax like this thing gets away with. I am not sure how this > thing associated "Document-Root" with documentRoot mind you. > > Thank you again. > i?fai. From legajid at free.fr Tue Nov 10 16:09:36 2009 From: legajid at free.fr (legajid) Date: Tue Nov 10 15:42:14 2009 Subject: [Haskell-beginners] Complex list manipulation Message-ID: <4AF9D690.6010403@free.fr> Hello, i'm trying to manipulate lists with a "complex" (two-level) structure : a list containing tuples, containing a list containing tuples. The object is to find a specific value according to 2 criterias. Here is my code tabmul= [ ( a, [ ( n, n*a ) | n <- [1..9] ] ) | a <- [2,3,4] ] {- gives the following list [ (2, [(1,2), (2,4), ....(9,18)]), (3, [(1,3), (2,6), ....(9,27)]), (4, [(1,4), (2,8), ....(9,36)]) ] -} {- Get the result for a=3 and n=5 -} -- select level 1 tuple for a=3 s1_flt (x,_) = (x==3) s1=filter (s1_flt) tabmul -- get the list [(3, [(), () .......])] s1_liste =head(s1) -- get the tuple (3, [.....]) -- extract the level 2 list of tuples s1_tup (x,y)=y -- then tuple for n=5 s1_flt2 (x, y) = x==5 s1_soltup = filter (s1_flt2) (s1_tup s1_liste) -- [(3,15)] --finally result for 3 * 5 s1_sol1 (x, y)= y s1_sol = s1_sol1 (head s1_soltup) Perhaps the structure is not the most efficient for this example, but it may simulate records in a database. Getting the result seems really hard. Do you know a shorter way to implement this search? It probably would be simpler when i had triples (a, n ,a*n) ? Another question : the values of criterias are hard-coded. What if i would like to type in s1_sol 3 5; how to put these parameters in the expressions for filters; the filters must get the parameters of the function, in other words the function should return or generate filters ? Thanks for helping Didier. From daniel.is.fischer at web.de Tue Nov 10 16:45:16 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Nov 10 16:22:29 2009 Subject: [Haskell-beginners] Complex list manipulation In-Reply-To: <4AF9D690.6010403@free.fr> References: <4AF9D690.6010403@free.fr> Message-ID: <200911102245.16648.daniel.is.fischer@web.de> Am Dienstag 10 November 2009 22:09:36 schrieb legajid: > Hello, > i'm trying to manipulate lists with a "complex" (two-level) structure : > a list containing tuples, containing a list containing tuples. > The object is to find a specific value according to 2 criterias. > > Here is my code > > tabmul= [ ( a, [ ( n, n*a ) | n <- [1..9] ] ) | a <- [2,3,4] ] > > {- gives the following list > [ > (2, [(1,2), (2,4), ....(9,18)]), > (3, [(1,3), (2,6), ....(9,27)]), > (4, [(1,4), (2,8), ....(9,36)]) > ] > -} > > > {- Get the result for a=3 and n=5 -} > > -- select level 1 tuple for a=3 > s1_flt (x,_) = (x==3) > s1=filter (s1_flt) tabmul -- get the list [(3, [(), () .......])] filter ((== 3) . fst) tabmul > s1_liste =head(s1) -- get the tuple (3, [.....]) You might want to use Data.List.lookup :: (Eq a) => a -> [(a,b)] -> Maybe b lookup 3 tabmul ~> Just [(1,3),...] > > -- extract the level 2 list of tuples > s1_tup (x,y)=y That's Prelude.snd (fst (a,b) = a; snd (a,b) = b) > > -- then tuple for n=5 > s1_flt2 (x, y) = x==5 (== 5) . fst > s1_soltup = filter (s1_flt2) (s1_tup s1_liste) -- [(3,15)] > > --finally result for 3 * 5 > s1_sol1 (x, y)= y > s1_sol = s1_sol1 (head s1_soltup) lookup 3 tabmul >>= lookup 5 or do listetrois <- lookup 3 tabmul lookup 5 listetrois ~> Just 15 > > > Perhaps the structure is not the most efficient for this example, but it > may simulate records in a database. > Getting the result seems really hard. > Do you know a shorter way to implement this search? > It probably would be simpler when i had triples (a, n ,a*n) ? Not necessarily, there are fst :: (a,b) -> a and snd :: (a,b) -> b in the Prelude, but not the analogous functions for triples or larger tuples. head . filter ((== val) . fst) is pretty simple, but if you want to use association lists as maps, lookup is even more handy. > > Another question : the values of criterias are hard-coded. What if i > would like to type in s1_sol 3 5; how to put these parameters in the > expressions for filters; the filters must get the parameters of the > function, in other words the function should return or generate filters ? r?sultat x y = lookup x tabmul >>= lookup y r?sultat x y = do liste <- lookup x tabmul lookup y liste r?sultat x y = head . filter ((== y) . fst) . snd . filter ((== x) . fst) $ tabmul In my book, the first two are clear winners. > > Thanks for helping > Didier. From bonfyre at gmail.com Tue Nov 10 19:50:03 2009 From: bonfyre at gmail.com (Austin Wood) Date: Tue Nov 10 23:31:16 2009 Subject: [Haskell-beginners] What is the best practice for code] In-Reply-To: <4AF88DAB.7000400@free.fr> References: <4AF88DAB.7000400@free.fr> Message-ID: On Tue, Nov 10, 2009 at 8:46 AM, legajid wrote: > i wanted to write a program that searches for all combinations of some > numbers, the sum of which is a given value. > So, i started writing my program, creating a function for each separate > phase : creating list of triples, selecting valuable ones, filtering the > result. > > Looking at my code, i've reduced it several ways; the last version holds on > one single line of code. > > Please, from the 3 versions i established, which one is " better"? What are > the criterias of a "good" code ? > What about using many anonymous functions? > I think there are other solutions than those i propose. It could be done using do; import Control.Monad numbers = [9,8..1] f = do x <- numbers y <- numbers z <- numbers guard (y < x && z < y) guard (x+y+z == 19) return [x,y,z] From darrinth at gmail.com Wed Nov 11 11:06:27 2009 From: darrinth at gmail.com (Darrin Thompson) Date: Wed Nov 11 10:42:14 2009 Subject: [Haskell-beginners] maybe this could be improved? In-Reply-To: <1268.75.50.149.126.1257615888.squirrel@mail.alumni.caltech.edu> References: <1268.75.50.149.126.1257615888.squirrel@mail.alumni.caltech.edu> Message-ID: On Sat, Nov 7, 2009 at 12:44 PM, Michael Mossey wrote: > ? ? ?where case1 = return . fst . M.findMin $ m2 > ? ? ? ? ? ?case2 = return . fst . M.findMax $ m1 > ? ? ? ? ? ?case3 = return $ closest (fst . M.findMax $ m1) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (fst . M.findMin $ m2) > ? ? ? ? ? ?closest a b = if abs (a - inPitch) < abs (b - inPitch) > ? ? ? ? ? ? ? ? ? ? ? ? ? then a > ? ? ? ? ? ? ? ? ? ? ? ? ? else b > I'd try writing quickcheck properties for these cases. That is a really complicated function. It strikes me that a lot of those cases need less available in their scopes than they have. You could force that by breaking the cases and closest into individual functions. Then you could write properties for them. Then you are left with only one complex function determining which case you need. Possibly you could return the case directly? Anyway, that's not as helpful as telling you that you just reinvented a 4 and a half gainer comonad or whatever but if you start cutting this thing up you might notice a structure you already know. -- Darrin From patrick.leboutillier at gmail.com Wed Nov 11 20:52:01 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Wed Nov 11 20:27:47 2009 Subject: [Haskell-beginners] maybe this could be improved? In-Reply-To: <1268.75.50.149.126.1257615888.squirrel@mail.alumni.caltech.edu> References: <1268.75.50.149.126.1257615888.squirrel@mail.alumni.caltech.edu> Message-ID: Michael, Your code is interesting and I'd like to run it, but I'm not to familiar with Maps and Monad transformers. Could you provide a function to create a SampleMap and a way to test it from ghci? Thanks, Patrick On Sat, Nov 7, 2009 at 12:44 PM, Michael Mossey wrote: > I've got some code which could be made simpler, I hope. the problem is > this: I am > implementing a software sampling synthesizer. For a given musical > instrument, like piano, there are sound samples in memory. One purchases > or creates sample sets. To > save time money & resources, most sample sets are not complete---they have > samples for only some of the pitches. Perhaps every third pitch has a > sample. For the software to produce the sound for a non-included pitch, > the software finds the closest included sample and plays it back slightly > slower/faster to get the target pitch. > > That leads to the following code. Any ideas for improvement are welcome. > The problem is that there are many cases to check: an empty map? the > requested pitch less than all available pitches, greater than all > available, or somewhere between? I am specifically writing this to run in > O( log n) time. (It would be simpler as O(n).) This particular algorithm > probably doesn't need to run in O(log n) time, but I want to do it as an > educational experience---I will have other applications that need to use > Map in O(log n) time. > > import Control.Monad.Identity > import Control.Monad.Error > import Control.Monad > import qualified Data.Map as M > > type Pitch = Int > type Sample = String > type SampleMap = M.Map Pitch Sample > > > -- Given a SampleMap and a Pitch, find the Pitch in the SampleMap > -- which is closest to the supplied Pitch and return that. Also > -- handle case of null map by throwing an error. > findClosestPitch :: SampleMap -> Pitch -> ErrorT String Identity Pitch > findClosestPitch samples inPitch = do > ?when (M.null samples) $ throwError "Was given empty sample table." > ?case M.splitLookup inPitch samples of > ? ?(_,Just _,_ ) -> return inPitch > ? ?(m1,_ ? ? ? ?,m2) | (M.null m1) && not (M.null m2) -> case1 > ? ? ? ? ? ? ? ? ? ? ?| not (M.null m1) && (M.null m2) -> case2 > ? ? ? ? ? ? ? ? ? ? ?| otherwise ? ? ? ? ? ? ? ? ? ? ?-> case3 > ? ? ?where case1 = return . fst . M.findMin $ m2 > ? ? ? ? ? ?case2 = return . fst . M.findMax $ m1 > ? ? ? ? ? ?case3 = return $ closest (fst . M.findMax $ m1) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (fst . M.findMin $ m2) > ? ? ? ? ? ?closest a b = if abs (a - inPitch) < abs (b - inPitch) > ? ? ? ? ? ? ? ? ? ? ? ? ? then a > ? ? ? ? ? ? ? ? ? ? ? ? ? else b > > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From mpm at alumni.caltech.edu Wed Nov 11 21:15:36 2009 From: mpm at alumni.caltech.edu (Michael P Mossey) Date: Wed Nov 11 20:51:28 2009 Subject: [Haskell-beginners] maybe this could be improved? In-Reply-To: References: <1268.75.50.149.126.1257615888.squirrel@mail.alumni.caltech.edu> Message-ID: <4AFB6FC8.10704@alumni.caltech.edu> Patrick LeBoutillier wrote: > Michael, > > Your code is interesting and I'd like to run it, but I'm not to > familiar with Maps and Monad transformers. > Could you provide a function to create a SampleMap and a way to test > it from ghci? > Sure, import Control.Monad.Identity import Control.Monad.Error import Control.Monad import qualified Data.Map as M type Pitch = Int type Sample = String type SampleMap = M.Map Pitch Sample -- Given a SampleMap and a Pitch, find the Pitch in the SampleMap -- which is closest to the supplied Pitch and return that. Also -- handle case of null map by throwing an error. findClosestPitch :: SampleMap -> Pitch -> ErrorT String Identity Pitch findClosestPitch samples inPitch = do when (M.null samples) $ throwError "Was given empty sample table." case M.splitLookup inPitch samples of (_,Just _,_ ) -> return inPitch (m1,_ ,m2) | (M.null m1) && not (M.null m2) -> case1 | not (M.null m1) && (M.null m2) -> case2 | otherwise -> case3 where case1 = return . fst . M.findMin $ m2 case2 = return . fst . M.findMax $ m1 case3 = return $ closest (fst . M.findMax $ m1) (fst . M.findMin $ m2) closest a b = if abs (a - inPitch) < abs (b - inPitch) then a else b testMap1 = M.fromList [ (1,"sample1") , (5,"sample2") , (9,"sample3") ] -- testMap2 ==> Right 1 testMap2 = runIdentity $ runErrorT $ findClosestPitch testMap1 2 -- testMap3 ==> Right 5 testMap3 = runIdentity $ runErrorT $ findClosestPitch testMap1 5 -- testMap4 ==> Left "Was given empty sample table." testMap4 = runIdentity $ runErrorT $ findClosestPitch M.empty 5 From dag.hovland at uib.no Thu Nov 12 03:37:28 2009 From: dag.hovland at uib.no (Dag Hovland) Date: Thu Nov 12 03:13:17 2009 Subject: [Haskell-beginners] Why is type "Integer -> Integer" and not "(Num a) => a -> a"? Message-ID: <4AFBC948.5010408@uib.no> Hi! I have a problem with understanding some types given by ghc and hugs. The file loaded is: f1 = \x -> x * 2 f2 x = x * 2 After they are loaded I get the following from ghci *Main> :t f1 f1 :: Integer -> Integer *Main> :t f2 f2 :: (Num a) => a -> a *Main> :t \x -> x * 2 \x -> x * 2 :: (Num a) => a -> a I do not understand why f1 is given Integer -> Integer as a type and not the polymorphic (Num a) => a -> a. I believed that f1, f2 and the lambda expression should all have the same type. Similar output to that above is given by Hugs. Thanks, Dag Hovland -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3880 bytes Desc: S/MIME Cryptographic Signature Url : http://www.haskell.org/pipermail/beginners/attachments/20091112/a88251b0/smime.bin From jfredett at gmail.com Thu Nov 12 03:45:08 2009 From: jfredett at gmail.com (Joe Fredette) Date: Thu Nov 12 03:20:55 2009 Subject: [Haskell-beginners] Why is type "Integer -> Integer" and not "(Num a) => a -> a"? In-Reply-To: <4AFBC948.5010408@uib.no> References: <4AFBC948.5010408@uib.no> Message-ID: <16E9B7CE-F131-4412-B24A-CE107C00EC15@gmail.com> Hi! That's very weird, I don't have a good answer (and fortunately there are far smarter people on this list who will have a better answer...) but my instincts say it has to do with defaulting. When GHC sees a literal digit, it tries to guess what it's type should be, first via inference, but if that returns a polymorphic type (like `Num a => a` or something) it will "default" to a particular type, for literal whole positive/negative numbers, it defaults to `Integer`. My guess is that, defining in GHCi > let f x = x * 2 > let g = \x -> x * 2 the former doesn't default to anything (it just does inference) since it's a function definition, and the latter defaults the '2' to an Integer because it's a value -- or some suitable analog of that situation. What will really blow your mind, try having GHCi inspect the type of > :t \x -> x * 2 (the defn. of `g` w/o the let...) Short answer, I have no idea, but I think it has to do with defaulting. /Joe On Nov 12, 2009, at 3:37 AM, Dag Hovland wrote: > Hi! > > I have a problem with understanding some types given by ghc and hugs. > The file loaded is: > > f1 = \x -> x * 2 > f2 x = x * 2 > > After they are loaded I get the following from ghci > > *Main> :t f1 > f1 :: Integer -> Integer > *Main> :t f2 > f2 :: (Num a) => a -> a > *Main> :t \x -> x * 2 > \x -> x * 2 :: (Num a) => a -> a > > > I do not understand why f1 is given Integer -> Integer as a type and > not > the polymorphic (Num a) => a -> a. I believed that f1, f2 and the > lambda > expression should all have the same type. Similar output to that above > is given by Hugs. > > Thanks, > > Dag Hovland > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From chaddai.fouche at gmail.com Thu Nov 12 04:04:53 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Thu Nov 12 03:40:37 2009 Subject: [Haskell-beginners] Why is type "Integer -> Integer" and not "(Num a) => a -> a"? In-Reply-To: <4AFBC948.5010408@uib.no> References: <4AFBC948.5010408@uib.no> Message-ID: On Thu, Nov 12, 2009 at 9:37 AM, Dag Hovland wrote: > Hi! > > I have a problem with understanding some types given by ghc and hugs. > The file loaded is: > > f1 = \x -> x * 2 > f2 x = x * 2 > > After they are loaded I get the following from ghci > > *Main> :t f1 > f1 :: Integer -> Integer > *Main> :t f2 > f2 :: (Num a) => a -> a > *Main> :t \x -> x * 2 > \x -> x * 2 :: (Num a) => a -> a This is called the monomorphism restriction, it's a rule that state a binding _without_parameters_ shall be inferred of a monomorphic type unless an explicit signature is given. There are several reasons for it, some of efficiency (polymorphism has a cost) and some of a more technical nature, refer to the Haskell Report for a more detailed explanation. Some Haskellers think this restriction is no longer required, that GHC is now often intelligent enough to alleviate the cost of polymorphism, that the technical reasons are not really all that pertinent and that the default should be to infer the more general type in all case rather than confuse beginners and oblige experts to put explicit signatures. It is already possible to deactivate the restriction by using the -XNoMonomorphismRestriction argument (or putting the equivalent language pragma in the code itself or in the cabal description file) and making this the default is discussed for Haskell' (the future standard for Haskell). In the meantime, it is a good idea to put ":set -XNoMonomorphismRestriction" in your .ghci file since most usage of GHCi would only hit the disadvantages of this rule and reap no benefits from it. -- Jeda? From shawn-haskell at willden.org Thu Nov 12 04:06:00 2009 From: shawn-haskell at willden.org (Shawn Willden) Date: Thu Nov 12 03:41:45 2009 Subject: [Haskell-beginners] Why is type "Integer -> Integer" and not "(Num a) => a -> a"? In-Reply-To: <16E9B7CE-F131-4412-B24A-CE107C00EC15@gmail.com> References: <4AFBC948.5010408@uib.no> <16E9B7CE-F131-4412-B24A-CE107C00EC15@gmail.com> Message-ID: <200911120206.00364.shawn-haskell@willden.org> On Thursday 12 November 2009 01:45:08 am Joe Fredette wrote: > My guess is that, defining in GHCi > > > let f x = x * 2 > > let g = \x -> x * 2 > > the former doesn't default to anything (it just does inference) since > it's a function definition, and the latter defaults the '2' to an > Integer because it's a value -- or some suitable analog of that > situation. Hmm. Would that also explain this? Prelude> let f1 x = x * 2 Prelude> :type f1 f1 :: (Num a) => a -> a Prelude> let f2 = \x -> f1 x Prelude> :type f2 f2 :: Integer -> Integer Shawn. From felipe.lessa at gmail.com Thu Nov 12 05:40:49 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Thu Nov 12 05:16:33 2009 Subject: [Haskell-beginners] Why is type "Integer -> Integer" and not "(Num a) => a -> a"? In-Reply-To: <200911120206.00364.shawn-haskell@willden.org> References: <4AFBC948.5010408@uib.no> <16E9B7CE-F131-4412-B24A-CE107C00EC15@gmail.com> <200911120206.00364.shawn-haskell@willden.org> Message-ID: On Thu, Nov 12, 2009 at 7:06 AM, Shawn Willden wrote: > Hmm. ?Would that also explain this? > > Prelude> let f1 x = x * 2 > Prelude> :type f1 > f1 :: (Num a) => a -> a > Prelude> let f2 = \x -> f1 x > Prelude> :type f2 > f2 :: Integer -> Integer Yes, that's the same monomorphism restriction. Also, note that you are defaulting to Integer here: Prelude> :s -Wall Prelude> let f1 x = x * 2 Prelude> :t f1 f1 :: (Num a) => a -> a Prelude> let f2 = \x -> f1 x :1:15: Warning: Defaulting the following constraint(s) to type `Integer' `Num a' arising from a use of `f1' at :1:15-18 In the expression: f1 x In the expression: \ x -> f1 x In the definition of `f2': f2 = \ x -> f1 x Prelude> let f3 :: Int -> Int; f3 = \x -> f1 x Prelude> let f4 :: Num a => a -> a; f4 = \x -> f1 x I find -Wall very useful. Relatively few times it gets annoying. HTH, -- Felipe. From nathanmholden at gmail.com Thu Nov 12 11:40:35 2009 From: nathanmholden at gmail.com (Nathan M. Holden) Date: Thu Nov 12 11:16:20 2009 Subject: [Haskell-beginners] Why is type "Integer -> Integer" and not "(Num a) => a -> a"? Message-ID: <200911121140.35748.nathanmholden@gmail.com> This is just a theory, but in my (limited) experience, GHCi is willing to guess at the type of values, where at functions (explicitly or implicitly typed) it can't guess. In your original function, it multiplied a number (Num a) => a by an Int, therefor it must be Int -> Int (because you can't multiply a Double by an Int, don't be crazy. In the new function, though, it can infer the type of the 2, and therefor it can infer it to whatever numerical type you send it. I've run into this problem a few times, but for whatever reason I can't get myself to fall into any of the usual ways I walk blindly into these sorts of problems this time. From chaddai.fouche at gmail.com Thu Nov 12 12:44:59 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Thu Nov 12 12:20:45 2009 Subject: [Haskell-beginners] Why is type "Integer -> Integer" and not "(Num a) => a -> a"? In-Reply-To: <200911121140.35748.nathanmholden@gmail.com> References: <200911121140.35748.nathanmholden@gmail.com> Message-ID: On Thu, Nov 12, 2009 at 5:40 PM, Nathan M. Holden wrote: > This is just a theory, but in my (limited) experience, GHCi is willing to > guess at the type of values, where at functions (explicitly or implicitly > typed) it can't guess. > > In your original function, it multiplied a number (Num a) => a by an Int, > therefor it must be Int -> Int (because you can't multiply a Double by an Int, > don't be crazy. That is not the problem : as the rest of your message acknowledge 2 is not an Int, it is of type (Num a) => a. The issue rest squarely with the fact that the binding f1 don't have parameter expressed on the left side of the "=", thus the monomorphism restriction kicks in (as alluded, probably, by your first paragraph) and GHC has to use the defaulting rules to find a monomorphic type for f1. -- Jeda? From patrick.leboutillier at gmail.com Thu Nov 12 14:05:58 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Thu Nov 12 13:49:47 2009 Subject: [Haskell-beginners] maybe this could be improved? In-Reply-To: <4AFB6FC8.10704@alumni.caltech.edu> References: <1268.75.50.149.126.1257615888.squirrel@mail.alumni.caltech.edu> <4AFB6FC8.10704@alumni.caltech.edu> Message-ID: Michael, Here's my stab at it, not sure if it's really better though: findClosestPitch :: SampleMap -> Pitch -> ErrorT String Identity Pitch findClosestPitch samples inPitch = do when (M.null samples) $ throwError "Was given empty sample table." case M.splitLookup inPitch samples of (_, Just _, _) -> return inPitch (ml, _, mh) -> return $ approxPitch ml mh where approxPitch ml mh | M.null ml = fst . M.findMin $ mh approxPitch ml mh | M.null mh = fst . M.findMax $ ml approxPitch ml mh = closest (fst . M.findMax $ ml) (fst . M.findMin $ mh) where closest a b = min (inPitch - a) (b - inPitch) I tried to separate the approximation part from the rest of the code, and used a bit of deduction to eliminate (hopefully correctly...) some of the testing conditions. Anyways, I had fun doing working on this, and I learned a bit about computerized music as well! Thanks, Patrick On Wed, Nov 11, 2009 at 9:15 PM, Michael P Mossey wrote: > Patrick LeBoutillier wrote: >> >> Michael, >> >> Your code is interesting and I'd like to run it, but I'm not to >> familiar with Maps and Monad transformers. >> Could you provide a function to create a SampleMap and a way to test >> it from ghci? >> > > Sure, > > > import Control.Monad.Identity > import Control.Monad.Error > import Control.Monad > import qualified Data.Map as M > > type Pitch = Int > type Sample = String > type SampleMap = M.Map Pitch Sample > > > -- Given a SampleMap and a Pitch, find the Pitch in the SampleMap > -- which is closest to the supplied Pitch and return that. Also > -- handle case of null map by throwing an error. > findClosestPitch :: SampleMap -> Pitch -> ErrorT String Identity Pitch > findClosestPitch samples inPitch = do > ?when (M.null samples) $ throwError "Was given empty sample table." > ?case M.splitLookup inPitch samples of > ? (_,Just _,_ ) -> return inPitch > ? (m1,_ ? ? ? ?,m2) | (M.null m1) && not (M.null m2) -> case1 > ? ? ? ? ? ? ? ? ? ? | not (M.null m1) && (M.null m2) -> case2 > ? ? ? ? ? ? ? ? ? ? | otherwise ? ? ? ? ? ? ? ? ? ? ?-> case3 > ? ? where case1 = return . fst . M.findMin $ m2 > ? ? ? ? ? case2 = return . fst . M.findMax $ m1 > ? ? ? ? ? case3 = return $ closest (fst . M.findMax $ m1) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?(fst . M.findMin $ m2) > ? ? ? ? ? closest a b = if abs (a - inPitch) < abs (b - inPitch) > ? ? ? ? ? ? ? ? ? ? ? ? ?then a > ? ? ? ? ? ? ? ? ? ? ? ? ?else b > > > testMap1 = M.fromList [ (1,"sample1") > ? ? ? ? ? ? ? ? ? ? ?, (5,"sample2") > ? ? ? ? ? ? ? ? ? ? ?, (9,"sample3") ] > > -- testMap2 ==> Right 1 > testMap2 = runIdentity $ runErrorT $ findClosestPitch testMap1 2 > > > -- testMap3 ==> Right 5 > testMap3 = runIdentity $ runErrorT $ findClosestPitch testMap1 5 > > -- testMap4 ==> Left "Was given empty sample table." > testMap4 = runIdentity $ runErrorT $ findClosestPitch M.empty 5 > > > > > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From mpm at alumni.caltech.edu Thu Nov 12 17:31:29 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Thu Nov 12 17:07:27 2009 Subject: [Haskell-beginners] maybe this could be improved? In-Reply-To: References: <1268.75.50.149.126.1257615888.squirrel@mail.alumni.caltech.edu> <4AFB6FC8.10704@alumni.caltech.edu> Message-ID: <4AFC8CC1.1040203@alumni.caltech.edu> Hi, Thanks for your help and it looks like you identified some conditions that could be removed. There is one change necessary, I think. closest a b = if (inPitch - a) < (b - inPitch) then a else b Patrick LeBoutillier wrote: > Michael, > > Here's my stab at it, not sure if it's really better though: > > > findClosestPitch :: SampleMap -> Pitch -> ErrorT String Identity Pitch > findClosestPitch samples inPitch = do > when (M.null samples) $ throwError "Was given empty sample table." > case M.splitLookup inPitch samples of > (_, Just _, _) -> return inPitch > (ml, _, mh) -> return $ approxPitch ml mh > where > approxPitch ml mh | M.null ml = fst . M.findMin $ mh > approxPitch ml mh | M.null mh = fst . M.findMax $ ml > approxPitch ml mh = closest (fst . M.findMax $ ml) > (fst . M.findMin $ mh) > where closest a b = min (inPitch - a) (b - inPitch) > > > I tried to separate the approximation part from the rest of the code, > and used a bit of deduction to eliminate (hopefully correctly...) some > of the testing conditions. > Anyways, I had fun doing working on this, and I learned a bit about > computerized music as well! > > > Thanks, > > Patrick > > > From patrick.leboutillier at gmail.com Thu Nov 12 19:06:23 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Thu Nov 12 18:42:06 2009 Subject: [Haskell-beginners] maybe this could be improved? In-Reply-To: <4AFC8CC1.1040203@alumni.caltech.edu> References: <1268.75.50.149.126.1257615888.squirrel@mail.alumni.caltech.edu> <4AFB6FC8.10704@alumni.caltech.edu> <4AFC8CC1.1040203@alumni.caltech.edu> Message-ID: On Thu, Nov 12, 2009 at 5:31 PM, Michael Mossey wrote: > Hi, Thanks for your help and it looks like you identified some conditions > that could be removed. There is one change necessary, I think. > > closest a b = if (inPitch - a) < (b - inPitch) then a else b Yes, of course. I just happens that in the test code (testMap2) it gives the same answer... Patrick > > Patrick LeBoutillier wrote: >> >> Michael, >> >> Here's my stab at it, not sure if it's really better though: >> >> >> findClosestPitch :: SampleMap -> Pitch -> ErrorT String Identity Pitch >> findClosestPitch samples inPitch = do >> ?when (M.null samples) $ throwError "Was given empty sample table." >> ?case M.splitLookup inPitch samples of >> ? ?(_, Just _, _) -> return inPitch >> ? ?(ml, _, mh) ? ?-> return $ approxPitch ml mh >> ? ?where >> ? ? ?approxPitch ml mh | M.null ml = fst . M.findMin $ mh >> ? ? ?approxPitch ml mh | M.null mh = fst . M.findMax $ ml >> ? ? ?approxPitch ml mh ? ? ? ? ? ? = closest (fst . M.findMax $ ml) >> (fst . M.findMin $ mh) >> ? ? ? ?where closest a b = min (inPitch - a) (b - inPitch) >> >> >> I tried to separate the approximation part from the rest of the code, >> and used a bit of deduction to eliminate (hopefully correctly...) some >> of the testing conditions. >> Anyways, I had fun doing working on this, and I learned a bit about >> computerized music as well! >> >> >> Thanks, >> >> Patrick >> >> >> > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From nathanmholden at gmail.com Thu Nov 12 21:55:40 2009 From: nathanmholden at gmail.com (Nathan M. Holden) Date: Thu Nov 12 21:31:27 2009 Subject: [Haskell-beginners] index too large Message-ID: <200911122155.40162.nathanmholden@gmail.com> I've been working on a quick program that acts (vaguely) like a console, lets me type notes and outputs them in a .tex file. I figure it's not that complicated, but it uses a vaguely n-ary structure, so that I can have headers and sub-notes, which loos like: data Note = N { nTitle :: {Char}, nBody :: {Char}, nFormat :: Format, subs :: [Note] | E [Char] Format's just a collection of preset formats, so I don't have to dynamically handle that (since I didn't need to for my uses). Anyways, for whatever reason, sometimes while adding notes, it sends me an error: Prelude.(!!): index too large My only 2 uses of that are in getFullName :: [Note] -> [Int] -> [Char] getFullName d [] = "/" getFullName d (x:xs) = "/" ++ getPartName (d!!x) ++ getFullName (subs (d!!x)) xs and moveIn :: [Note] -> [Int] -> [Char] -> Int -> [Int] moveIn [] i m c = reverse i moveIn ((N dt db df du):ds) [] m c = if matchNote (N dt db df du) m then c:[] else moveIn ds [] m (c+1) moveIn n i m c = last i : ((moveIn (subs (n!!(last i)))) (allButLast i) m 0) where the [Int] is the variable I use to track where in the tree I am. Since I'm not moving into a Note that doesn't exist, and the display shouldn't be changing, what could be the problem? This is probably too in-depth a question, now that I think about it... From daniel.is.fischer at web.de Fri Nov 13 01:00:43 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Nov 13 00:38:43 2009 Subject: [Haskell-beginners] index too large In-Reply-To: <200911122155.40162.nathanmholden@gmail.com> References: <200911122155.40162.nathanmholden@gmail.com> Message-ID: <200911130700.43557.daniel.is.fischer@web.de> Am Freitag 13 November 2009 03:55:40 schrieb Nathan M. Holden: > I've been working on a quick program that acts (vaguely) like a console, > lets me type notes and outputs them in a .tex file. I figure it's not that > complicated, but it uses a vaguely n-ary structure, so that I can have > headers and sub-notes, which loos like: > > data Note = N { > nTitle :: {Char}, > nBody :: {Char}, > nFormat :: Format, > subs :: [Note] > > | E [Char] > > Format's just a collection of preset formats, so I don't have to > dynamically handle that (since I didn't need to for my uses). > > Anyways, for whatever reason, sometimes while adding notes, it sends me an > error: Prelude.(!!): index too large Obviously, sometimes you call list!!index with index > (length list - 1). Are you aware that the indices are 0-based? If it's not that, one would have to analyse the code, but it would be better to see more of it for that. From malthe_j at hotmail.com Sun Nov 15 11:42:39 2009 From: malthe_j at hotmail.com (=?iso-8859-1?Q?Malthe_J=F8rgensen?=) Date: Sun Nov 15 11:18:17 2009 Subject: [Haskell-beginners] Dynamic libraries not of required architecture when installing via cabal (Snow Leopard) Message-ID: I'm on Snow Leopard, so I've read numerous posts on the subject of GHC and it's Snow Leopard (non-)compatibility. I've got most things working - I can do a 'cabal update' - something that gave errors before. GHC itself seems to be working fine. I want to install the SDL package from Hackage, which I first tried doing like this: 'cabal install sdl' which gives a bunch of warnings, all looking like this 'ld: warning: in /opt/local/lib/libSDL.dylib, file is not of required architecture' with 'libSDL.dylib' replaced with various *.a and *.dylib files I then found this in a Usenet post about Snow Leopard breaking GHC: -- Once cabal works, options --ld-option=-m32 (and also --gcc-option=- m32) may be used. These options may also be passed to "./Setup configure" And tried this: (I think maybe my problem is that I'm not passing these flags correctly to cabal) 'cabal install sdl --ld-options="-arch i386" --gcc-option=-m32 -- reinstall' Well I get the same errors, well warnings actually. Can I just ignore these warnings? When compiling my small sample code: import Prelude import Graphics.UI.SDL as SDL main = do SDL.init [InitEverything] setVideoMode 640 480 32 [] I again get the warnings: ld: warning: in /opt/local/lib/libSDL.dylib, file is not of required architecture ld: warning: in /opt/local/lib/libSDLmain.a, file is not of required architecture and then a bunch of undefined symbols such as: _SDL_Init _SDL_SetClipRect Well this post basically based on the assumption that the warnings are breaking the SDL library and thereby keeping my code from compiling - so how do I fix those warnings? - Sorry for the long mail Malthe -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091115/94a3e4b3/attachment.html From allbery at ece.cmu.edu Sun Nov 15 20:27:48 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sun Nov 15 20:03:31 2009 Subject: [Haskell-beginners] Dynamic libraries not of required architecture when installing via cabal (Snow Leopard) In-Reply-To: References: Message-ID: Skipped content of type multipart/alternative-------------- 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/20091115/85f752b7/PGP.bin From ppirrip at gmail.com Sun Nov 15 22:50:05 2009 From: ppirrip at gmail.com (Phillip Pirrip) Date: Sun Nov 15 22:25:39 2009 Subject: [Haskell-beginners] Functor question. Message-ID: Hi, When I define my data as fellow, data Moo a = Moo a deriving (Show) instance Functor Moo where fmap f (Moo a) = Moo (f a) GHC gives me no problem. Then I add something, data (Num a) => Moo a = Moo a deriving (Show) instance Functor Moo where fmap f (Moo a) = Moo (f a) Now GHC gives me the follow error - see bellow. What is the reason behind this? What should I do to correct this? thx, // matFun_v2.hs:16:12: Could not deduce (Num a) from the context () arising from a use of `Moo' at matFun_v2.hs:16:12-14 Possible fix: add (Num a) to the context of the type signature for `fmap' In the pattern: Moo a In the definition of `fmap': fmap f (Moo a) = Moo (f a) In the instance declaration for `Functor Moo' matFun_v2.hs:16:21: Could not deduce (Num b) from the context () arising from a use of `Moo' at matFun_v2.hs:16:21-29 Possible fix: add (Num b) to the context of the type signature for `fmap' In the expression: Moo (f a) In the definition of `fmap': fmap f (Moo a) = Moo (f a) In the instance declaration for `Functor Moo' From alexander.dunlap at gmail.com Sun Nov 15 23:07:36 2009 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Sun Nov 15 22:43:28 2009 Subject: [Haskell-beginners] Functor question. In-Reply-To: References: Message-ID: <57526e770911152007y54165145veae92d4afd5523b4@mail.gmail.com> On Sun, Nov 15, 2009 at 7:50 PM, Phillip Pirrip wrote: > > Hi, > > When I define my data as fellow, > > data Moo a = Moo a > ? ? ? ? ? ?deriving (Show) > > instance Functor Moo where > ? fmap f (Moo a) = Moo (f a) > > GHC gives me no problem. ?Then I add something, > > data (Num a) => Moo a = Moo a > ? ? ? ? ? ?deriving (Show) > > instance Functor Moo where > ? fmap f (Moo a) = Moo (f a) > > Now GHC gives me the follow error - see bellow. > > What is the reason behind this? ?What should I do to correct this? > > thx, > > // > > matFun_v2.hs:16:12: > ? Could not deduce (Num a) from the context () > ? ? arising from a use of `Moo' at matFun_v2.hs:16:12-14 > ? Possible fix: > ? ? add (Num a) to the context of the type signature for `fmap' > ? In the pattern: Moo a > ? In the definition of `fmap': fmap f (Moo a) = Moo (f a) > ? In the instance declaration for `Functor Moo' > > matFun_v2.hs:16:21: > ? Could not deduce (Num b) from the context () > ? ? arising from a use of `Moo' at matFun_v2.hs:16:21-29 > ? Possible fix: > ? ? add (Num b) to the context of the type signature for `fmap' > ? In the expression: Moo (f a) > ? In the definition of `fmap': fmap f (Moo a) = Moo (f a) > ? In the instance declaration for `Functor Moo' > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > Your datatype Moo cannot be an instance of Functor because Moo cannot contain all types. fmap takes a function of type (a -> b), which means that the function can be from *any* type a to *any* type b, and produces a function of type (f a -> f b), which in your case means Moo a -> Moo b. But the function fmap f (Moo x) = Moo (f x) does not have type "a -> b"; it has type "(Num a, Num b) => a -> b", since if you can have a type Moo a, a must be an instance of Num. In general, people recommend against using constriants on datatypes, recommending instead to put those constraints on the functions that operate on the datatypes. I'm not quite sure why that is, though. Alex From ppirrip at gmail.com Sun Nov 15 23:34:39 2009 From: ppirrip at gmail.com (Phillip Pirrip) Date: Sun Nov 15 23:10:14 2009 Subject: [Haskell-beginners] Functor question. In-Reply-To: <57526e770911152007y54165145veae92d4afd5523b4@mail.gmail.com> References: <57526e770911152007y54165145veae92d4afd5523b4@mail.gmail.com> Message-ID: <9B0F47A5-1D25-4144-800D-B91A94D6B9DB@gmail.com> On 2009-11-15, at 11:07 PM, Alexander Dunlap wrote: > On Sun, Nov 15, 2009 at 7:50 PM, Phillip Pirrip wrote: >> >> Hi, >> >> When I define my data as fellow, >> >> data Moo a = Moo a >> deriving (Show) >> >> instance Functor Moo where >> fmap f (Moo a) = Moo (f a) >> >> GHC gives me no problem. Then I add something, >> >> data (Num a) => Moo a = Moo a >> deriving (Show) >> >> instance Functor Moo where >> fmap f (Moo a) = Moo (f a) >> >> Now GHC gives me the follow error - see bellow. >> >> What is the reason behind this? What should I do to correct this? >> >> thx, >> >> // >> >> matFun_v2.hs:16:12: >> Could not deduce (Num a) from the context () >> arising from a use of `Moo' at matFun_v2.hs:16:12-14 >> Possible fix: >> add (Num a) to the context of the type signature for `fmap' >> In the pattern: Moo a >> In the definition of `fmap': fmap f (Moo a) = Moo (f a) >> In the instance declaration for `Functor Moo' >> >> matFun_v2.hs:16:21: >> Could not deduce (Num b) from the context () >> arising from a use of `Moo' at matFun_v2.hs:16:21-29 >> Possible fix: >> add (Num b) to the context of the type signature for `fmap' >> In the expression: Moo (f a) >> In the definition of `fmap': fmap f (Moo a) = Moo (f a) >> In the instance declaration for `Functor Moo' >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > > Your datatype Moo cannot be an instance of Functor because Moo cannot > contain all types. fmap takes a function of type (a -> b), which means > that the function can be from *any* type a to *any* type b, and > produces a function of type (f a -> f b), which in your case means Moo > a -> Moo b. But the function fmap f (Moo x) = Moo (f x) does not have > type "a -> b"; it has type "(Num a, Num b) => a -> b", since if you > can have a type Moo a, a must be an instance of Num. > > In general, people recommend against using constriants on datatypes, > recommending instead to put those constraints on the functions that > operate on the datatypes. I'm not quite sure why that is, though. > > Alex Thanks Alex. That is very clear. I didn't expect that (Num a, Num b)=>a->b is actually different than a->b from the compiler point of view. I was under the assumption that the more constraint I put there the better for the compiler. //pip From ppirrip at gmail.com Mon Nov 16 00:33:51 2009 From: ppirrip at gmail.com (Phillip Pirrip) Date: Mon Nov 16 00:09:24 2009 Subject: [Haskell-beginners] Question on data/type Message-ID: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> Hi, I have the following data defined. data TypeCon a = ValConA a | ValConB [a] | ValConC [[a]] So I can use functions with type like (a->a->a) -> TypeCon a -> TypeCon a -> TypeCon a for all 3 value types, and I think is easier to define one single typeclass for (+), (*) etc. If I want to express the following idea (the following won't compiler): data TypeCon a = ValConA a | ValConB [ValConA a] | ValConC [ValConB a] Is this even a good idea? If so how could I proceed? The closest thing I can get to compiler is like this: data TypeCon a = ValConA a | ValConB [TypeCon a] Which is a nightmare when I try to manipulate anything in this structure. The alternative I guess is to use 3 different type constructors, data TypeConA a = ValConA a data TypeConB a = ValConB [ValConA a] data TypeConC a = ValConC [ValConB a] but then I can't use one signal typeclass for (+) etc. Am I correct? thx, //pip From byorgey at seas.upenn.edu Mon Nov 16 06:47:43 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Nov 16 06:23:13 2009 Subject: [Haskell-beginners] Functor question. In-Reply-To: <57526e770911152007y54165145veae92d4afd5523b4@mail.gmail.com> References: <57526e770911152007y54165145veae92d4afd5523b4@mail.gmail.com> Message-ID: <20091116114743.GA7859@seas.upenn.edu> On Sun, Nov 15, 2009 at 08:07:36PM -0800, Alexander Dunlap wrote: > > In general, people recommend against using constriants on datatypes, > recommending instead to put those constraints on the functions that > operate on the datatypes. I'm not quite sure why that is, though. It is because adding a constraint to a datatype definition only puts a constraint on the *constructor*---in particular, you don't get any constraints when pattern-matching, and you have to put the constraints on functions that operate on the datatype anyway. -Brent From iaefai at me.com Mon Nov 16 11:57:45 2009 From: iaefai at me.com (=?iso-8859-1?Q?i=E6fai?=) Date: Mon Nov 16 11:33:46 2009 Subject: [Haskell-beginners] Question on data/type In-Reply-To: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> References: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> Message-ID: <074DDF16-E80A-4F22-8C36-BB2527AF0735@me.com> I will try to help with my limited knowledge and what I believe to be going on. When you try to compile: > data TypeCon a = ValConA a | ValConB [ValConA a] | ValConC [ValConB a] You get this: Not in scope: type constructor or class `ValConA' Not in scope: type constructor or class `ValConB' What you have here is a type constructor TypeCon and a data constructor ValConA, ValConB, ValConC. When you are constructing your different data constructors (such as ValConA) you have to give it type constructors, or substitutes like a. You can do this: data TypeCon a = ValConA a | ValConB [TypeCon a] Regards, i?fai. On 2009-11-16, at 12:33 AM, Phillip Pirrip wrote: > Hi, > > I have the following data defined. > > data TypeCon a = ValConA a | ValConB [a] | ValConC [[a]] > > So I can use functions with type like (a->a->a) -> TypeCon a -> TypeCon a -> TypeCon a > for all 3 value types, and I think is easier to define one single typeclass for (+), (*) etc. > > If I want to express the following idea (the following won't compiler): > > data TypeCon a = ValConA a | ValConB [ValConA a] | ValConC [ValConB a] > > Is this even a good idea? If so how could I proceed? The closest thing I can get to compiler is like this: > > data TypeCon a = ValConA a | ValConB [TypeCon a] > > Which is a nightmare when I try to manipulate anything in this structure. The alternative I guess is to use 3 different type constructors, > > data TypeConA a = ValConA a > data TypeConB a = ValConB [ValConA a] > data TypeConC a = ValConC [ValConB a] > > but then I can't use one signal typeclass for (+) etc. Am I correct? > > thx, > > //pip > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From byorgey at seas.upenn.edu Mon Nov 16 13:17:19 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Nov 16 12:52:49 2009 Subject: [Haskell-beginners] Question on data/type In-Reply-To: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> References: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> Message-ID: <20091116181719.GA10703@seas.upenn.edu> On Mon, Nov 16, 2009 at 12:33:51AM -0500, Phillip Pirrip wrote: > Hi, > > I have the following data defined. > > data TypeCon a = ValConA a | ValConB [a] | ValConC [[a]] > > So I can use functions with type like (a->a->a) -> TypeCon a -> TypeCon a -> TypeCon a > for all 3 value types, and I think is easier to define one single typeclass for (+), (*) etc. > > If I want to express the following idea (the following won't compiler): > > data TypeCon a = ValConA a | ValConB [ValConA a] | ValConC [ValConB a] > The reason this doesn't compile is that ValConA and ValConB are not types. Indeed, as their names suggest, they are value constructors. I see what you are trying to do here, but in Haskell there is no way to say 'the type of things which were constructed using the ValConB constructor', you can only say 'TypeCon a' which includes values built out of all three constructors. > data TypeCon a = ValConA a | ValConB [TypeCon a] > > Which is a nightmare when I try to manipulate anything in this structure. Right, this isn't really the same thing: this type features such fun friends as ValConB [ValConA 3, ValConA 6, ValConB [ValConB [ValConA 2], ValConA 9]] and so on. > The alternative I guess is to use 3 different type constructors, > > data TypeConA a = ValConA a > data TypeConB a = ValConB [ValConA a] > data TypeConC a = ValConC [ValConB a] > > but then I can't use one signal typeclass for (+) etc. Am I correct? Yes, this seems like the correct alternative to me. What is so bad about having three separate (smaller) type class instances? In my opinion that would break up the code a bit and make it easier to read anyway, as opposed to a single monolithic instance for TypeCon. -Brent From matwong at rogers.com Sun Nov 15 22:47:53 2009 From: matwong at rogers.com (Matthew Wong) Date: Mon Nov 16 23:06:42 2009 Subject: [Haskell-beginners] Functor question Message-ID: Hi, When I define my data as fellow, data Moo a = Moo a deriving (Show) instance Functor Moo where fmap f (Moo a) = Moo (f a) GHC gives me no problem. Then I add something, data (Num a) => Moo a = Moo a deriving (Show) instance Functor Moo where fmap f (Moo a) = Moo (f a) Now GHC gives me the follow error - see bellow. What is the reason behind this? What should I do to correct this? thx, // matFun_v2.hs:16:12: Could not deduce (Num a) from the context () arising from a use of `Moo' at matFun_v2.hs:16:12-14 Possible fix: add (Num a) to the context of the type signature for `fmap' In the pattern: Moo a In the definition of `fmap': fmap f (Moo a) = Moo (f a) In the instance declaration for `Functor Moo' matFun_v2.hs:16:21: Could not deduce (Num b) from the context () arising from a use of `Moo' at matFun_v2.hs:16:21-29 Possible fix: add (Num b) to the context of the type signature for `fmap' In the expression: Moo (f a) In the definition of `fmap': fmap f (Moo a) = Moo (f a) In the instance declaration for `Functor Moo' From matwong at rogers.com Mon Nov 16 00:31:00 2009 From: matwong at rogers.com (Matthew Wong) Date: Mon Nov 16 23:07:20 2009 Subject: [Haskell-beginners] Questions on data/type Message-ID: <44134FB4-6361-4473-AE4A-B8FA53F49DEB@rogers.com> Hi, I have the following data defined. data TypeCon a = ValConA a | ValConB [a] | ValConC [[a]] So I can use functions with type like (a->a->a) -> TypeCon a -> TypeCon a -> TypeCon a for all 3 value types, and I think is easier to define one single typeclass for (+), (*) etc. If I want to express the following idea (the following won't compiler): data TypeCon a = ValConA a | ValConB [ValConA a] | ValConC [ValConB a] Is this even a good idea? If so how could I proceed? The closest thing I can get to compiler is like this: data TypeCon a = ValConA a | ValConB [TypeCon a] Which is a nightmare when I try to manipulate anything in this structure. The alternative is use 3 different type constructors, data TypeConA a = ValConA a data TypeConB a = ValConB a data TypeConC a = ValConC a but then I can't use one signal typeclass for (+) etc. thx, //pip From jason.dusek at gmail.com Tue Nov 17 01:07:45 2009 From: jason.dusek at gmail.com (Jason Dusek) Date: Tue Nov 17 00:43:13 2009 Subject: [Haskell-beginners] Functor question In-Reply-To: References: Message-ID: <42784f260911162207t1ed685b0me3b5ffcbed8efff4@mail.gmail.com> Functor must be defined for all types -- not some restriction thereof (hence you see talk of indexed functors). Thus `fmap` needs to be typeable for any `a -> b` but the construcor `Moo` is only typeable at `a, b` such that we have both `Num a, Num b`. -- Jason Dusek From jason.dusek at gmail.com Tue Nov 17 01:11:32 2009 From: jason.dusek at gmail.com (Jason Dusek) Date: Tue Nov 17 00:47:00 2009 Subject: [Haskell-beginners] Questions on data/type In-Reply-To: <44134FB4-6361-4473-AE4A-B8FA53F49DEB@rogers.com> References: <44134FB4-6361-4473-AE4A-B8FA53F49DEB@rogers.com> Message-ID: <42784f260911162211i6b9e36f2xfc7779904912275@mail.gmail.com> 2009/11/15 Matthew Wong : > If I want to express the following idea (the following won't compiler): > > data TypeCon a = ValConA a | ValConB [ValConA a] | ValConC [ValConB a] In this definition, you are confusing constructors with types. You can't have a list of `ValConB a` -- the type is actually `TypeCon a`. > The alternative is use 3 different type constructors, > > data TypeConA a = ValConA a > data TypeConB a = ValConB a > data TypeConC a = ValConC a This is more promising. I'd need to see the typeclass you're trying to define to say more. -- Jason Dusek From dav.vire+haskell at gmail.com Tue Nov 17 04:56:15 2009 From: dav.vire+haskell at gmail.com (David Virebayre) Date: Tue Nov 17 04:31:45 2009 Subject: [Haskell-beginners] Question on data/type In-Reply-To: <20091116181719.GA10703@seas.upenn.edu> References: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> <20091116181719.GA10703@seas.upenn.edu> Message-ID: <4c88418c0911170156v6fdea443lc4c89d9ca6c4928b@mail.gmail.com> On Mon, Nov 16, 2009 at 7:17 PM, Brent Yorgey wrote: > On Mon, Nov 16, 2009 at 12:33:51AM -0500, Phillip Pirrip wrote: >> The alternative I guess is to use 3 different type constructors, >> data TypeConA a = ValConA a >> data TypeConB a = ValConB [ValConA a] >> data TypeConC a = ValConC [ValConB a] >> but then I can't use one signal typeclass for (+) etc. Am I correct? > Yes, this seems like the correct alternative to me. What is so bad With a minor correction : data TypeConA a = ValConA a data TypeConB a = ValConB [TypeConA a] data TypeConC a = ValConC [TypeConB a] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091117/987ab093/attachment.html From felipe.lessa at gmail.com Tue Nov 17 06:40:04 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Tue Nov 17 06:15:34 2009 Subject: [Haskell-beginners] Question on data/type In-Reply-To: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> References: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> Message-ID: (This e-mail is literate Haskell) Not that this is the right solution to your problems, but... > {-# LANGUAGE GADTs, EmptyDataDecls, > FlexibleInstances, FlexibleContexts #-} > > import Control.Applicative This requires EmptyDataDecls: > data TypeConA > data TypeConB > data TypeConC We're gonna use those empty data types as phantom types in our data type below. This requires GADTs: > data TypeCon t a where > ValConA :: a -> TypeCon TypeConA a > ValConB :: [TypeCon TypeConA a] -> TypeCon TypeConB a > ValConC :: [TypeCon TypeConB a] -> TypeCon TypeConC a Using the phantom types we tell the type system what kind of value we want. Now, some useful instances because we can't derive them: > instance Show a => Show (TypeCon t a) where > showsPrec n x = showParen (n > 10) $ > case x of > ValConA a -> showString "ValConA " . showsPrec 11 a > ValConB a -> showString "ValConB " . showsPrec 11 a > ValConC a -> showString "ValConC " . showsPrec 11 a > > instance Eq a => Eq (TypeCon t a) where > (ValConA a) == (ValConA b) = (a == b) > (ValConB a) == (ValConB b) = (a == b) > (ValConC a) == (ValConC b) = (a == b) > _ == _ = error "never here" The 't' phantom type guarantees that we'll never reach that last definition, e.g. *Main> (ValConA True) == (ValConB []) :1:19: Couldn't match expected type `TypeConA' against inferred type `TypeConB' Expected type: TypeCon TypeConA Bool Inferred type: TypeCon TypeConB a In the second argument of `(==)', namely `(ValConB [])' In the expression: (ValConA True) == (ValConB []) > instance Functor (TypeCon t) where > fmap f (ValConA a) = ValConA (f a) > fmap f (ValConB a) = ValConB (fmap (fmap f) a) > fmap f (ValConC a) = ValConC (fmap (fmap f) a) Now, if you want applicative then you'll need FlexibleInstances because we can't write 'pure :: a -> TypeCon t a'; this signature means that the user of the function may choose any 't' he wants, but we can give him only one of the 't's that appear in the constructors above. > instance Applicative (TypeCon TypeConA) where > pure x = ValConA x > (ValConA f) <*> (ValConA x) = ValConA (f x) > _ <*> _ = error "never here" > > instance Applicative (TypeCon TypeConB) where > pure x = ValConB [pure x] > (ValConB fs) <*> (ValConB xs) = ValConB (fmap (<*>) fs <*> xs) > _ <*> _ = error "never here" > > instance Applicative (TypeCon TypeConC) where > pure x = ValConC [pure x] > (ValConC fs) <*> (ValConC xs) = ValConC (fmap (<*>) fs <*> xs) > _ <*> _ = error "never here" Now that we have applicative we can also write, using FlexibleContexts, > liftBinOp :: Applicative (TypeCon t) => (a->b->c) > -> TypeCon t a -> TypeCon t b -> TypeCon t c > liftBinOp = liftA2 We need that 'Applicative' constraint because the type system doesn't know that we have already defined all possible 'Applicative' instances, so we have to live with that :). And then we can simply write > instance (Applicative (TypeCon t), Num a) => > Num (TypeCon t a) where > (+) = liftA2 (+) > (-) = liftA2 (-) > (*) = liftA2 (*) > negate = fmap negate > abs = fmap abs > signum = fmap signum > fromInteger = pure . fromInteger Finally, *Main> let x1 = ValConB [ValConA 10, ValConA 7] *Main> let x2 = ValConB [ValConA 5, ValConA 13] *Main> x1 * x2 ValConB [ValConA 50,ValConA 130,ValConA 35,ValConA 91] HTH, -- Felipe. From legajid at free.fr Tue Nov 17 16:24:26 2009 From: legajid at free.fr (legajid) Date: Tue Nov 17 15:56:32 2009 Subject: [Haskell-beginners] Named fields in data types Message-ID: <4B03148A.10009@free.fr> Hello, i've some trouble with named fields in data types. data Carnet = Adresse { nom :: String, cp :: Integer, ville :: String } | Telephone {nom::String, telnum::String} deriving Show contact01 = Adresse "Didier" 51100 "Reims" contact02 = Adresse {nom="Laure", cp=0} -- line 1 --contact02 Adresse { ville="Nogent" } -- line 2 --contact02 { ville="Nogent" } -- line 3 contact03=Telephone "Didier" "0326..." -- line 4 When loading this source : line 1 says "warning : Fields not initialized :ville line 2 and 3 when uncommented give parse error (possibly indentation) I'm ok with line 1. Is it possible to write such things as line2 or 3 ? Which syntax ? Thanks for help. Didier. From chaddai.fouche at gmail.com Tue Nov 17 16:55:05 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Tue Nov 17 16:30:32 2009 Subject: [Haskell-beginners] Named fields in data types In-Reply-To: <4B03148A.10009@free.fr> References: <4B03148A.10009@free.fr> Message-ID: On Tue, Nov 17, 2009 at 10:24 PM, legajid wrote: > Hello, > i've some trouble with named fields in data types. > > data Carnet = Adresse ?{ nom :: String, cp :: Integer, ville :: String ?} > ? ? ? | > ? ? ?Telephone {nom::String, telnum::String} > ? deriving Show > > contact01 = Adresse "Didier" 51100 "Reims" > contact02 = Adresse {nom="Laure", cp=0} -- line 1 > --contact02 Adresse { ville="Nogent" } ? ? ? -- line 2 > --contact02 { ville="Nogent" } ? ? ? ? ? ? ? ? ? ? -- line 3 > contact03=Telephone "Didier" "0326..." ? ? ? -- line 4 > > When loading this source : > line 1 says "warning : Fields not initialized :ville > line 2 and 3 when uncommented give parse error (possibly indentation) > > I'm ok with line 1. > Is it possible to write such things as line2 or 3 ? Which syntax ? line 2 appears correct except you forgot the "="... Of course some fields aren't initialized so you may have a problem if you try to access them later on. (La ligne 2 est correcte sauf que tu as oubli? le ?gal "="... Bien s?r certains des champs ne sont pas initialis?s et ?a pourrait poser probl?me si tu essaies d'y acc?der plus tard) Note that you can also create a new value with some fields in common with an old value, for instance : (Note que tu peux aussi cr?er une nouvelle valeur partageant un certain nombre de champs avec une autre valeur d?j? d?clar?e) > contact01 = Adresse "Didier" 51100 "Reims" > contact02 = contact01 { nom = "Charles" } Which leads to the practice of using records to create a "default setting" value where you just modify the field that concern you. (Ce qui a donn? lieu ? l'idiome qui consiste ? utiliser un type enregistrement (avec des champs nomm?s) pour les configuration avec une valeur "r?glage par d?faut" dont on ne modifie que les champs qui nous int?resse) > main = xmonad defaultConfig {terminal = "konsole"} -- Jeda? From ppirrip at gmail.com Tue Nov 17 21:46:45 2009 From: ppirrip at gmail.com (Phillip Pirrip) Date: Tue Nov 17 21:22:13 2009 Subject: [Haskell-beginners] Question on data/type In-Reply-To: References: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> Message-ID: Hi, Thanks everyone for their patience on my question and took the time to write back. I was thinking to re-phrase my question (to correct some typo etc), but many of you have already guessed my intent. I am trying to write a simple Matrix library, as my little learning exercise, so TypeConA : Scalar TypeConB : 1D array TypeConC : 2D array /matrix. So I would like to have one typeclass for operations like Scalar +/* Matrix etc. Felipe: you are way ahead of me (like showing me the answer before I do my exam), and I really appreciate your example code, since that is the level of understanding of Haskell I am looking forward to. I don't think I really understand the code yet, but I will give it a try and let you know. As this moment my level of understanding is basic Haskell syntax, basic Monad (going to try Monad/IArray for in-place non-destruction update) and just started to read up on Control.Applicative (and arrows) and Existential types. I have never even heard of phantom types until now. BTW, how do I generate "literate" Haskell code? I keep reading it but I still don't know how to make one (I am assuming it is more complicated then just type the code in with ">" in emacs). //pip On 2009-11-17, at 6:40 AM, Felipe Lessa wrote: > (This e-mail is literate Haskell) > > Not that this is the right solution to your problems, but... > >> {-# LANGUAGE GADTs, EmptyDataDecls, >> FlexibleInstances, FlexibleContexts #-} >> >> import Control.Applicative > > This requires EmptyDataDecls: > >> data TypeConA >> data TypeConB >> data TypeConC > > We're gonna use those empty data types as phantom types in our > data type below. This requires GADTs: > >> data TypeCon t a where >> ValConA :: a -> TypeCon TypeConA a >> ValConB :: [TypeCon TypeConA a] -> TypeCon TypeConB a >> ValConC :: [TypeCon TypeConB a] -> TypeCon TypeConC a > > Using the phantom types we tell the type system what kind of > value we want. Now, some useful instances because we can't > derive them: > >> instance Show a => Show (TypeCon t a) where >> showsPrec n x = showParen (n > 10) $ >> case x of >> ValConA a -> showString "ValConA " . showsPrec 11 a >> ValConB a -> showString "ValConB " . showsPrec 11 a >> ValConC a -> showString "ValConC " . showsPrec 11 a >> >> instance Eq a => Eq (TypeCon t a) where >> (ValConA a) == (ValConA b) = (a == b) >> (ValConB a) == (ValConB b) = (a == b) >> (ValConC a) == (ValConC b) = (a == b) >> _ == _ = error "never here" > > The 't' phantom type guarantees that we'll never reach that > last definition, e.g. > > *Main> (ValConA True) == (ValConB []) > > :1:19: > Couldn't match expected type `TypeConA' > against inferred type `TypeConB' > Expected type: TypeCon TypeConA Bool > Inferred type: TypeCon TypeConB a > In the second argument of `(==)', namely `(ValConB [])' > In the expression: (ValConA True) == (ValConB []) > >> instance Functor (TypeCon t) where >> fmap f (ValConA a) = ValConA (f a) >> fmap f (ValConB a) = ValConB (fmap (fmap f) a) >> fmap f (ValConC a) = ValConC (fmap (fmap f) a) > > Now, if you want applicative then you'll need FlexibleInstances > because we can't write 'pure :: a -> TypeCon t a'; this signature > means that the user of the function may choose any 't' he wants, > but we can give him only one of the 't's that appear in the > constructors above. > >> instance Applicative (TypeCon TypeConA) where >> pure x = ValConA x >> (ValConA f) <*> (ValConA x) = ValConA (f x) >> _ <*> _ = error "never here" >> >> instance Applicative (TypeCon TypeConB) where >> pure x = ValConB [pure x] >> (ValConB fs) <*> (ValConB xs) = ValConB (fmap (<*>) fs <*> xs) >> _ <*> _ = error "never here" >> >> instance Applicative (TypeCon TypeConC) where >> pure x = ValConC [pure x] >> (ValConC fs) <*> (ValConC xs) = ValConC (fmap (<*>) fs <*> xs) >> _ <*> _ = error "never here" > > Now that we have applicative we can also write, using > FlexibleContexts, > >> liftBinOp :: Applicative (TypeCon t) => (a->b->c) >> -> TypeCon t a -> TypeCon t b -> TypeCon t c >> liftBinOp = liftA2 > > We need that 'Applicative' constraint because the type system > doesn't know that we have already defined all possible > 'Applicative' instances, so we have to live with that :). > > And then we can simply write > >> instance (Applicative (TypeCon t), Num a) => >> Num (TypeCon t a) where >> (+) = liftA2 (+) >> (-) = liftA2 (-) >> (*) = liftA2 (*) >> negate = fmap negate >> abs = fmap abs >> signum = fmap signum >> fromInteger = pure . fromInteger > > Finally, > > *Main> let x1 = ValConB [ValConA 10, ValConA 7] > *Main> let x2 = ValConB [ValConA 5, ValConA 13] > *Main> x1 * x2 > ValConB [ValConA 50,ValConA 130,ValConA 35,ValConA 91] > > HTH, > > -- > Felipe. From daniel.is.fischer at web.de Tue Nov 17 22:59:41 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Nov 17 22:36:34 2009 Subject: [Haskell-beginners] Question on data/type In-Reply-To: References: <7DC11D2C-ABDE-4956-ADCF-5A5C9EA246B5@gmail.com> Message-ID: <200911180459.42866.daniel.is.fischer@web.de> Am Mittwoch 18 November 2009 03:46:45 schrieb Phillip Pirrip: > BTW, how do I generate "literate" Haskell code? ?I keep reading it but I > still don't know how to make one (I am assuming it is more complicated then > just type the code in with ">" in emacs). > > //pip No, it isn't. The hardest part is writing good code and comments (regardless of whether you write literate code or 'normal'). There are two ways of writing literal Haskell code, explained at http://haskell.org/onlinereport/syntax-iso.html#sect9.4 . a) 'Bird tack', start code lines with '>', write as normal (you can include -- and {- -} comments). *Separate '>'-lines from non-code lines by at least one blank line*. b) 'LaTeX' literate Haskell, code is begun by a line starting with "\begin{code}" and ended by "\end{code}". You can create really pretty stuff with that style. From legajid at free.fr Wed Nov 18 15:11:01 2009 From: legajid at free.fr (legajid) Date: Wed Nov 18 14:43:02 2009 Subject: [Haskell-beginners] Named fields in data types In-Reply-To: References: <4B03148A.10009@free.fr> Message-ID: <4B0454D5.2030401@free.fr> Chadda? Fouch? a ?crit : > On Tue, Nov 17, 2009 at 10:24 PM, legajid wrote: > >> Hello, >> i've some trouble with named fields in data types. >> >> data Carnet = Adresse { nom :: String, cp :: Integer, ville :: String } >> | >> Telephone {nom::String, telnum::String} >> deriving Show >> >> contact01 = Adresse "Didier" 51100 "Reims" >> contact02 = Adresse {nom="Laure", cp=0} -- line 1 >> --contact02 Adresse { ville="Nogent" } -- line 2 >> --contact02 { ville="Nogent" } -- line 3 >> contact03=Telephone "Didier" "0326..." -- line 4 >> >> When loading this source : >> line 1 says "warning : Fields not initialized :ville >> line 2 and 3 when uncommented give parse error (possibly indentation) >> >> I'm ok with line 1. >> Is it possible to write such things as line2 or 3 ? Which syntax ? >> > > line 2 appears correct except you forgot the "="... Of course some > fields aren't initialized so you may have a problem if you try to > access them later on. > (La ligne 2 est correcte sauf que tu as oubli? le ?gal "="... Bien s?r > certains des champs ne sont pas initialis?s et ?a pourrait poser > probl?me si tu essaies d'y acc?der plus tard) > > Note that you can also create a new value with some fields in common > with an old value, for instance : > (Note que tu peux aussi cr?er une nouvelle valeur partageant un > certain nombre de champs avec une autre valeur d?j? d?clar?e) > > >> contact01 = Adresse "Didier" 51100 "Reims" >> contact02 = contact01 { nom = "Charles" } >> > > Which leads to the practice of using records to create a "default > setting" value where you just modify the field that concern you. > (Ce qui a donn? lieu ? l'idiome qui consiste ? utiliser un type > enregistrement (avec des champs nomm?s) pour les configuration avec > une valeur "r?glage par d?faut" dont on ne modifie que les champs qui > nous int?resse) > > >> main = xmonad defaultConfig {terminal = "konsole"} >> > > I've tried these lines : contact01 = Adresse "Didier" 51100 "Reims" contact02 = Adresse {nom="Laure", cp=0} contact02 = contact02 { ville="Nogent" } but i get an error : multiple declarations of Main.contact02 So, does it mean i can't add values to contact02. Instead, i must create a contact03 based on contact02 ? Didier. From ezyang at MIT.EDU Wed Nov 18 15:38:33 2009 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Wed Nov 18 15:20:00 2009 Subject: [Haskell-beginners] Named fields in data types In-Reply-To: <4B0454D5.2030401@free.fr> References: <4B03148A.10009@free.fr> <4B0454D5.2030401@free.fr> Message-ID: <1258576646-sup-8987@ezyang> Excerpts from legajid's message of Wed Nov 18 15:11:01 -0500 2009: > I've tried these lines : > contact01 = Adresse "Didier" 51100 "Reims" > contact02 = Adresse {nom="Laure", cp=0} > contact02 = contact02 { ville="Nogent" } > > but i get an error : multiple declarations of Main.contact02 > So, does it mean i can't add values to contact02. Instead, i must create > a contact03 based on contact02 ? Yep; part of the point behind a pure functional language is to not allow mutation by default. Cheers, Edward From iaefai at me.com Fri Nov 20 02:58:30 2009 From: iaefai at me.com (=?iso-8859-1?Q?i=E6fai?=) Date: Fri Nov 20 02:33:52 2009 Subject: [Haskell-beginners] Windows API and FFI Message-ID: I have a specific function that I would like to get info to allow me to accept clicks into the cmd.exe window. The function seems to be here: http://msdn.microsoft.com/en-us/library/ms684961(VS.85).aspx One of the parameters is this: A pointer to an array of INPUT_RECORD structures that receives the input buffer data. The total size of the array required will be less than 64K. There are in and out parameters for this function. I have never done anything like this before, and was hoping this is done somewhere, or it is fairly easy to do. Any help would be appreciated. - i?fai. From jeffzaroyko at gmail.com Fri Nov 20 03:11:01 2009 From: jeffzaroyko at gmail.com (Jeff Zaroyko) Date: Fri Nov 20 02:46:21 2009 Subject: [Haskell-beginners] Windows API and FFI In-Reply-To: References: Message-ID: On Fri, Nov 20, 2009 at 6:58 PM, i?fai wrote: > I have a specific function that I would like to get info to allow me to accept clicks into the cmd.exe window. > > The function seems to be here: > > http://msdn.microsoft.com/en-us/library/ms684961(VS.85).aspx > > One of the parameters is this: A pointer to an array of INPUT_RECORD structures that receives the input buffer data. The total size of the array required will be less than 64K. > > There are in and out parameters for this function. I have never done anything like this before, and was hoping this is done somewhere, or it is fairly easy to do. If you have not already, start by looking at the Win32 package which has bindings to some Win32 functions, which includes helper functions and types which you should find useful. As to the specific structure required, I'm not sure if it's covered, but it's a reasonable starting point. From jack at realmode.com Fri Nov 20 17:22:08 2009 From: jack at realmode.com (I. J. Kennedy) Date: Fri Nov 20 16:57:26 2009 Subject: [Haskell-beginners] points-free problem Message-ID: <1008bfc90911201422t56f00c6ep429f929d155d7643@mail.gmail.com> I know I'm going to kick myself when the answer is revealed by one of you kind folks, but after staring at this a while I just can't figure out what's going on. The compiler (ghci) is trying so hard to tell me what's wrong, but I am failing to understand. I thought for the most part one could take a function definition like f x = (blah blah blah) x and turn it into points-free style by f = (blah blah blah) But from the dialog below, my assumption is incorrect. Help? I. J. Kennedy > sortBy (compare `on` fst) [(2,3),(0,1),(1,5)] ? -- test a little sort expression [(0,1),(1,5),(2,3)] > let sortpairs xss = sortBy (compare `on` fst) xss ? -- make it into a function > :t sortpairs sortpairs :: (Ord a) => [(a, b)] -> [(a, b)] > sortpairs [(2,3),(0,1),(1,5)] [(0,1),(1,5),(2,3)] > let sortpairs = sortBy (compare `on` fst) ? ?-- points-free style > sortpairs [(2,3),(0,1),(1,5)] :1:24: ?? ?No instance for (Num ()) ?? ? ?arising from the literal `1' at :1:24 ?? ?Possible fix: add an instance declaration for (Num ()) ?? ?In the expression: 1 ?? ?In the expression: (1, 5) ?? ?In the first argument of `sortpairs', namely ?? ? ? ?`[(2, 3), (0, 1), (1, 5)]' > :t sortpairs sortpairs :: [((), b)] -> [((), b)] -- what?! From daniel.is.fischer at web.de Fri Nov 20 17:41:53 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Nov 20 17:18:37 2009 Subject: [Haskell-beginners] points-free problem In-Reply-To: <1008bfc90911201422t56f00c6ep429f929d155d7643@mail.gmail.com> References: <1008bfc90911201422t56f00c6ep429f929d155d7643@mail.gmail.com> Message-ID: <200911202341.53566.daniel.is.fischer@web.de> Am Freitag 20 November 2009 23:22:08 schrieb I. J. Kennedy: > I know I'm going to kick myself when the answer is revealed by one of > you kind folks, but after staring at this a while I just can't figure > out what's going on. The compiler (ghci) is trying so hard to tell me > what's wrong, but I am failing to understand. I thought for the most > part one could take a function definition like > > f x = (blah blah blah) x > > and turn it into points-free style by > > f = (blah blah blah) > > But from the dialog below, my assumption is incorrect. > Help? > > I. J. Kennedy Monomorphism restriction. By that, if you bind f via f = (blah blah blah) and don't give a type signature, f gets a monomorphic type. Dreadful details in the report, section 4.5.(?) Put ":set -XNoMonomorphismRestriction" in your .ghci file. > > > sortBy (compare `on` fst) [(2,3),(0,1),(1,5)] ? -- test a little sort > > expression > > [(0,1),(1,5),(2,3)] > > > let sortpairs xss = sortBy (compare `on` fst) xss ? -- make it into a > > function > > > > :t sortpairs > > sortpairs :: (Ord a) => [(a, b)] -> [(a, b)] > > > sortpairs [(2,3),(0,1),(1,5)] > > [(0,1),(1,5),(2,3)] > > > let sortpairs = sortBy (compare `on` fst) ? ?-- points-free style > > sortpairs [(2,3),(0,1),(1,5)] > > :1:24: > ?? ?No instance for (Num ()) > ?? ? ?arising from the literal `1' at :1:24 > ?? ?Possible fix: add an instance declaration for (Num ()) > ?? ?In the expression: 1 > ?? ?In the expression: (1, 5) > ?? ?In the first argument of `sortpairs', namely > ?? ? ? ?`[(2, 3), (0, 1), (1, 5)]' > > > :t sortpairs > > sortpairs :: [((), b)] -> [((), b)] -- what?! From mpm at alumni.caltech.edu Fri Nov 20 18:10:48 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Fri Nov 20 17:46:13 2009 Subject: [Haskell-beginners] points-free problem In-Reply-To: <200911202341.53566.daniel.is.fischer@web.de> References: <1008bfc90911201422t56f00c6ep429f929d155d7643@mail.gmail.com> <200911202341.53566.daniel.is.fischer@web.de> Message-ID: <4B0721F8.4090502@alumni.caltech.edu> I've been on this list for something like 7 months and I think "monomorphism restriction" is the answer to about 70% of newbie/intermediate questions. I don't always understand their questions but one can pretty much guess the answer. Daniel Fischer wrote: > Monomorphism restriction. > By that, if you bind f via > > f = (blah blah blah) > > and don't give a type signature, f gets a monomorphic type. Dreadful details in the > report, section 4.5.(?) > From daniel.is.fischer at web.de Fri Nov 20 18:31:42 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Nov 20 18:08:42 2009 Subject: [Haskell-beginners] points-free problem In-Reply-To: <4B0721F8.4090502@alumni.caltech.edu> References: <1008bfc90911201422t56f00c6ep429f929d155d7643@mail.gmail.com> <200911202341.53566.daniel.is.fischer@web.de> <4B0721F8.4090502@alumni.caltech.edu> Message-ID: <200911210031.42688.daniel.is.fischer@web.de> Am Samstag 21 November 2009 00:10:48 schrieb Michael Mossey: > I've been on this list for something like 7 months and I think > "monomorphism restriction" is the answer to about 70% of Certainly seems like that sometimes. But actually it's only 46.35% ;) Earnestly, it's apparently the thing by far the most people trip over. It would probably be a good thing to have it disabled by default in ghci as that's where it bites most often. On the other hand, it means lots of easy answers on the lists 8-) > newbie/intermediate questions. I don't always understand their questions > but one can pretty much guess the answer. > > Daniel Fischer wrote: > > Monomorphism restriction. > > By that, if you bind f via > > > > f = (blah blah blah) > > > > and don't give a type signature, f gets a monomorphic type. Dreadful > > details in the report, section 4.5.(?) > From jon at ffconsultancy.com Fri Nov 20 23:36:42 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Fri Nov 20 21:58:50 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <200911061019.50935.shawn-haskell@willden.org> References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> Message-ID: <200911210436.42523.jon@ffconsultancy.com> On Friday 06 November 2009 17:19:50 Shawn Willden wrote: > On Friday 06 November 2009 09:52:48 am Cory Knapp wrote: > > Idiomatic Haskell won't be as fast as idiomatic C++, but it will blow > > Python away. > > Based on the little bit of stuff I've done, I think I'd characterize it > this way: C++ will be maybe twice as fast as Haskell. Maybe a little > more, maybe a little less, depending on a lot of details. For heavy > computation, Python will be a couple orders of magnitude slower than both. > > IOW, Haskell is slower than C++ but it's in the same ballpark. > > Would anyone disagree? The long-standing bug in GHC's garbage collector that makes writing a single boxed value into an array O(n) instead of O(1), because the GC dirties and retraverses the entire array, makes it impossible to write efficient Haskell code to solve many basic problems. Here is a simple dictionary benchmark where Python is 4x faster than Haskell because this bug means it is impossible to implement a competitively- performant dictionary: http://flyingfrogblog.blogspot.com/2009/04/f-vs-ocaml-vs-haskell-hash-table.html Haskell's celebrated idiomatic quicksort is actually 6,000x slower than a traditional implementation on this machine and consumes asymptotically more memory (making it useless for quite mundane problems): http://www.haskell.org/haskellwiki/Introduction#Quicksort_in_Haskell Although people have created array-based quicksorts in Haskell the same perf bug in the GC means that a generic quicksort in Haskell would be asymptotically slower if it were given an array of boxed values. As an aside, purity complicates the creation of a parallel generic quicksort because it is necessary to mutate different parts of the same array in parallel. AFAICT, writing an efficient parallel generic quicksort is an unsolved problem in Haskell. Suffice to say, I cannot agree that Haskell is in the same ballpark as C++ in terms of performance. :-) -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From Ben.Lippmeier at anu.edu.au Sat Nov 21 01:38:09 2009 From: Ben.Lippmeier at anu.edu.au (Ben Lippmeier) Date: Sat Nov 21 01:13:30 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <200911210436.42523.jon@ffconsultancy.com> References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> <200911210436.42523.jon@ffconsultancy.com> Message-ID: On 21/11/2009, at 15:36 , Jon Harrop wrote: > The long-standing bug in GHC's garbage collector that makes writing a single > boxed value into an array O(n) instead of O(1), because the GC dirties and > retraverses the entire array, makes it impossible to write efficient Haskell > code to solve many basic problems. Are you talking about http://hackage.haskell.org/trac/ghc/ticket/650 ? The way I read that ticket is that writing a boxed value to a mutable array is still O(1), but the garbage collector traverses the whole array during scanning. That could certainly slow down GC cycles, but how does it make array update O(n)? (update of the standard Haskell "pure" arrays being a separate issue, of course). Ben. From nicolas.pouillard at gmail.com Sat Nov 21 05:13:22 2009 From: nicolas.pouillard at gmail.com (Nicolas Pouillard) Date: Sat Nov 21 04:48:38 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> <200911210436.42523.jon@ffconsultancy.com> Message-ID: <1258798176-sup-2681@peray> Excerpts from Ben Lippmeier's message of Sat Nov 21 07:38:09 +0100 2009: > > On 21/11/2009, at 15:36 , Jon Harrop wrote: > > > The long-standing bug in GHC's garbage collector that makes writing a single > > boxed value into an array O(n) instead of O(1), because the GC dirties and > > retraverses the entire array, makes it impossible to write efficient Haskell > > code to solve many basic problems. > > Are you talking about http://hackage.haskell.org/trac/ghc/ticket/650 ? > > The way I read that ticket is that writing a boxed value to a mutable array is still O(1), but the garbage collector traverses the whole array during > scanning. That could certainly slow down GC cycles, but how does it make array update O(n)? He means in worst case. Writing once, will cause O(n) during the next GC. Of course if you do a lot of updates between two GCs their is no extra penalty. So if you make 'k' updates between 2 GCs it costs you k*O(1)+O(n) which is still O(n) but practically nicer than k*O(n). -- Nicolas Pouillard http://nicolaspouillard.fr From ben.lippmeier at anu.edu.au Sat Nov 21 06:56:09 2009 From: ben.lippmeier at anu.edu.au (Ben Lippmeier) Date: Sat Nov 21 06:31:31 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <1258798176-sup-2681@peray> References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> <200911210436.42523.jon@ffconsultancy.com> <1258798176-sup-2681@peray> Message-ID: <5816568E-3AFA-4E23-AAE4-7ACC60B43AEA@anu.edu.au> On 21/11/2009, at 21:13 , Nicolas Pouillard wrote: > Excerpts from Ben Lippmeier's message of Sat Nov 21 07:38:09 +0100 2009: >> >> On 21/11/2009, at 15:36 , Jon Harrop wrote: >> >>> The long-standing bug in GHC's garbage collector that makes writing a single >>> boxed value into an array O(n) instead of O(1), because the GC dirties and >>> retraverses the entire array, makes it impossible to write efficient Haskell >>> code to solve many basic problems. >> >> Are you talking about http://hackage.haskell.org/trac/ghc/ticket/650 ? >> >> The way I read that ticket is that writing a boxed value to a mutable array is still O(1), but the garbage collector traverses the whole array during >> scanning. That could certainly slow down GC cycles, but how does it make array update O(n)? > > He means in worst case. Writing once, will cause O(n) during the next GC. Of > course if you do a lot of updates between two GCs their is no extra penalty. > So if you make 'k' updates between 2 GCs it costs you k*O(1)+O(n) which is > still O(n) but practically nicer than k*O(n). > Hmm. I'd be careful about conflating algorithmic complexity with memory management issues. By the above reasoning, if I were to run any program using arrays on a system with a two space garbage collector (which copies all live objects during each GC) I could say the worst case algorithmic complexity was O(n). That doesn't sound right. I could take this further and say that in a virtual memory system, there is a chance that the whole heap gets copied to the disk and back between each array update. I might again say this has O(n) complexity, but it wouldn't be very helpful... Ben. From nicolas.pouillard at gmail.com Sat Nov 21 09:10:05 2009 From: nicolas.pouillard at gmail.com (Nicolas Pouillard) Date: Sat Nov 21 08:45:23 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <5816568E-3AFA-4E23-AAE4-7ACC60B43AEA@anu.edu.au> References: <4AF45460.8060809@gmail.com> <200911061019.50935.shawn-haskell@willden.org> <200911210436.42523.jon@ffconsultancy.com> <1258798176-sup-2681@peray> <5816568E-3AFA-4E23-AAE4-7ACC60B43AEA@anu.edu.au> Message-ID: <1258812414-sup-2576@peray> Excerpts from Ben Lippmeier's message of Sat Nov 21 12:56:09 +0100 2009: > > On 21/11/2009, at 21:13 , Nicolas Pouillard wrote: > > > Excerpts from Ben Lippmeier's message of Sat Nov 21 07:38:09 +0100 2009: > >> > >> On 21/11/2009, at 15:36 , Jon Harrop wrote: > >> > >>> The long-standing bug in GHC's garbage collector that makes writing a single > >>> boxed value into an array O(n) instead of O(1), because the GC dirties and > >>> retraverses the entire array, makes it impossible to write efficient Haskell > >>> code to solve many basic problems. > >> > >> Are you talking about http://hackage.haskell.org/trac/ghc/ticket/650 ? > >> > >> The way I read that ticket is that writing a boxed value to a mutable array is still O(1), but the garbage collector traverses the whole array during > >> scanning. That could certainly slow down GC cycles, but how does it make array update O(n)? > > > > He means in worst case. Writing once, will cause O(n) during the next GC. Of > > course if you do a lot of updates between two GCs their is no extra penalty. > > So if you make 'k' updates between 2 GCs it costs you k*O(1)+O(n) which is > > still O(n) but practically nicer than k*O(n). > > > Hmm. I'd be careful about conflating algorithmic complexity with memory management issues. By the above reasoning, if I were to run any program using > arrays on a system with a two space garbage collector (which copies all live objects during each GC) I could say the worst case algorithmic complexity was > O(n). That doesn't sound right. > I could take this further and say that in a virtual memory system, there is a chance that the whole heap gets copied to the disk and back between each > array update. I might again say this has O(n) complexity, but it wouldn't be very helpful... Your algorithm is O(1) but the current run-time system can take a time closer to O(n). This could be the case with a two spaces GC or with swapping. -- Nicolas Pouillard http://nicolaspouillard.fr From haskell-beginners at foo.me.uk Sat Nov 21 10:20:30 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Sat Nov 21 09:55:57 2009 Subject: [Haskell-beginners] Type classes and synonyms Message-ID: <200911211520.31063.haskell-beginners@foo.me.uk> Hello all, Quick one for you. I have a list of (,) pairs, and I have defined lots of nice functions for doing various tricks with them. I'd like to define a custom data type which is an instance of 'Num' so I can conveniently do arithmetic on them. (I have written some tools for merging two time series etc...) e.g. t (x,y) = x v (x,y) = y mergeSkip _ [] = [] mergeSkip [] _ = [] mergeSkip (x:xs) (y:ys) | t x == t y = ( t x, (v x, v y) ) : (mergeSkip xs ys) | t x > t y = mergeSkip xs (y:ys) | t x < t y = mergeSkip (x:xs) ys binaryValueFunc f [] = [] binaryValueFunc f ((t,(a,b)):xs) = (t, f a b):binaryValueFunc f xs add xs = binaryValueFunc (+) xs addSkip xs ys = add $ mergeSkip xs ys So addSkip will nicely take two of my time series, merge them by throwing out any pairs which don't have a time stamp that exists in both and then add the values to return a new series. All is well. But how do I make it so that I can use the + operator to add two of them? Well of course, I tried making a custom data type: data Ts a b = Ts [(a,b)] intance Ts Num where But then I have to rewrite all of my functions to pattern match on Ts instead of just the list. Worse, when I am writing recursive functions I have to construct a Ts again for the recursive call. I guess I could make my own 'list-like' datastructure data Ts a b = Empty | Cons ((a,b), Ts) But that seems rather clumsy. So I tried to make 'Ts' a type synonym for [(a,b)] which worked, but then I couldn't declare it an instance of 'Num'. So I guess the question is, is there any way of making a type synonym for a type which I can define as an instance of another class? So I can use my values of the type synonym for functions which expect the 'vanilla' type, but define 'extra' stuff my type synonym can do? Any help or advice greatly appreciated. - Philip From stephen.tetley at gmail.com Sat Nov 21 11:34:33 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sat Nov 21 11:09:49 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911211520.31063.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> Message-ID: <5fdc56d70911210834x615dee00n88341f194b275ac3@mail.gmail.com> Hello Philip If you are wanting element-wise addition with two lists, you can do > instance Num a => Num [a] where > (+) = zipWith (+) > (-) = zipWith (-) > (*) = zipWith (*) > fromInteger = repeat . fromInteger > abs = map abs > signum = map signum Plus as you are representing timestamped values as pairs you would need a Num instance for pairs... > instance (Num a,Num b) => Num (a,b) where > (+) (a,b) (x,y) = (a+x,b+y) > (-) (a,b) (x,y) = (a-x,b-y) > (*) (a,b) (x,y) = (a*x,b*y) > fromInteger a = (fromInteger a, fromInteger a) > abs (a,b) = (abs a, abs b) > signum (a,b) = (signum a, signum b) But... these instances are somewhat arbitrary, and other people would no doubt disagree with their details: For Num on lists there is the problem of uneven length lists. Also fromInteger has a valid definintion as fromInteger a = a : repeat 0 Hence, there aren't instances in the Hierarchical Libraries. Uneven lists can be solved with Streams - see Ralf Hinze's Streams, but then you move to infinite lists... Oh well. http://hackage.haskell.org/packages/archive/hinze-streams/1.0/doc/html/Data-Stream-Hinze-Stream.html As for your question, you can't use a type synonym to define different class instances, you have to use a newtype. Perhaps the best illustration is in Data.Monoid - Numbers have several useful monoids, two of them are: addition (0,+) multiplication (1,*) Data.Monoid uses the Sum newtype wrapper to define the addition monoid and the Product newtype wrapper to define the multiplication monoid. Best wishes Stephen From felipe.lessa at gmail.com Sat Nov 21 11:07:14 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sat Nov 21 11:15:21 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911211520.31063.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> Message-ID: <20091121160714.GB22992@kira.casa> Well, let's begin by making some suggestions to your current code. Below I tell my answer to your question as well. :) On Sat, Nov 21, 2009 at 03:20:30PM +0000, Philip Scott wrote: ] t (x,y) = x ] v (x,y) = y > t = fst > v = snd ] mergeSkip _ [] = [] ] mergeSkip [] _ = [] ] mergeSkip (x:xs) (y:ys) ] | t x == t y = ( t x, (v x, v y) ) : (mergeSkip xs ys) ] | t x > t y = mergeSkip xs (y:ys) ] | t x < t y = mergeSkip (x:xs) ys Using 't' and 'v' isn't very readable, so probably it would be better to just type two more characters and use 'fst' and 'snd': > mergeSkip (x:xs) (y:ys) > | fst x == fst y = (fst x, (snd x, snd y)) : mergeSkip xs ys > | fst x > fst y = mergeSkip xs (y:ys) > | fst x < fst y = mergeSkip (x:xs) ys Or, even better yet, > mergeSkip xss@((xa,xb):xs) yss@((ya,yb):ys) > | xa == ya = (xa, (xb, yb)) : mergeSkip xs ys > | xa > ya = mergeSkip xs yss > | xa < ya = mergeSkip xss ys ] binaryValueFunc f [] = [] ] binaryValueFunc f ((t,(a,b)):xs) = (t, f a b):binaryValueFunc f xs > import Control.Arrow (second) > binaryValueFunc f = map (second $ uncurry f) Now, to your question! ] So addSkip will nicely take two of my time series, merge them by throwing out ] any pairs which don't have a time stamp that exists in both and then add the ] values to return a new series. All is well. But how do I make it so that I can ] use the + operator to add two of them? ] ] Well of course, I tried making a custom data type: ] ] data Ts a b = Ts [(a,b)] ] intance Ts Num where ] ] ] But then I have to rewrite all of my functions to pattern match on Ts instead ] of just the list. Worse, when I am writing recursive functions I have to ] construct a Ts again for the recursive call. I guess I could make my own ] 'list-like' datastructure The common idiom is to write > newtype Ts a b = Ts {unTs :: [(a,b)]} deriving (Eq, Show) We use a newtype just to guarantee that there will be no overhead in using this data type instead of just using a plain list (i.e. at runtime Ts and unTs will be striped out). We name the field as unTs to use it when composing functions (see below). So your definitions above will become: > mergeSkip' (T xs) (T ys) = T (mergeSkip xs ys) if you want to keep the old definition, or > mergeSkip'' (T []) _ = T [] > mergeSkip'' _ (T []) = T [] > mergeSkip'' xss@(T ((xa,xb):xs)) yss@(T ((ya,yb):ys)) > | xa == ya = T $ (xa, (xb, yb)) : mergeSkip'' xs ys > | xa > ya = mergeSkip'' (T xs) yss > | xa < ya = mergeSkip'' xss (T ys) Not that bad, I think. Continuing, let's use unTs: > binaryValueFunc f = Ts . map (second $ uncurry f) . unTs Not bad at all :). However we can just define: > instance Functor (Ts a) where > fmap f = Ts . fmap (second f) . unTs Using the Functor we can rewrite binaryValueFunc to just > binaryValueFunc' :: Functor f => (a -> b -> c) -> f (a,b) -> f c > binaryValueFunc' f = fmap (uncurry f) I've written the type explicitly to show how general we just got. However, I guess the following function is more useful for the Num instance: > liftBin f xs ys = fmap (uncurry f) $ mergeSkip xs ys Now our Num instance is just > instance (Ord a, Num b) => Num (Ts a b) where > (+) = liftBin (+) > (-) = liftBin (-) > (*) = liftBin (*) > abs = fmap abs > negate = fmap negate > signum = fmap signum > fromInteger = error "I don't know how you would define this :)" I hope that helps! (Note that if you can implement the Applicative type class for your Ts data type and then get liftBin = liftA2 for free.) -- Felipe. From jon at ffconsultancy.com Sat Nov 21 13:02:33 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Sat Nov 21 11:24:38 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <5816568E-3AFA-4E23-AAE4-7ACC60B43AEA@anu.edu.au> References: <1258798176-sup-2681@peray> <5816568E-3AFA-4E23-AAE4-7ACC60B43AEA@anu.edu.au> Message-ID: <200911211802.33494.jon@ffconsultancy.com> On Saturday 21 November 2009 11:56:09 Ben Lippmeier wrote: > Hmm. I'd be careful about conflating algorithmic complexity with memory > management issues. No need. Just look at how badly the performance scales for Haskell vs other languages. For example, inserting 1-16 million floating point key/values into a hash table: Haskell OCaml F# 1M: 3.198s 1.0x 1.129s 1.0x 0.080s 1.0x 2M: 8.498s 2.7x 2.313s 2.0x 0.138s 1.7x 4M: 25.697s 8.0x 4.567s 4.0x 0.281s 3.5x 8M: 97.994s 30.6x 10.450s 9.3x 0.637s 8.0x 16M: 388.080s 121.4x 23.261s 20.6x 1.338s 16.7x Note that Haskell is 290x slower than F# on that last test. In practice, you would turn to a purely functional dictionary in Haskell based upon balanced binary trees in order to work around this long-standing bug in the GC but those trees incur O(log n) indirections and typically run orders of magnitude slower than a decent hash table. Suffice to say, Haskell is nowhere near being in the ballpark of C++'s performance for basic functionality like dictionaries and sorting. > By the above reasoning, if I were to run any program > using arrays on a system with a two space garbage collector (which copies > all live objects during each GC) I could say the worst case algorithmic > complexity was O(n). That doesn't sound right. Can you write a program that demonstrates this effect as I did? > I could take this further and say that in a virtual memory system, there is > a chance that the whole heap gets copied to the disk and back between each > array update. Can you write a program that demonstrates this effect as I did? -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From haskell-beginners at foo.me.uk Sat Nov 21 12:39:20 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Sat Nov 21 12:14:50 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <5fdc56d70911210834x615dee00n88341f194b275ac3@mail.gmail.com> References: <200911211520.31063.haskell-beginners@foo.me.uk> <5fdc56d70911210834x615dee00n88341f194b275ac3@mail.gmail.com> Message-ID: <200911211739.20689.haskell-beginners@foo.me.uk> Hi Stephan, > > instance Num a => Num [a] where > > (+) = zipWith (+) > > (-) = zipWith (-) > > (*) = zipWith (*) > > fromInteger = repeat . fromInteger > > abs = map abs > > signum = map signum Oooh I had no idea you could do that with 'instance' I merge my lists into a list of pairs before I do anything with them so unevenness isn't a problem; I was just trying t convince haskell that I could use nice operators like '+' on my derived type. Thank you very much for your reply; between that and Felipe's I have enough to keep me busy all evening digesting the new toys you have demonstrated :) - Philip From haskell-beginners at foo.me.uk Sat Nov 21 12:57:45 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Sat Nov 21 12:33:16 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <20091121160714.GB22992@kira.casa> References: <200911211520.31063.haskell-beginners@foo.me.uk> <20091121160714.GB22992@kira.casa> Message-ID: <200911211757.45857.haskell-beginners@foo.me.uk> > Well, let's begin by making some suggestions to your current > code. Below I tell my answer to your question as well. :) What a fantastic and comprehensive answer, thank you! I now need to sit down and digest it. There are so many little clever tricks you can do with Haskell, is there a collection of them somewhere? If you want to collect your obligatory cookie and are ever in and around Cambridge UK let me know :) - Philip From stephen.tetley at gmail.com Sat Nov 21 13:13:02 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sat Nov 21 12:48:18 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911211739.20689.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> <5fdc56d70911210834x615dee00n88341f194b275ac3@mail.gmail.com> <200911211739.20689.haskell-beginners@foo.me.uk> Message-ID: <5fdc56d70911211013k3db1d47cl904d58f7b15a26a4@mail.gmail.com> Hi Philip Aesthetics, taste, sanity, whatever... strongly suggest not doing it of course. But there is (probably) little harm in trying it. Best wishes Stephen 2009/11/21 Philip Scott : > > Oooh I had no idea you could do that with 'instance' > > > instance Num a => Num [a] where > > (+) = zipWith (+) > > (-) = zipWith (-) > > (*) = zipWith (*) > > fromInteger = repeat . fromInteger > > abs = map abs > > signum = map signum From felipe.lessa at gmail.com Sat Nov 21 13:19:34 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sat Nov 21 12:55:02 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911211757.45857.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> <20091121160714.GB22992@kira.casa> <200911211757.45857.haskell-beginners@foo.me.uk> Message-ID: <20091121181934.GB11728@kira.casa> On Sat, Nov 21, 2009 at 05:57:45PM +0000, Philip Scott wrote: > What a fantastic and comprehensive answer, thank you! No problem. :) > I now need to sit down and digest it. There are so many little clever tricks > you can do with Haskell, is there a collection of them somewhere? Lately people have been suggesting the Typeclassopedia[1] as a good place for begginners. It's a good reading and I recommend it, I just don't know if you'll find everything needed for my answer there. In general, however, you just need practice. Go code! =) [1] http://haskell.org/sitewiki/images/8/85/TMR-Issue13.pdf > If you want to collect your obligatory cookie and are ever in and around > Cambridge UK let me know :) Too bad I'm 8837 km away from Cambridge according to Alpha =(... Cheers, -- Felipe. From nathanmholden at gmail.com Sat Nov 21 13:57:21 2009 From: nathanmholden at gmail.com (Nathan M. Holden) Date: Sat Nov 21 13:32:39 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <20091121175503.8A44E3247E8@www.haskell.org> References: <20091121175503.8A44E3247E8@www.haskell.org> Message-ID: <200911211357.21870.nathanmholden@gmail.com> I'm not a Haskell expert-- in fact, I'm a beginner, and that's why I'm here, but I read your blog post on the subject of this hash table program, and it seems to me from reading the comments in reply that you're just here trolling, because you're using an algorithm that is fundamentally not purely functional, and of course that's going to be slower, just like asking Joel Zumaya to pitch left handed. If you were being honest about your complaint, you'd make an apples-to-apples comparison, and a number of commenters on your blog have proposed implementations that perform much better than your example. Sorry if I'm just being a jerk, Nathan M. Holden, Haskell Beginner On Saturday 21 November 2009 12:55:03 pm beginners-request@haskell.org wrote: > Message: 4 > Date: Sat, 21 Nov 2009 18:02:33 +0000 > From: Jon Harrop > Subject: Re: [Haskell-beginners] Re: Is Haskell for me? > To: Ben Lippmeier > Cc: beginners > Message-ID: <200911211802.33494.jon@ffconsultancy.com> > Content-Type: text/plain; charset="iso-8859-1" > > On Saturday 21 November 2009 11:56:09 Ben Lippmeier wrote: > > Hmm. I'd be careful about conflating algorithmic complexity with memory > > management issues. > > No need. Just look at how badly the performance scales for Haskell vs other > languages. For example, inserting 1-16 million floating point key/values > into a hash table: > > Haskell OCaml F# > 1M: 3.198s 1.0x 1.129s 1.0x 0.080s 1.0x > 2M: 8.498s 2.7x 2.313s 2.0x 0.138s 1.7x > 4M: 25.697s 8.0x 4.567s 4.0x 0.281s 3.5x > 8M: 97.994s 30.6x 10.450s 9.3x 0.637s 8.0x > 16M: 388.080s 121.4x 23.261s 20.6x 1.338s 16.7x > > Note that Haskell is 290x slower than F# on that last test. > > In practice, you would turn to a purely functional dictionary in Haskell > based upon balanced binary trees in order to work around this > long-standing bug in the GC but those trees incur O(log n) indirections > and typically run orders of magnitude slower than a decent hash table. > > Suffice to say, Haskell is nowhere near being in the ballpark of C++'s > performance for basic functionality like dictionaries and sorting. > > > By the above reasoning, if I were to run any program > > using arrays on a system with a two space garbage collector (which copies > > all live objects during each GC) I could say the worst case algorithmic > > complexity was O(n). That doesn't sound right. > > Can you write a program that demonstrates this effect as I did? > > > I could take this further and say that in a virtual memory system, there > > is a chance that the whole heap gets copied to the disk and back between > > each array update. > > Can you write a program that demonstrates this effect as I did? From jon at ffconsultancy.com Sat Nov 21 15:52:30 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Sat Nov 21 14:14:36 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <200911211357.21870.nathanmholden@gmail.com> References: <20091121175503.8A44E3247E8@www.haskell.org> <200911211357.21870.nathanmholden@gmail.com> Message-ID: <200911212052.30615.jon@ffconsultancy.com> On Saturday 21 November 2009 18:57:21 you wrote: > I'm not a Haskell expert-- in fact, I'm a beginner, and that's why I'm > here, but I read your blog post on the subject of this hash table program, > and it seems to me from reading the comments in reply that you're just here > trolling, because you're using an algorithm that is fundamentally not > purely functional, and of course that's going to be slower, just like > asking Joel Zumaya to pitch left handed. > > If you were being honest about your complaint, you'd make an > apples-to-apples comparison, and a number of commenters on your blog have > proposed implementations that perform much better than your example. > > Sorry if I'm just being a jerk, Not at all, that is a perfectly reasonable concern but I did already try to address it in my previous post: > > In practice, you would turn to a purely functional dictionary in Haskell > > based upon balanced binary trees in order to work around this > > long-standing bug in the GC but those trees incur O(log n) indirections > > and typically run orders of magnitude slower than a decent hash table. For example, the following Haskell program builds a purely functional Data.Map: module Main where import Prelude hiding (lookup) import Data.Map (empty, insert, lookup, size) n = 1000000 build m 0 = m build m n = build (insert x (1.0 / x) m) (n-1) where x = fromIntegral n :: Double main = do let m = build empty n (Just v) = lookup 100 m print $ size m print v Running this program with different "n" gives: Data.Map 1M: 2.797s 1.0x 2M: 6.090s 2.2x 4M: 14.226s 5.1x 8M: 28.449s 10.2x 16M: 83.171s 29.7x This is several times faster than Haskell's Data.Hashtable (because of the long-standing bug in their GC that I described) and is scaling better. However, if you compare with the timings I gave before: Data.Hashtable OCaml F# 1M: 3.198s 1.0x 1.129s 1.0x 0.080s 1.0x 2M: 8.498s 2.7x 2.313s 2.0x 0.138s 1.7x 4M: 25.697s 8.0x 4.567s 4.0x 0.281s 3.5x 8M: 97.994s 30.6x 10.450s 9.3x 0.637s 8.0x 16M: 388.080s 121.4x 23.261s 20.6x 1.338s 16.7x you'll see that the absolute performance of this idiomatic Haskell solution is still absolutely awful: consistently about 50x slower than the F#. This is also true in the context of sorting: Haskell's standard library routines for sorting are orders of magnitude slower than those found in most other compiled languages. Suffice to say, idiomatic Haskell is also nowhere near being in the same ballpark as C++ with respect to performance. Realistically, with enough expertise you should be able to optimize most of your Haskell programs to beat Python's performance but there are some important cases where you will not even be able to do that. -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From haskell-beginners at foo.me.uk Sat Nov 21 15:33:28 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Sat Nov 21 15:08:51 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <20091121181934.GB11728@kira.casa> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> Message-ID: <200911212033.29004.haskell-beginners@foo.me.uk> Hi ho, > In general, however, you just need practice. Go code! =) Righto, I am getting stuck in with that. One last question; I've been trying to read up on Arrows and my mind is being boggled. Via experiment, I have worked out what 'second' was doing (the documentation is useless unless you already understand a lot of stuff I clearly don't) For the other newbies, 'second' takes a function and a tuple, it applies the function to the second thing in your tuple and returns a tuple with the first value unchanged, and the result of applying 'f' to the second: > second (\x -> "fish") (10,20) (10,"fish") What I am struggling to understand is what on earth the type signature means: :t second second :: (Arrow a) => a b c -> a (d, b) (d, c) How can (\x -> "fish") be an 'a b c' when it really looks like this: :t (\x->"fish") (\x->"fish") :: t -> [Char] And I am pretty sure I never made any Arrpws... I feel I am on the verge of understanding something deep and fundamentally philosophical about the typesystem but I can't quite bend my mind around to it :) All the best, Philip From chaddai.fouche at gmail.com Sat Nov 21 15:51:06 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Sat Nov 21 15:26:20 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911212033.29004.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> Message-ID: On Sat, Nov 21, 2009 at 9:33 PM, Philip Scott wrote: > For the other newbies, 'second' takes a function and a tuple, it applies the > function to the second thing in your tuple and returns a tuple with the first > value unchanged, and the result of applying 'f' to the second: That's what it does on a specific arrow, though generally that's the idea. > What I am struggling to understand is what on earth the type signature means: > > :t second > second :: (Arrow a) => a b c -> a (d, b) (d, c) > > How can (\x -> "fish") be an 'a b c' when it really looks like this: > > :t (\x->"fish") > (\x->"fish") :: t -> [Char] Right, but you must understand that (->) is a type constructor, just like Maybe or Either or your Ts. It takes two types parameter and return a function type. So "a -> b" is the infix syntax, but you could write that "(->) a b" just like you can write "3 + 5" as "(+) 3 5". Once you've done that on your function you get "(->) t Char" which looks a bit more like "a b c"... The final piece is that (->) is an Arrow, the most basic one but still an Arrow, so if you replace a by (->) in the type of second, you get : second :: (->) b c -> (->) (d, b) (d, c) which is just second :: (b -> c) -> (d, b) -> (d, c) which corresponds exactly to the action of second you described (that's the only function that could have this type, except bottom of course). -- Jeda? From daniel.is.fischer at web.de Sat Nov 21 15:51:42 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Nov 21 15:28:26 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911212033.29004.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> Message-ID: <200911212151.43482.daniel.is.fischer@web.de> Am Samstag 21 November 2009 21:33:28 schrieb Philip Scott: > Hi ho, > > > In general, however, you just need practice. Go code! =) > > Righto, I am getting stuck in with that. One last question; I've been > trying to read up on Arrows and my mind is being boggled. Via experiment, I > have worked out what 'second' was doing (the documentation is useless > unless you already understand a lot of stuff I clearly don't) > > For the other newbies, 'second' takes a function and a tuple, it applies > the function to the second thing in your tuple and returns a tuple with the > first > > value unchanged, and the result of applying 'f' to the second: > > second (\x -> "fish") (10,20) > > (10,"fish") > > What I am struggling to understand is what on earth the type signature means: > :t second > > second :: (Arrow a) => a b c -> a (d, b) (d, c) > > How can (\x -> "fish") be an 'a b c' when it really looks like this: > :t (\x->"fish") > (\x->"fish") :: t -> [Char] a is a type variable (restricted to be a member of the Arrow class). Now the type ghci reports for (\x -> "fish") is printed in infix form, in prefix form, it reads :t (\x -> "fish") (\x -> "fish") :: (->) t [Char] so we find a = (->) b = t c = [Char] and you're using the most widespread instance of Arrow, (->). Arrows are a generalisation of functions. Until you're more familiar with Arrows, I suggest replacing any (Arrow a) with (->) in the type signatures to understand what things mean in the familiar case. Next in line would probably be Kleisli arrows (Monad m => a -> m b; it's wrapped in a newtype for Control.Arrow), break at any level of abstraction you want and return later. > > And I am pretty sure I never made any Arrpws... There are a few others have made for you to use :) > > I feel I am on the verge of understanding something deep and fundamentally > philosophical about the typesystem but I can't quite bend my mind around to > it > > :) > > All the best, > > Philip From haskell-beginners at foo.me.uk Sat Nov 21 16:07:38 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Sat Nov 21 15:43:11 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911212033.29004.haskell-beginners@foo.me.uk> Message-ID: <200911212107.38396.haskell-beginners@foo.me.uk> > The final piece is that (->) is an Arrow, the most basic one but still > an Arrow, so if you replace a by (->) in the type of second, you get : > second :: (->) b c -> (->) (d, b) (d, c) > which is just > second :: (b -> c) -> (d, b) -> (d, c) Ahh I see, very clever! There is method to the madness after all; I should never have doubted you Haskell. Thank you for taking the time to explain that :) Do you know of any good discussions/tutorials on Arrows? I've only managed to find little snippets here and there http://www.haskell.org/arrows/ Doesn't have a lot of detail and http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html ..would probably be useful once I actually understand what is going on but right now I think a slap in the face with a big wet fish might help me more ;) - Philip From felipe.lessa at gmail.com Sat Nov 21 16:08:33 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sat Nov 21 15:43:53 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911212033.29004.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> Message-ID: <20091121210833.GA656@kira.casa> On Sat, Nov 21, 2009 at 08:33:28PM +0000, Philip Scott wrote: > Righto, I am getting stuck in with that. One last question; I've been trying > to read up on Arrows and my mind is being boggled. Via experiment, I have > worked out what 'second' was doing (the documentation is useless unless you > already understand a lot of stuff I clearly don't) > > For the other newbies, 'second' takes a function and a tuple, it applies the > function to the second thing in your tuple and returns a tuple with the first > value unchanged, and the result of applying 'f' to the second: > > > second (\x -> "fish") (10,20) > (10,"fish") > > What I am struggling to understand is what on earth the type signature means: > > :t second > second :: (Arrow a) => a b c -> a (d, b) (d, c) > > How can (\x -> "fish") be an 'a b c' when it really looks like this: > > :t (\x->"fish") > (\x->"fish") :: t -> [Char] > > And I am pretty sure I never made any Arrpws... > > I feel I am on the verge of understanding something deep and fundamentally > philosophical about the typesystem but I can't quite bend my mind around to it > :) The problem you're facing is that you have to think of the arrow operator (->) as a type constructor. IOW, to unify : a b c with t -> [Char] you have the following "assignments": a ~ (->) b ~ t c ~ [Char] In another other words, t -> [Char] is the same as (->) t [Char] Now it's easy to see whats happening. Note that (->) is an instance to Arrow, in GHCi: Prelude Control.Arrow> :i Arrow class (Control.Category.Category a) => Arrow a where arr :: (b -> c) -> a b c first :: a b c -> a (b, d) (c, d) second :: a b c -> a (d, b) (d, c) (***) :: a b c -> a b' c' -> a (b, b') (c, c') (&&&) :: a b c -> a b c' -> a b (c, c') -- Defined in Control.Arrow instance Arrow (->) -- Defined in Control.Arrow <<< HERE <<< instance (Monad m) => Arrow (Kleisli m) -- Defined in Control.Arrow Specializing those types to Arrow (->) and using the common infix notation we have that: arr :: (b -> c) -> (b -> c) first :: (b -> c) -> ((b, d) -> (c, d)) second :: (b -> c) -> ((d, b) -> (d, c)) (***) :: (b -> c) -> (b' -> c') -> ((b, b') -> (c, c')) (&&&) :: (b -> c) -> (b' -> c') -> (b -> (c, c')) Note that 'arr = id'. That's why we may use all Arrow functions on, err, plain functions without having wrap everything with 'arr' (as you would with any other arrow). It's a good exercise to try to reproduce the definition of the Arrow (->) instance by defining the functions above. Most definitions, if not all, are just the corresponding free theorems (meaning roughly that the definition follows from the type because that's the only definition that doesn't have undefined's). HTH! -- Felipe. From haskell at colquitt.org Sat Nov 21 16:13:49 2009 From: haskell at colquitt.org (John Dorsey) Date: Sat Nov 21 15:49:03 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> Message-ID: <20091121211349.GF23495@colquitt.org> Chadda? Fouch? wrote: > second :: (b -> c) -> (d, b) -> (d, c) > which corresponds exactly to the action of second you described > (that's the only function that could have this type, except bottom of > course). Nonsense! There are several perfectly good Haskell functions with that type. I count seven: second :: (b -> c) -> (d, b) -> (d, c) second = Control.Arrow.second second = undefined second = const undefined second = const (const undefined) second = const (const (undefined,undefined)) second f (d,b) = (undefined, f b) second f (d,b) = (d, undefined) Why I'm stickling on that point on the beginners list, however, is a mystery. I'll go write a more useful response, in contrition. John From haskell at colquitt.org Sat Nov 21 16:23:26 2009 From: haskell at colquitt.org (John Dorsey) Date: Sat Nov 21 15:58:41 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911211739.20689.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> <5fdc56d70911210834x615dee00n88341f194b275ac3@mail.gmail.com> <200911211739.20689.haskell-beginners@foo.me.uk> Message-ID: <20091121212326.GG23495@colquitt.org> Philip, > I merge my lists into a list of pairs before I do anything with them so > unevenness isn't a problem; I was just trying t convince haskell that I could > use nice operators like '+' on my derived type. There's another way to use nice operators like '+', in cases where the type you're using it with just doesn't make sense as an instance of Class Num. (I think there's an argument that your [(date,value)] type isn't a number and shouldn't be a Num, but I'm not going to go there.) Every module can have its own definition for each name, such as the operator (+). So in your module (eg. module Main, or module DateValueSeries), you can go ahead and define your own (+). The major caveat is making sure you don't conflict with the default (+), which lives in module Prelude, which is normally automatically brought into scope. So you could do this: -- file DateValueSeries.hs module DateValueSeries where import Prelude hiding ((+)) (+) :: [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)] (+) = addSkip addSkip = ... -- file main.hs import Prelude hiding ((+)) import DateValueSeries dvlist1 = [(0,100)] dvlist2 = ... dvlist3 = dvlist1 + dvlist2 The code is incomplete and untested, of course. The basic idea is that you can use (+) for something that isn't exactly addition (although you're choosing that name because it's clearly related to addition). Unlike the examples using Class Num your (+) has nothing to do with the normal (+); it just has the same name. John From chaddai.fouche at gmail.com Sat Nov 21 16:23:38 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Sat Nov 21 15:58:52 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <20091121211349.GF23495@colquitt.org> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> <20091121211349.GF23495@colquitt.org> Message-ID: On Sat, Nov 21, 2009 at 10:13 PM, John Dorsey wrote: > Chadda? Fouch? wrote: > >> second :: (b -> c) -> (d, b) -> (d, c) >> which corresponds exactly to the action of second you described >> (that's the only function that could have this type, except bottom of >> course). > > Nonsense! ?There are several perfectly good Haskell functions with that > type. ?I count seven: > > second :: (b -> c) -> (d, b) -> (d, c) > second = Control.Arrow.second > second = undefined > second = const undefined > second = const (const undefined) > second = const (const (undefined,undefined)) > second f (d,b) = (undefined, f b) > second f (d,b) = (d, undefined) Right... Let's just say functions that may be evaluated to normal form if their parameters can be evaluated to normal form. Nitpicker !! :P -- Jeda? From daniel.is.fischer at web.de Sat Nov 21 16:27:20 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Nov 21 16:06:45 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <20091121211349.GF23495@colquitt.org> References: <200911211520.31063.haskell-beginners@foo.me.uk> <20091121211349.GF23495@colquitt.org> Message-ID: <200911212227.21470.daniel.is.fischer@web.de> Am Samstag 21 November 2009 22:13:49 schrieb John Dorsey: > Chadda? Fouch? wrote: > > second :: (b -> c) -> (d, b) -> (d, c) > > which corresponds exactly to the action of second you described > > (that's the only function that could have this type, except bottom of > > course). > > Nonsense! There are several perfectly good Haskell functions with that > type. I count seven: > > second :: (b -> c) -> (d, b) -> (d, c) > second = Control.Arrow.second > second = undefined > second = const undefined > second = const (const undefined) > second = const (const (undefined,undefined)) > second f (d,b) = (undefined, f b) > second f (d,b) = (d, undefined) I don't see second f (d,b) = (undefined, f undefined) second f (d,b) = (d, f undefined) in there. > > Why I'm stickling on that point on the beginners list, however, is a > mystery. I'll go write a more useful response, in contrition. > > John From haskell at colquitt.org Sat Nov 21 16:44:50 2009 From: haskell at colquitt.org (John Dorsey) Date: Sat Nov 21 16:20:04 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911212227.21470.daniel.is.fischer@web.de> References: <200911211520.31063.haskell-beginners@foo.me.uk> <20091121211349.GF23495@colquitt.org> <200911212227.21470.daniel.is.fischer@web.de> Message-ID: <20091121214450.GN6929@colquitt.org> Daniel Fischer re-nitpicked: > > I don't see > > second f (d,b) = (undefined, f undefined) > second f (d,b) = (d, f undefined) > > in there. Brilliant! I thought I might have missed something, hence "I count seven" instead of "there are seven". John From haskell-beginners at foo.me.uk Sat Nov 21 17:25:35 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Sat Nov 21 17:01:17 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <20091121212326.GG23495@colquitt.org> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211739.20689.haskell-beginners@foo.me.uk> <20091121212326.GG23495@colquitt.org> Message-ID: <200911212225.35757.haskell-beginners@foo.me.uk> Thanks John, > Every module can have its own definition for each name, such as the > operator (+). So in your module (eg. module Main, or module > DateValueSeries), you can go ahead and define your own (+). The major > caveat is making sure you don't conflict with the default (+), which lives > in module Prelude, which is normally automatically brought into scope. That actually quite nicely solves the problem... it feels almost a little too easy, after spending the evening getting my mind wrapped up with Arrows :) Thank you very much for your help. - Philip From ml at isaac.cedarswampstudios.org Sat Nov 21 17:43:29 2009 From: ml at isaac.cedarswampstudios.org (Isaac Dupree) Date: Sat Nov 21 17:19:15 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911212225.35757.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211739.20689.haskell-beginners@foo.me.uk> <20091121212326.GG23495@colquitt.org> <200911212225.35757.haskell-beginners@foo.me.uk> Message-ID: <4B086D11.5080600@isaac.cedarswampstudios.org> Philip Scott wrote: > Thanks John, > >> Every module can have its own definition for each name, such as the >> operator (+). So in your module (eg. module Main, or module >> DateValueSeries), you can go ahead and define your own (+). The major >> caveat is making sure you don't conflict with the default (+), which lives >> in module Prelude, which is normally automatically brought into scope. > > That actually quite nicely solves the problem... it feels almost a little too > easy, after spending the evening getting my mind wrapped up with Arrows :) why has no one mentioned: you most likely don't need to understand Arrows? I'm pretty good with Haskell, and Arrows are still somewhat confusing to me. Why? Most problems I've worked with in Haskell have had more-idiomatic solutions than Arrows. (examples include: Monad; Functor; Applicative; just plain functions; plain old lack of type-class abstraction.) It's not so easy or useful to understand any abstraction/class without using at least two or three useful examples/instances of it first. -Isaac From felipe.lessa at gmail.com Sat Nov 21 18:07:35 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sat Nov 21 17:42:54 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <4B086D11.5080600@isaac.cedarswampstudios.org> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211739.20689.haskell-beginners@foo.me.uk> <20091121212326.GG23495@colquitt.org> <200911212225.35757.haskell-beginners@foo.me.uk> <4B086D11.5080600@isaac.cedarswampstudios.org> Message-ID: <20091121230735.GA20701@kira.casa> On Sat, Nov 21, 2009 at 05:43:29PM -0500, Isaac Dupree wrote: > why has no one mentioned: you most likely don't need to understand > Arrows? I'm pretty good with Haskell, and Arrows are still somewhat > confusing to me. Why? Most problems I've worked with in Haskell > have had more-idiomatic solutions than Arrows. (examples include: > Monad; Functor; Applicative; just plain functions; plain old lack of > type-class abstraction.) It's not so easy or useful to understand > any abstraction/class without using at least two or three useful > examples/instances of it first. In defence of my solution, I haven't really used the power of the arrows. The "problem" is that the quite useful functions first, second, (***) and (&&&) are defined within Control.Arrow. Cheers, :) -- Felipe. From tonymorris at gmail.com Sat Nov 21 18:11:21 2009 From: tonymorris at gmail.com (Tony Morris) Date: Sat Nov 21 17:46:17 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <4B086D11.5080600@isaac.cedarswampstudios.org> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211739.20689.haskell-beginners@foo.me.uk> <20091121212326.GG23495@colquitt.org> <200911212225.35757.haskell-beginners@foo.me.uk> <4B086D11.5080600@isaac.cedarswampstudios.org> Message-ID: <4B087399.1070408@gmail.com> If you don't yet understand Arrows, then what compels you to conclude that there are more idiomatic solutions (than what you don't yet understand)? Just sayin' Isaac Dupree wrote: > Philip Scott wrote: >> Thanks John, >> >>> Every module can have its own definition for each name, such as the >>> operator (+). So in your module (eg. module Main, or module >>> DateValueSeries), you can go ahead and define your own (+). The major >>> caveat is making sure you don't conflict with the default (+), >>> which lives >>> in module Prelude, which is normally automatically brought into scope. >> >> That actually quite nicely solves the problem... it feels almost a >> little too easy, after spending the evening getting my mind wrapped >> up with Arrows :) > > why has no one mentioned: you most likely don't need to understand > Arrows? I'm pretty good with Haskell, and Arrows are still somewhat > confusing to me. Why? Most problems I've worked with in Haskell have > had more-idiomatic solutions than Arrows. (examples include: Monad; > Functor; Applicative; just plain functions; plain old lack of > type-class abstraction.) It's not so easy or useful to understand any > abstraction/class without using at least two or three useful > examples/instances of it first. > > -Isaac > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Tony Morris http://tmorris.net/ From ben.lippmeier at anu.edu.au Sat Nov 21 18:52:51 2009 From: ben.lippmeier at anu.edu.au (Ben Lippmeier) Date: Sat Nov 21 18:28:17 2009 Subject: [Haskell-beginners] Re: Is Haskell for me? In-Reply-To: <200911211802.33494.jon@ffconsultancy.com> References: <1258798176-sup-2681@peray> <5816568E-3AFA-4E23-AAE4-7ACC60B43AEA@anu.edu.au> <200911211802.33494.jon@ffconsultancy.com> Message-ID: On 22/11/2009, at 5:02 , Jon Harrop wrote: > >> By the above reasoning, if I were to run any program >> using arrays on a system with a two space garbage collector (which copies >> all live objects during each GC) I could say the worst case algorithmic >> complexity was O(n). That doesn't sound right. > > Can you write a program that demonstrates this effect as I did? I believe your numbers, but I don't have a F# install to test against ATM. > Suffice to say, Haskell is nowhere near being in the ballpark of C++'s > performance for basic functionality like dictionaries and sorting. Sorry, I wasn't trying to start a pissing match. I just wanted to know what the issue was so I could avoid it in my own programs. Thanks! Ben. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091121/76b2abd0/attachment-0001.html From ml at isaac.cedarswampstudios.org Sat Nov 21 23:18:22 2009 From: ml at isaac.cedarswampstudios.org (Isaac Dupree) Date: Sat Nov 21 22:54:11 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <4B087399.1070408@gmail.com> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211739.20689.haskell-beginners@foo.me.uk> <20091121212326.GG23495@colquitt.org> <200911212225.35757.haskell-beginners@foo.me.uk> <4B086D11.5080600@isaac.cedarswampstudios.org> <4B087399.1070408@gmail.com> Message-ID: <4B08BB8E.3060700@isaac.cedarswampstudios.org> Sorry to take offense :-) maybe I was being too modest? What leads me to conclude that is... Reading several papers about uses of Arrows and Applicative and Monads for parsing and FRP, being on the mailing-lists for a few years listening to debates and people struggling with bits of code, getting a sense of the history of each abstraction and of how people who use that abstraction daily relate to it. (let's see if I can name names... Ross Paterson, Conor McBride, maybe Simon Peyton-Jones..). Experimenting a bit with my own code. Having a vague sense, through coding Haskell quite a bit, how much it's possible to condense a piece of code. It is not a conclusion of compulsion, just that I haven't seen it done better. It seems Arrows are a necessary abstraction for a couple very particular world-views/paradigms, and don't fit very well with a lot of other stuff. So far, I haven't used FRP for anything major, and I've done most parsing with Parsec (monad-based) and Happy (hmm, it's a preprocessor). Since I don't have lots of experience with the examples, I didn't want to claim to understand the abstraction(class) very well. :-) -Isaac Tony Morris wrote: > If you don't yet understand Arrows, then what compels you to conclude > that there are more idiomatic solutions (than what you don't yet > understand)? > Just sayin' > > Isaac Dupree wrote: >> Philip Scott wrote: >>> Thanks John, >>> >>>> Every module can have its own definition for each name, such as the >>>> operator (+). So in your module (eg. module Main, or module >>>> DateValueSeries), you can go ahead and define your own (+). The major >>>> caveat is making sure you don't conflict with the default (+), >>>> which lives >>>> in module Prelude, which is normally automatically brought into scope. >>> That actually quite nicely solves the problem... it feels almost a >>> little too easy, after spending the evening getting my mind wrapped >>> up with Arrows :) >> why has no one mentioned: you most likely don't need to understand >> Arrows? I'm pretty good with Haskell, and Arrows are still somewhat >> confusing to me. Why? Most problems I've worked with in Haskell have >> had more-idiomatic solutions than Arrows. (examples include: Monad; >> Functor; Applicative; just plain functions; plain old lack of >> type-class abstraction.) It's not so easy or useful to understand any >> abstraction/class without using at least two or three useful >> examples/instances of it first. >> >> -Isaac >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > From mpm at alumni.caltech.edu Sun Nov 22 02:51:38 2009 From: mpm at alumni.caltech.edu (Michael P. Mossey) Date: Sun Nov 22 02:26:59 2009 Subject: [Haskell-beginners] reverse flow . Message-ID: <4B08ED8A.7000400@alumni.caltech.edu> Can I get some recommendations on defining a function composition operator that flows in the reverse direction? Thanks, Mike From mpm at alumni.caltech.edu Sun Nov 22 03:25:55 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sun Nov 22 03:01:24 2009 Subject: [Haskell-beginners] reverse flow . In-Reply-To: <4B08ED8A.7000400@alumni.caltech.edu> References: <4B08ED8A.7000400@alumni.caltech.edu> Message-ID: <4B08F593.3020706@alumni.caltech.edu> To clarify, I'm interested in - what symbols you would choose - how to set the left/right associativity and precedence Michael P. Mossey wrote: > Can I get some recommendations on defining a function composition > operator that flows in the reverse direction? > > Thanks, > Mike > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From tonymorris at gmail.com Sun Nov 22 03:47:34 2009 From: tonymorris at gmail.com (Tony Morris) Date: Sun Nov 22 03:22:27 2009 Subject: [Haskell-beginners] reverse flow . In-Reply-To: <4B08F593.3020706@alumni.caltech.edu> References: <4B08ED8A.7000400@alumni.caltech.edu> <4B08F593.3020706@alumni.caltech.edu> Message-ID: <4B08FAA6.6030203@gmail.com> There is already one. Prelude Control.Arrow> :type (>>>) (>>>) :: (Control.Category.Category cat) => cat a b -> cat b c -> cat a c Michael Mossey wrote: > To clarify, I'm interested in > > - what symbols you would choose > - how to set the left/right associativity and precedence > > Michael P. Mossey wrote: >> Can I get some recommendations on defining a function composition >> operator that flows in the reverse direction? >> >> Thanks, >> Mike >> >> _______________________________________________ >> 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 > -- Tony Morris http://tmorris.net/ From nicolas.pouillard at gmail.com Sun Nov 22 03:49:31 2009 From: nicolas.pouillard at gmail.com (Nicolas Pouillard) Date: Sun Nov 22 03:24:45 2009 Subject: [Haskell-beginners] reverse flow . In-Reply-To: <4B08ED8A.7000400@alumni.caltech.edu> References: <4B08ED8A.7000400@alumni.caltech.edu> Message-ID: <1258879747-sup-320@peray> Excerpts from Michael P. Mossey's message of Sun Nov 22 08:51:38 +0100 2009: > Can I get some recommendations on defining a function composition > operator that flows in the reverse direction? There is (>>>) in Control.Category. -- Nicolas Pouillard http://nicolaspouillard.fr From mpm at alumni.caltech.edu Sun Nov 22 05:25:45 2009 From: mpm at alumni.caltech.edu (Michael P. Mossey) Date: Sun Nov 22 05:01:04 2009 Subject: [Haskell-beginners] combinatorial Message-ID: <4B0911A9.8030208@alumni.caltech.edu> I'm trying to write a combinatorial search algorithm with evaluation, and kind of stuck. Not sure how to do this. I'm constructing a musical phrase, which is a list of MidiPitch: [MidiPitch] I have an evaluation function that determines the fitness of any given phrase: eval :: [MidiPitch] -> Maybe Float This returns Nothing if the phrase is completely unacceptable. The idea is to build up a phrase one midi pitch at a time, choosing all possible next pitches (notes) from a range: next pitch comes from: [10..90] Most of the pitches will result in a phrase that evaluates to Nothing, so the combinatoral "explosion" will be limited. I'd like to write a function that constructs a phrase of length n, and in fact will have to return a list of all phrases that have equal scores of the maximum. -- -> -> -> -- coolFunc :: Int -> MidiPitch -> ([MidiPitch] -> Maybe Float) -> [[MidiPitch]] I am stuck on how to write this. thanks, Mike From stephen.tetley at gmail.com Sun Nov 22 06:31:05 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sun Nov 22 06:06:18 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <4B08BB8E.3060700@isaac.cedarswampstudios.org> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211739.20689.haskell-beginners@foo.me.uk> <20091121212326.GG23495@colquitt.org> <200911212225.35757.haskell-beginners@foo.me.uk> <4B086D11.5080600@isaac.cedarswampstudios.org> <4B087399.1070408@gmail.com> <4B08BB8E.3060700@isaac.cedarswampstudios.org> Message-ID: <5fdc56d70911220331r269340baj114bcf81af7923ca@mail.gmail.com> 2009/11/22 Isaac Dupree : > Sorry to take offense :-) maybe I was being too modest? > > It seems Arrows are a necessary abstraction for a couple very particular > world-views/paradigms, and don't fit very well with a lot of other stuff. > Hello All I wouldn't go quite as far as saying Arrows are misfits, but in Isaac's defence, if all you have are pure functions, then arrows are just a wee bit, erm, boring. In Philip's original message he happened to be representing his data as a pair, so second worked fine as a projection/application function, vis: *Arrows> second (\x -> "fish") (10,20) (10,"fish") But of course it doesn't work as a projection/application function for triples (sorry I lack a better term for projection/application): *Arrows> second (\x -> "chips") (10,20,30) :1:0: Couldn't match expected type `(t, t1, t2)' against inferred type `(d, b)' In the expression: second (\ x -> "chips") (10, 20, 30) In the definition of `it': it = second (\ x -> "chips") (10, 20, 30) Nor would it work if Philip had defined his own data type. Also for pure functions the derived operators (>>^) and (^>>) become (.), and (<<^) & (^<<) are become reverse composition - which was sometimes called (##) but now seems categorized as (<<<) . The code below is a bit superfluous to the discussion, but it does define the arrow operations for pure functions with the type constructor simplified to (->), I occasionally do the Arrow combinators longhand when I can't remember which Arrow combinator does what. Best wishes Stephen > module ArrowLonghand where > import Control.Arrow arr :: (b -> c) -> a b c fun_arr :: a b c -> (b -> c) where a = (->) > fun_arr :: (b -> c) -> (b -> c) > fun_arr f = f arr's definition is clearly identity, but specialized to functions > alt_fun_arr :: (b -> c) -> (b -> c) > alt_fun_arr = id first :: a b c -> a (b, d) (c, d) fun_first :: a b c -> a (b,d) (c,d) where a = (->) > fun_first :: (b -> c) -> (b,d) -> (c,d) > fun_first f (x,y) = (f x, y) second :: a b c -> a (d, b) (d, c) fun_second :: a b c -> a (d,b) (d,c) where a = (->) > fun_second :: (b -> c) -> (d,b) -> (d,c) > fun_second f (x,y) = (x, f y) (***) :: a b c -> a b' c' -> a (b, b') (c, c') fun_starstarstar :: a b c -> a b' c' -> a (b,b') (c,c') where a = (->) > fun_starstarstar :: (b -> c) -> (b' -> c') -> (b,b') -> (c,c') > fun_starstarstar f g (x,y) = (f x, g y) Funnily enough, (***) is not unlike prod from Jeremy Gibbons 'Pair Calculus': http://www.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/acmmpc-calcfp.pdf > prod :: (b -> c) -> (b' -> c') -> (b,b') -> (c,c') > prod f g = fork (f . fst, g . snd) (&&&) :: a b c -> a b c' -> a b (c, c') fun_ampampamp :: a b c -> a b c' -> a b (c,c') where a = (->) > fun_ampampamp :: (b -> c) -> (b -> c') -> b -> (c,c') > fun_ampampamp f g x = (f x, g x) Funnily enough, (&&&) is not unlike fork from the Pair Calculus... > fork :: (b -> c, b -> c') -> b -> (c,c') > fork (f,g) a = (f a, g a) > pair_first :: (b -> c) -> (b,d) -> (c,d) > pair_first f = f `prod` id > pair_second :: (b -> c) -> (d,b) -> (d,c) > pair_second g = id `prod` g -------------------------------------------------------------------------------- (^>>) :: Arrow a => (b -> c) -> a c d -> a b d > preCompLR :: (b -> c) -> (c -> d) -> (b -> d) > preCompLR f g = \x -> g (f x) (>>^) :: Arrow a => a b c -> (c -> d) -> a b d > postCompLR :: (b -> c) -> (c -> d) -> (b -> d) > postCompLR f g = \x -> g (f x) (^>>) and (>>^) are the same for functions. -- reverse (<<^) :: Arrow a => a c d -> (b -> c) -> a b d > preCompRL :: (c -> d) -> (b -> c) -> (b -> d) > preCompRL f g = \x -> f (g x) (^<<) :: Arrow a => (c -> d) -> a b c -> a b d > postCompRL :: (c -> d) -> (b -> c) -> (b -> d) > postCompRL f g = \x -> f (g x) From byorgey at seas.upenn.edu Sun Nov 22 10:30:20 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Nov 22 10:05:32 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <200911212107.38396.haskell-beginners@foo.me.uk> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911212033.29004.haskell-beginners@foo.me.uk> <200911212107.38396.haskell-beginners@foo.me.uk> Message-ID: <20091122153020.GA31537@seas.upenn.edu> On Sat, Nov 21, 2009 at 09:07:38PM +0000, Philip Scott wrote: > > The final piece is that (->) is an Arrow, the most basic one but still > > an Arrow, so if you replace a by (->) in the type of second, you get : > > second :: (->) b c -> (->) (d, b) (d, c) > > which is just > > second :: (b -> c) -> (d, b) -> (d, c) > > Ahh I see, very clever! There is method to the madness after all; I should > never have doubted you Haskell. Thank you for taking the time to explain that > :) > > Do you know of any good discussions/tutorials on Arrows? I've only managed to > find little snippets here and there > > http://www.haskell.org/arrows/ The two tutorials linked from the "Bibliogrphy" section of that page are very good: http://www.soi.city.ac.uk/~ross/papers/fop.html http://www.cs.chalmers.se/~rjmh/afp-arrows.pdf You may also be interested in reading the "Category" and "Arrow" sections of the Typeclassopedia: http://www.haskell.org/sitewiki/images/8/85/TMR-Issue13.pdf -Brent From Patrick.Browne at comp.dit.ie Sun Nov 22 10:32:07 2009 From: Patrick.Browne at comp.dit.ie (pbrowne) Date: Sun Nov 22 10:07:30 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <20091121210833.GA656@kira.casa> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> <20091121210833.GA656@kira.casa> Message-ID: <4B095977.4080103@comp.dit.ie> On Sat, Nov 21, 2009 at 21:08 Felipe Lessa wrote: > Most definitions, if not all, are just the corresponding free theorems > (meaning roughly that the definition follows from the type > because that's the only definition that doesn't have > undefined's). Question: Is it correct to paraphrase Felipe's description as follows: In Haskell the *term theorems for free* means roughly that the definition of a class, instance or a function follows from the supplied types because they are the only types that don?t have undefined argumens or undefined return types. Regards, Pat From byorgey at seas.upenn.edu Sun Nov 22 10:42:38 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Nov 22 10:17:51 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <4B095977.4080103@comp.dit.ie> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> <20091121210833.GA656@kira.casa> <4B095977.4080103@comp.dit.ie> Message-ID: <20091122154238.GA490@seas.upenn.edu> On Sun, Nov 22, 2009 at 03:32:07PM +0000, pbrowne wrote: > > On Sat, Nov 21, 2009 at 21:08 Felipe Lessa wrote: > > Most definitions, if not all, are just the corresponding free theorems > > (meaning roughly that the definition follows from the type > > because that's the only definition that doesn't have > > undefined's). > > Question: Is it correct to paraphrase Felipe's description as follows: > In Haskell the *term theorems for free* means roughly that the > definition of a class, instance or a function follows from the supplied > types because they are the only types that don?t have undefined argumens > or undefined return types. That is a good way to paraphrase Felipe's description --- but I don't think Felipe's terminology is correct. Many types do indeed have only a small number, or even only one, possible "interesting" implementation that does not involve undefined anywhere. However, this is not what is meant by "free theorems". A "free theorem" is a *property* which is satisfied by any function with a particular type. For example, any function with the type foo :: [a] -> Maybe a necessarily satisfies foo (map f xs) = fmap f (foo xs) (or, in points-free form, foo . map f = fmap f . foo ) for any list xs and function f, no matter what the implementation of foo (as long as it does not involve undefined or unsafePerformIO or any "cheating" of that sort). -Brent From allbery at ece.cmu.edu Sun Nov 22 10:45:04 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sun Nov 22 10:20:28 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <4B095977.4080103@comp.dit.ie> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> <20091121210833.GA656@kira.casa> <4B095977.4080103@comp.dit.ie> Message-ID: <4F0AB5CD-95CA-41DA-86A5-1FAC5781BE2E@ece.cmu.edu> On Nov 22, 2009, at 10:32 , pbrowne wrote: > On Sat, Nov 21, 2009 at 21:08 Felipe Lessa wrote: >> Most definitions, if not all, are just the corresponding free >> theorems >> (meaning roughly that the definition follows from the type >> because that's the only definition that doesn't have >> undefined's). > > Question: Is it correct to paraphrase Felipe's description as follows: > In Haskell the *term theorems for free* means roughly that the > definition of a class, instance or a function follows from the > supplied > types because they are the only types that don?t have undefined > argumens > or undefined return types. Pretty much. It's not specific to Haskell, either; it's a result of the Curry-Howard correspondence between programs and mathematical proofs. http://homepages.inf.ed.ac.uk/wadler/papers/free/free.ps is the canonical paper on deriving free theorems from Hindley-Milner type systems. -- 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/20091122/3964ba3f/PGP.bin From Patrick.Browne at comp.dit.ie Sun Nov 22 11:12:29 2009 From: Patrick.Browne at comp.dit.ie (pbrowne) Date: Sun Nov 22 10:47:49 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <20091122154238.GA490@seas.upenn.edu> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> <20091121210833.GA656@kira.casa> <4B095977.4080103@comp.dit.ie> <20091122154238.GA490@seas.upenn.edu> Message-ID: <4B0962ED.204@comp.dit.ie> On Sun, Nov 22, 2009 at 03:32:07PM +0000, Brent Yorgey wrote: > A "free theorem" is a *property* which > is satisfied by any function with a particular type. For example, any > function with the type > > foo :: [a] -> Maybe a > > necessarily satisfies > > foo (map f xs) = fmap f (foo xs) A theorem is a statement which has been proved on the basis of previously established theorems or axiom. So, should the definition of the function not satisfy the signature? I may be confusing terminology here. I am coming of an OBJ2/Maude/CafeOBJ background to Haskell. In CafeOBJ a *property* of an operation could, for example, be associativity. I am having difficulty in adjusting to Haskells level of formality. >> In Haskell the *theorems for free* means roughly that the >> definition of a class, instance or a function follows from the supplied >> types because they are the only types that don?t have undefined argumens >> or undefined return types. Question: Is my generalization of applying the "free theorem" concept to classes and instances correct? Pat From john.moore54 at gmail.com Sun Nov 22 11:17:46 2009 From: john.moore54 at gmail.com (John Moore) Date: Sun Nov 22 10:52:59 2009 Subject: [Haskell-beginners] Show how the evaluation works Message-ID: <4f7ad1ad0911220817k1b8fda7fy756179a6c9afe0ab@mail.gmail.com> Hi All, I'm trying to work out how to show the steps in evaluating "How the function is calculated". In other words I want this program to actually print out the steps. For e.g. eval (Multiply(Add(Val 10) (Val 20)) (Val 3) Which is add 10+20 and multiply by 3 = 90 The program then produces( Prints out) something like working: eval (Multiply(Add(Val 10) (Val 20)) (Val 3) working Add(Val10) (Val 20) answer 1 Val 30 answer 2 Val 90 This is what I have so far but it wont even do the calculations. Any help appreciated. data Expression = Val Float | Add Expression Expression | Subtract Expression Expression | Multiply Expression Expression | Divide Expression Expression deriving Show eval :: Expression -> Float eval (Val x) = x eval (Add x y) = eval x + eval y eval (Multiply x y) = eval x * eval y eval (Subtract x y) = eval x - eval y eval (Divide x y) = eval x / eval y John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091122/5ede682c/attachment.html From stephen.tetley at gmail.com Sun Nov 22 11:45:07 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sun Nov 22 11:20:20 2009 Subject: [Haskell-beginners] Show how the evaluation works In-Reply-To: <4f7ad1ad0911220817k1b8fda7fy756179a6c9afe0ab@mail.gmail.com> References: <4f7ad1ad0911220817k1b8fda7fy756179a6c9afe0ab@mail.gmail.com> Message-ID: <5fdc56d70911220845u6c46560bg56ce98c78e9fa53c@mail.gmail.com> Hi John You need some more /machinery/ in your evaluator. One possibility is to make it a monadic evaluator - you could then choose to use IO and print things as you go, or a writer monad which 'collects' (think logging) as evaluation progresses. The at the end you'd show both the log and the answer. The writer monad has a run function, which you would need to run the extended evaluator with runWriter :: Writer w a -> (a, w) The result of runWriter is a pair of a (the answer) and w (the log). Writer is more general than just logging, but in this instance logging is close to what you might want. Best wishes Stephen 2009/11/22 John Moore : > Hi All, > > I'm trying to work out how to show the steps in evaluating "How the function > is calculated". In other words I want this program to actually print out the > steps. For e.g. eval (Multiply(Add(Val 10) (Val 20)) (Val 3)??? Which is add > 10+20 and multiply by 3 = 90 > > The program then produces( Prints out)?something like > > working: eval (Multiply(Add(Val 10) (Val 20)) (Val 3) > working Add(Val10) (Val 20) > answer 1 Val 30 > answer 2 Val 90 > > This is what I have so far but it wont even do the calculations. Any help > appreciated. > > data Expression = Val Float > ??????????????? | Add Expression Expression > ??????????????? | Subtract Expression Expression > ??????????????? | Multiply Expression Expression > ??????????????? | Divide Expression Expression > ???????? deriving Show > eval :: Expression -> Float > eval (Val x) = x > eval (Add x y) = eval x + eval y > eval (Multiply x y) = eval x * eval y > eval (Subtract x y) = eval x - eval y > eval (Divide x y) = eval x / eval y > > > > John > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > From daniel.is.fischer at web.de Sun Nov 22 11:54:16 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Nov 22 11:33:10 2009 Subject: [Haskell-beginners] Show how the evaluation works In-Reply-To: <4f7ad1ad0911220817k1b8fda7fy756179a6c9afe0ab@mail.gmail.com> References: <4f7ad1ad0911220817k1b8fda7fy756179a6c9afe0ab@mail.gmail.com> Message-ID: <200911221754.16411.daniel.is.fischer@web.de> Am Sonntag 22 November 2009 17:17:46 schrieb John Moore: > Hi All, > > I'm trying to work out how to show the steps in evaluating "How the > function is calculated". In other words I want this program to actually > print out the steps. For e.g. eval (Multiply(Add(Val 10) (Val 20)) (Val 3) > Which is add 10+20 and multiply by 3 = 90 > > The program then produces( Prints out) something like > > working: eval (Multiply(Add(Val 10) (Val 20)) (Val 3) > working Add(Val10) (Val 20) > answer 1 Val 30 > answer 2 Val 90 > > This is what I have so far but it wont even do the calculations. Any help > appreciated. > > data Expression = Val Float > > | Add Expression Expression > | Subtract Expression Expression > | Multiply Expression Expression > | Divide Expression Expression > > deriving Show > eval :: Expression -> Float > eval (Val x) = x > eval (Add x y) = eval x + eval y > eval (Multiply x y) = eval x * eval y > eval (Subtract x y) = eval x - eval y > eval (Divide x y) = eval x / eval y If you want to have the evaluation steps printed, you must do it in IO (after all, your programme will be performing IO) evalIO :: Expression -> IO Float evalIO (Val x) = do putStrLn $ "Plain value " ++ show x return x evalIO (Add x y) = do vx <- evalIO x vy <- evalIO y putStrLn $ "Add " ++ show vx ++ " and " ++ show vy return (vx+vy) ... You can chose other formatting, maybe display the entire expression before evaluating the subexpressions, indent evaluation printout of subexpressions (needs an Int parameter counting how many levels below the top you are for indentation), ... One thing is that by putting it in IO, *you* specify the evaluation order. By itself, faced with eval (Add x y) = eval x + eval y the system may evaluate either subexpression first. You can give the system that freedom back by using Debug.Trace instead of IO, but then there is a nonzero probability that the output of different evaluations becomes entangled (it may evaluate part of x first, then some part of y, more of x,...). > > > > John From ml at isaac.cedarswampstudios.org Sun Nov 22 12:14:30 2009 From: ml at isaac.cedarswampstudios.org (Isaac Dupree) Date: Sun Nov 22 11:50:09 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <5fdc56d70911220331r269340baj114bcf81af7923ca@mail.gmail.com> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211739.20689.haskell-beginners@foo.me.uk> <20091121212326.GG23495@colquitt.org> <200911212225.35757.haskell-beginners@foo.me.uk> <4B086D11.5080600@isaac.cedarswampstudios.org> <4B087399.1070408@gmail.com> <4B08BB8E.3060700@isaac.cedarswampstudios.org> <5fdc56d70911220331r269340baj114bcf81af7923ca@mail.gmail.com> Message-ID: <4B097176.7060506@isaac.cedarswampstudios.org> Stephen Tetley wrote: > 2009/11/22 Isaac Dupree : >> Sorry to take offense :-) maybe I was being too modest? >> >> It seems Arrows are a necessary abstraction for a couple very particular >> world-views/paradigms, and don't fit very well with a lot of other stuff. >> > > > > Hello All > > I wouldn't go quite as far as saying Arrows are misfits, but in > Isaac's defence, if all you have are pure functions, then arrows are > just a wee bit, erm, boring. :-) there are a few combinators in Arrow that would be nice to have for functions, without even that Arrow generalization, as people have noted now and then. I used to use them sometimes, but then I decided that it was a bit too confusing to the reader to involve a type-class (Arrow) that wasn't very relevant (and not ubiquitously well-known), even if a version with explicit lambdas is a bit longer. From byorgey at seas.upenn.edu Sun Nov 22 12:25:36 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Nov 22 12:00:50 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <4B0962ED.204@comp.dit.ie> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> <20091121210833.GA656@kira.casa> <4B095977.4080103@comp.dit.ie> <20091122154238.GA490@seas.upenn.edu> <4B0962ED.204@comp.dit.ie> Message-ID: <20091122172536.GA11111@seas.upenn.edu> On Sun, Nov 22, 2009 at 04:12:29PM +0000, pbrowne wrote: > On Sun, Nov 22, 2009 at 03:32:07PM +0000, Brent Yorgey wrote: > > A "free theorem" is a *property* which > > is satisfied by any function with a particular type. For example, any > > function with the type > > > > foo :: [a] -> Maybe a > > > > necessarily satisfies > > > > foo (map f xs) = fmap f (foo xs) > > > A theorem is a statement which has been proved on the basis of > previously established theorems or axiom. So, should the definition of > the function not satisfy the signature? I may be confusing terminology > here. I am coming of an OBJ2/Maude/CafeOBJ background to Haskell. In > CafeOBJ a *property* of an operation could, for example, be > associativity. I am having difficulty in adjusting to Haskells level of > formality. I'm not quite sure what you're asking here. My point is just that a "free theorem" will be of the form "Any function f of type T, *no matter how f is implemented*, will always satisfy the following property: blah blah f blah = blah f blah " This has nothing to do with whether or not there is only one possible implementation of f that does not involve undefined, which is a different phenomenon. > > >> In Haskell the *theorems for free* means roughly that the > >> definition of a class, instance or a function follows from the supplied > >> types because they are the only types that don?t have undefined argumens > >> or undefined return types. > > Question: Is my generalization of applying the "free theorem" concept to > classes and instances correct? Classes don't have types, so I'm not sure what you mean by including classes. Generalizing to instances makes sense; type class instances are just composed of a list of functions. However, again, this notion of there sometimes being only one possible implementation of a particular type has nothing to do with the concept of "free theorems". (At least, it has not much to do with it that I am aware of.) From haskell-beginners at foo.me.uk Sun Nov 22 12:59:04 2009 From: haskell-beginners at foo.me.uk (Philip Scott) Date: Sun Nov 22 12:34:30 2009 Subject: [Haskell-beginners] Performance Message-ID: <200911221759.04648.haskell-beginners@foo.me.uk> Hi again folks, I am still at it with my time-series problem, for those who haven't been following; I have a list of (time stamp, value) pairs and I need to do various bits and bobs with them. I have got arithmetic down pat now, thanks to the kind help of various members of the list - now I am looking at functions that look at some historical data in the time-series and do some work on that to give me an answer for a particular day. I have chosen to represent my time series in reverse date order, since non of the operations will ever want to look into the future, but often they would like to look in to the past. A function I would like to write is 'avg'. For a particular day, it computes the average of the values last 'n' points; if there are not n points to fetch, thee is no answer. I then combine those to make a new time series. e.g. If my input time series was [(5,10),(4,20),(3,30),(2,40), (1,50)] (Where 5, 4, 3, 2, 1 are timestamps and 10, 20, 30, 50, 50 are values) I would like the answer [(5,20), (4,30), (3,40)] (e.g. 20 = (10+20+30)/3 etc.. I can't get an answer for timestamps 2 and 1 because there isn't enough historical data) So I have written some code to do this, and it works nicely enough; but it is _slow_. To do 1000 averages of different lengths on a series with only 3000 points takes about 200 seconds on my (not overly shabby) laptop. The equivalent C program takes under a second. I am entirely sure that this is due to some failing on my part. I have been mucking around with the profiler all afternoon lazifying and delazifying various bits and bobs with no dramatic success so I thought I might put it to y'all if you don't mind! So here's some code. I've kept it quite general because there are a lot of functions I would like to implement that do similar things with bits of historical data. General comments on the Haskellyness/goodness of my code are welcomed as well, I'm still very much a beginner at this! --------- SNIP -------------- -- Take n elements from a list if at least n exist takeMaybe n l | length l < n = Nothing | otherwise = Just $! (take n l) -- Little utility function, take a function f and apply it to the whole list, -- then the tail etc... lMap _ [] = [] lMap f (x:xs) = (f (x:xs)):(lMap f xs) -- Little utility function to take a list containing Maybes and delete them -- Returning a list with the values inside the Just maybeListToList [] = [] maybeListToList (x:xs) = maybe (maybeListToList xs) (\y -> y:(maybeListToList xs)) x -- Return a list of lists, where each sublist is a list of the next n values histMaybe x = lMap (takeMaybe x) hist n x = maybeListToList $ histMaybe n x -- Take a function which works on a list of things and apply it only to a -- list of the second elements in a list of tuples 'l'. applyToValues f l = let (ts,vs) = unzip l in zip ts $ f vs -- Create a timeseries with the cumulative sum of the last n values cumL n l = map sum (hist n l) cum = applyToValues . cumL -- Creates a timeseries with the average of the last n values avgL n l = map ((*) (1/fromIntegral(n))) $ cumL n l avg = applyToValues . avgL --------- SNIP -------------- According to the profiler (log attached), the vast majority of the time is spent in takeMaybe, presumably allocating and deallocating enormous amounts of memory for each of my little temporary sublists. I have tried liberally sprinkling $! and 'seq' about, thinking that might help but I am clearly not doing it right. Perhaps list is the wrong basic data structure for what I am doing? I hope I didn't bore you with that rather long email, I will leave it at that. If it would be useful, I could give you the complete program with a data set if anyone is keen enough to try for themselves. Thanks, Philip -------------- next part -------------- Sun Nov 22 17:28 2009 Time and Allocation Profiling Report (Final) test +RTS -p -hc -RTS total time = 162.98 secs (8149 ticks @ 20 ms) total alloc = 47,324,561,080 bytes (excludes profiling overheads) COST CENTRE MODULE %time %alloc takeMaybe Main 62.2 45.9 cumL Main 36.2 52.4 individual inherited COST CENTRE MODULE no. entries %time %alloc %time %alloc MAIN MAIN 1 0 0.0 0.0 100.0 100.0 main Main 297 0 0.0 0.0 0.0 0.0 readCurve TsdbFile 298 0 0.0 0.0 0.0 0.0 CAF Main 260 4 0.0 0.0 100.0 100.0 avgL Main 281 1 0.0 0.0 0.2 0.2 cumL Main 282 1 0.1 0.1 0.2 0.2 hist Main 283 1 0.0 0.0 0.1 0.1 histMaybe Main 285 1 0.0 0.0 0.1 0.1 takeMaybe Main 287 2543 0.1 0.1 0.1 0.1 lMap Main 286 2544 0.0 0.0 0.0 0.0 maybeListToList Main 284 2544 0.0 0.0 0.0 0.0 avg Main 276 1 0.0 0.0 0.0 0.0 applyToValues Main 277 1 0.0 0.0 0.0 0.0 main Main 266 1 0.0 0.0 99.8 99.8 avg Main 288 0 0.2 0.2 99.1 99.1 avgL Main 290 0 0.0 0.0 98.8 98.4 cumL Main 291 0 36.1 52.3 98.8 98.4 hist Main 292 999 0.0 0.0 62.6 46.1 histMaybe Main 294 999 0.0 0.0 62.4 46.0 takeMaybe Main 296 1542456 62.1 45.8 62.1 45.8 lMap Main 295 1542456 0.3 0.2 0.3 0.2 maybeListToList Main 293 1542456 0.2 0.1 0.2 0.1 applyToValues Main 289 999 0.2 0.5 0.2 0.5 @+ Main 272 1000 0.0 0.0 0.6 0.6 mergeStep Main 275 1000 0.3 0.2 0.4 0.4 v Main 300 0 0.0 0.1 0.0 0.1 t Main 299 0 0.1 0.1 0.1 0.1 add Main 273 1000 0.0 0.0 0.1 0.2 binaryValueFunc Main 274 1544001 0.1 0.2 0.1 0.2 sendCurve GuiLink 268 1 0.0 0.0 0.1 0.0 putCurve GuiLink 271 1545 0.1 0.0 0.1 0.0 readCurve TsdbFile 267 1 0.0 0.0 0.0 0.0 CAF Data.Typeable 258 1 0.0 0.0 0.0 0.0 CAF GHC.IOBase 236 3 0.0 0.0 0.0 0.0 CAF GHC.Read 234 1 0.0 0.0 0.0 0.0 CAF GHC.Float 233 1 0.0 0.0 0.0 0.0 CAF Text.Read.Lex 227 6 0.0 0.0 0.0 0.0 CAF GHC.Int 222 1 0.0 0.0 0.0 0.0 CAF Data.HashTable 213 2 0.0 0.0 0.0 0.0 CAF GHC.Handle 211 5 0.0 0.0 0.0 0.0 main Main 279 0 0.0 0.0 0.0 0.0 readCurve TsdbFile 280 0 0.0 0.0 0.0 0.0 CAF GHC.Conc 210 1 0.0 0.0 0.0 0.0 CAF System.Posix.Internals 192 1 0.0 0.0 0.0 0.0 CAF TsdbFile 181 5 0.0 0.0 0.0 0.0 getCurve TsdbFile 278 1 0.0 0.0 0.0 0.0 CAF Data.Binary.IEEE754 180 6 0.0 0.0 0.0 0.0 CAF Data.Binary.Get 179 2 0.0 0.0 0.0 0.0 CAF Data.Binary.Put 151 1 0.0 0.0 0.0 0.0 CAF GuiLink 145 2 0.0 0.0 0.0 0.0 CAF Network 144 1 0.0 0.0 0.0 0.0 CAF Network.Socket 143 5 0.0 0.0 0.0 0.0 main Main 269 0 0.0 0.0 0.0 0.0 sendCurve GuiLink 270 0 0.0 0.0 0.0 0.0 CAF Network.BSD 139 1 0.0 0.0 0.0 0.0 From s.clover at gmail.com Sun Nov 22 13:08:24 2009 From: s.clover at gmail.com (sterl) Date: Sun Nov 22 12:43:39 2009 Subject: [Haskell-beginners] Type classes and synonyms In-Reply-To: <20091122172536.GA11111@seas.upenn.edu> References: <200911211520.31063.haskell-beginners@foo.me.uk> <200911211757.45857.haskell-beginners@foo.me.uk> <20091121181934.GB11728@kira.casa> <200911212033.29004.haskell-beginners@foo.me.uk> <20091121210833.GA656@kira.casa> <4B095977.4080103@comp.dit.ie> <20091122154238.GA490@seas.upenn.edu> <4B0962ED.204@comp.dit.ie> <20091122172536.GA11111@seas.upenn.edu> Message-ID: <4B097E18.2030002@gmail.com> Brent Yorgey wrote: > "free theorem" will be of the form > > "Any function f of type T, *no matter how f is implemented*, will > always satisfy the following property: > > blah blah f blah = blah f blah > " > > This has nothing to do with whether or not there is only one possible > implementation of f that does not involve undefined, which is a > different phenomenon. > If it hasn't been mentioned, djinn turns type signatures into code, as has been discussed, although if f has multiple implementations, it will simply produce one of them. http://hackage.haskell.org/package/djinn The discussion on ltu helps flesh out the concept: http://lambda-the-ultimate.org/node/1178 This is, of course, as Brent pointed out, very different from free theorems. --S From ezyang at MIT.EDU Sun Nov 22 13:29:42 2009 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Sun Nov 22 13:07:59 2009 Subject: [Haskell-beginners] combinatorial In-Reply-To: <4B0911A9.8030208@alumni.caltech.edu> References: <4B0911A9.8030208@alumni.caltech.edu> Message-ID: <1258913625-sup-9282@ezyang> > I'd like to write a function that constructs a phrase of length n, and > in fact will have to return a list of all phrases that have equal scores > of the maximum. > > -- -> -> -> > -- > coolFunc :: Int -> MidiPitch -> ([MidiPitch] -> Maybe Float) -> > [[MidiPitch]] We can relax this requirement by returning a list of all phrases that are of length n (and were not unacceptable) and then doing some kind of fold. If you can relax the maximum requirement, you can make it not necessary to know the entire solutions space before you can start returning results. In that case, the worker function looks something like: type Evaluator = [MidiPitch] -> Maybe Float] workFunc :: Int -> [MidiPitch] -> Evaluator -> [[MidiPitch]] Letting Int decrease in successive iterations. And you probably want some sort of generating function: generateFunc :: [MidiPitch] -> [[MidiPitch]] And then you can let the list (or logic) monad work its magic. workFunc 0 song eval = return song workFunc n song eval = do song' <- generateFunc case eval song' of Nothing -> [] _ -> return song' Note that since your evaluation function is not incremental (i.e. I can't pass it a partial evaluation) I don't maintain scores in workFunc. Cheers, Edward From daniel.is.fischer at web.de Sun Nov 22 13:32:26 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Nov 22 13:11:53 2009 Subject: [Haskell-beginners] Performance In-Reply-To: <200911221759.04648.haskell-beginners@foo.me.uk> References: <200911221759.04648.haskell-beginners@foo.me.uk> Message-ID: <200911221932.26779.daniel.is.fischer@web.de> Am Sonntag 22 November 2009 18:59:04 schrieb Philip Scott: > Hi again folks, > > I am still at it with my time-series problem, for those who haven't been > following; I have a list of (time stamp, value) pairs and I need to do > various bits and bobs with them. I have got arithmetic down pat now, thanks > to the kind help of various members of the list - now I am looking at > functions that look at some historical data in the time-series and do some > work on that to give me an answer for a particular day. > > I have chosen to represent my time series in reverse date order, since non > of the operations will ever want to look into the future, but often they > would like to look in to the past. > > A function I would like to write is 'avg'. For a particular day, it > computes the average of the values last 'n' points; if there are not n > points to fetch, thee is no answer. I then combine those to make a new time > series. > > e.g. > > If my input time series was > > [(5,10),(4,20),(3,30),(2,40), (1,50)] > > (Where 5, 4, 3, 2, 1 are timestamps and 10, 20, 30, 50, 50 are values) > > I would like the answer > > [(5,20), (4,30), (3,40)] > > (e.g. 20 = (10+20+30)/3 etc.. I can't get an answer for timestamps 2 and 1 > because there isn't enough historical data) > > So I have written some code to do this, and it works nicely enough; but it > is _slow_. To do 1000 averages of different lengths on a series with only > 3000 points takes about 200 seconds on my (not overly shabby) laptop. The > equivalent C program takes under a second. > > I am entirely sure that this is due to some failing on my part. I have been > mucking around with the profiler all afternoon lazifying and delazifying > various bits and bobs with no dramatic success so I thought I might put it > to y'all if you don't mind! > > So here's some code. I've kept it quite general because there are a lot of > functions I would like to implement that do similar things with bits of > historical data. > > General comments on the Haskellyness/goodness of my code are welcomed as > well, I'm still very much a beginner at this! > > --------- SNIP -------------- > > -- Take n elements from a list if at least n exist > takeMaybe n l | length l < n = Nothing > > | otherwise = Just $! (take n l) Ouch, that makes your algorithm quadratic already. Checking "length l < n" must trverse the entire list: 3000 nodes + 2999 nodes + 2998 nodes + you get the idea. takeMaybe n l | null $ drop (n-1) l = Nothing | otherwise = Just (take n l) Or a variation, case splitAt (n-1) l of (a,h:t) -> Just (a ++ [h]) _ -> Nothing (test which is faster, play with various sorts of strictness,...) > > -- Little utility function, take a function f and apply it to the whole > list, -- then the tail etc... > lMap _ [] = [] > lMap f (x:xs) = (f (x:xs)):(lMap f xs) lMap f = map f . tails (Data.List.tails and Data.List.inits are often useful, more idiomatic anyway) > > -- Little utility function to take a list containing Maybes and delete them > -- Returning a list with the values inside the Just > maybeListToList [] = [] > maybeListToList (x:xs) = maybe (maybeListToList xs) > (\y -> y:(maybeListToList xs)) > x Look at Data.Maybe.catMaybes > > -- Return a list of lists, where each sublist is a list of the next n > values histMaybe x = lMap (takeMaybe x) > hist n x = maybeListToList $ histMaybe n x map (take n) $ takeWhile (not . null . drop (n-1)) $ tails xs > > -- Take a function which works on a list of things and apply it only to a > -- list of the second elements in a list of tuples 'l'. > applyToValues f l = let (ts,vs) = unzip l > in zip ts $ f vs > > -- Create a timeseries with the cumulative sum of the last n values > cumL n l = map sum (hist n l) > cum = applyToValues . cumL > > -- Creates a timeseries with the average of the last n values > avgL n l = map ((*) (1/fromIntegral(n))) $ cumL n l map (/fromIntegral n), surely? > avg = applyToValues . avgL > > > --------- SNIP -------------- > > According to the profiler (log attached), the vast majority of the time is > spent in takeMaybe, presumably allocating and deallocating enormous amounts > of memory for each of my little temporary sublists. I have tried liberally > sprinkling $! and 'seq' about, thinking that might help but I am clearly > not doing it right. > > Perhaps list is the wrong basic data structure for what I am doing? > > I hope I didn't bore you with that rather long email, I will leave it at > that. If it would be useful, I could give you the complete program with a > data set if anyone is keen enough to try for themselves. > > Thanks, > > Philip From ezyang at MIT.EDU Sun Nov 22 13:37:31 2009 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Sun Nov 22 13:19:04 2009 Subject: [Haskell-beginners] combinatorial In-Reply-To: <1258913625-sup-9282@ezyang> References: <4B0911A9.8030208@alumni.caltech.edu> <1258913625-sup-9282@ezyang> Message-ID: <1258914980-sup-5592@ezyang> Excerpts from Edward Z. Yang's message of Sun Nov 22 13:29:42 -0500 2009: > Letting Int decrease in successive iterations. > > [snip] > > workFunc 0 song eval = return song > workFunc n song eval = do > song' <- generateFunc > case eval song' of > Nothing -> [] > _ -> return song' Um, I fudged the recursive case. workFunc n song eval = do song' <- generateFunc case eval song' of Nothing -> [] _ -> workFunc (n-1) song' eval Cheers, Edward From alexander.dunlap at gmail.com Sun Nov 22 13:44:38 2009 From: alexander.dunlap at gmail.com (Alex Dunlap) Date: Sun Nov 22 13:25:11 2009 Subject: [Haskell-beginners] Performance In-Reply-To: <200911221759.04648.haskell-beginners@foo.me.uk> References: <200911221759.04648.haskell-beginners@foo.me.uk> Message-ID: <20091122184438.GA20452@rhubarb.hsd1.wa.comcast.net> On Sun, Nov 22, 2009 at 05:59:04PM +0000, Philip Scott wrote: > Hi again folks, > > I am still at it with my time-series problem, for those who haven't been > following; I have a list of (time stamp, value) pairs and I need to do various > bits and bobs with them. I have got arithmetic down pat now, thanks to the > kind help of various members of the list - now I am looking at functions that > look at some historical data in the time-series and do some work on that to > give me an answer for a particular day. > > I have chosen to represent my time series in reverse date order, since non of > the operations will ever want to look into the future, but often they would > like to look in to the past. > > A function I would like to write is 'avg'. For a particular day, it computes > the average of the values last 'n' points; if there are not n points to fetch, > thee is no answer. I then combine those to make a new time series. > > e.g. > > If my input time series was > > [(5,10),(4,20),(3,30),(2,40), (1,50)] > > (Where 5, 4, 3, 2, 1 are timestamps and 10, 20, 30, 50, 50 are values) > > I would like the answer > > [(5,20), (4,30), (3,40)] > > (e.g. 20 = (10+20+30)/3 etc.. I can't get an answer for timestamps 2 and 1 > because there isn't enough historical data) > > So I have written some code to do this, and it works nicely enough; but it is > _slow_. To do 1000 averages of different lengths on a series with only 3000 > points takes about 200 seconds on my (not overly shabby) laptop. The > equivalent C program takes under a second. > > I am entirely sure that this is due to some failing on my part. I have been > mucking around with the profiler all afternoon lazifying and delazifying > various bits and bobs with no dramatic success so I thought I might put it to > y'all if you don't mind! > > So here's some code. I've kept it quite general because there are a lot of > functions I would like to implement that do similar things with bits of > historical data. > > General comments on the Haskellyness/goodness of my code are welcomed as well, > I'm still very much a beginner at this! > > --------- SNIP -------------- > > -- Take n elements from a list if at least n exist > takeMaybe n l | length l < n = Nothing > | otherwise = Just $! (take n l) > > -- Little utility function, take a function f and apply it to the whole list, > -- then the tail etc... > lMap _ [] = [] > lMap f (x:xs) = (f (x:xs)):(lMap f xs) > > -- Little utility function to take a list containing Maybes and delete them > -- Returning a list with the values inside the Just > maybeListToList [] = [] > maybeListToList (x:xs) = maybe (maybeListToList xs) > (\y -> y:(maybeListToList xs)) > x > > -- Return a list of lists, where each sublist is a list of the next n values > histMaybe x = lMap (takeMaybe x) > hist n x = maybeListToList $ histMaybe n x > > -- Take a function which works on a list of things and apply it only to a > -- list of the second elements in a list of tuples 'l'. > applyToValues f l = let (ts,vs) = unzip l > in zip ts $ f vs > > -- Create a timeseries with the cumulative sum of the last n values > cumL n l = map sum (hist n l) > cum = applyToValues . cumL > > -- Creates a timeseries with the average of the last n values > avgL n l = map ((*) (1/fromIntegral(n))) $ cumL n l > avg = applyToValues . avgL > > > --------- SNIP -------------- > > According to the profiler (log attached), the vast majority of the time is > spent in takeMaybe, presumably allocating and deallocating enormous amounts of > memory for each of my little temporary sublists. I have tried liberally > sprinkling $! and 'seq' about, thinking that might help but I am clearly not > doing it right. > > Perhaps list is the wrong basic data structure for what I am doing? > > I hope I didn't bore you with that rather long email, I will leave it at that. > If it would be useful, I could give you the complete program with a data set > if anyone is keen enough to try for themselves. > > Thanks, > > Philip > > Sun Nov 22 17:28 2009 Time and Allocation Profiling Report (Final) > > test +RTS -p -hc -RTS > > total time = 162.98 secs (8149 ticks @ 20 ms) > total alloc = 47,324,561,080 bytes (excludes profiling overheads) > > COST CENTRE MODULE %time %alloc > > takeMaybe Main 62.2 45.9 > cumL Main 36.2 52.4 > > > individual inherited > COST CENTRE MODULE no. entries %time %alloc %time %alloc > > MAIN MAIN 1 0 0.0 0.0 100.0 100.0 > main Main 297 0 0.0 0.0 0.0 0.0 > readCurve TsdbFile 298 0 0.0 0.0 0.0 0.0 > CAF Main 260 4 0.0 0.0 100.0 100.0 > avgL Main 281 1 0.0 0.0 0.2 0.2 > cumL Main 282 1 0.1 0.1 0.2 0.2 > hist Main 283 1 0.0 0.0 0.1 0.1 > histMaybe Main 285 1 0.0 0.0 0.1 0.1 > takeMaybe Main 287 2543 0.1 0.1 0.1 0.1 > lMap Main 286 2544 0.0 0.0 0.0 0.0 > maybeListToList Main 284 2544 0.0 0.0 0.0 0.0 > avg Main 276 1 0.0 0.0 0.0 0.0 > applyToValues Main 277 1 0.0 0.0 0.0 0.0 > main Main 266 1 0.0 0.0 99.8 99.8 > avg Main 288 0 0.2 0.2 99.1 99.1 > avgL Main 290 0 0.0 0.0 98.8 98.4 > cumL Main 291 0 36.1 52.3 98.8 98.4 > hist Main 292 999 0.0 0.0 62.6 46.1 > histMaybe Main 294 999 0.0 0.0 62.4 46.0 > takeMaybe Main 296 1542456 62.1 45.8 62.1 45.8 > lMap Main 295 1542456 0.3 0.2 0.3 0.2 > maybeListToList Main 293 1542456 0.2 0.1 0.2 0.1 > applyToValues Main 289 999 0.2 0.5 0.2 0.5 > @+ Main 272 1000 0.0 0.0 0.6 0.6 > mergeStep Main 275 1000 0.3 0.2 0.4 0.4 > v Main 300 0 0.0 0.1 0.0 0.1 > t Main 299 0 0.1 0.1 0.1 0.1 > add Main 273 1000 0.0 0.0 0.1 0.2 > binaryValueFunc Main 274 1544001 0.1 0.2 0.1 0.2 > sendCurve GuiLink 268 1 0.0 0.0 0.1 0.0 > putCurve GuiLink 271 1545 0.1 0.0 0.1 0.0 > readCurve TsdbFile 267 1 0.0 0.0 0.0 0.0 > CAF Data.Typeable 258 1 0.0 0.0 0.0 0.0 > CAF GHC.IOBase 236 3 0.0 0.0 0.0 0.0 > CAF GHC.Read 234 1 0.0 0.0 0.0 0.0 > CAF GHC.Float 233 1 0.0 0.0 0.0 0.0 > CAF Text.Read.Lex 227 6 0.0 0.0 0.0 0.0 > CAF GHC.Int 222 1 0.0 0.0 0.0 0.0 > CAF Data.HashTable 213 2 0.0 0.0 0.0 0.0 > CAF GHC.Handle 211 5 0.0 0.0 0.0 0.0 > main Main 279 0 0.0 0.0 0.0 0.0 > readCurve TsdbFile 280 0 0.0 0.0 0.0 0.0 > CAF GHC.Conc 210 1 0.0 0.0 0.0 0.0 > CAF System.Posix.Internals 192 1 0.0 0.0 0.0 0.0 > CAF TsdbFile 181 5 0.0 0.0 0.0 0.0 > getCurve TsdbFile 278 1 0.0 0.0 0.0 0.0 > CAF Data.Binary.IEEE754 180 6 0.0 0.0 0.0 0.0 > CAF Data.Binary.Get 179 2 0.0 0.0 0.0 0.0 > CAF Data.Binary.Put 151 1 0.0 0.0 0.0 0.0 > CAF GuiLink 145 2 0.0 0.0 0.0 0.0 > CAF Network 144 1 0.0 0.0 0.0 0.0 > CAF Network.Socket 143 5 0.0 0.0 0.0 0.0 > main Main 269 0 0.0 0.0 0.0 0.0 > sendCurve GuiLink 270 0 0.0 0.0 0.0 0.0 > CAF Network.BSD 139 1 0.0 0.0 0.0 0.0 > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners Without a dataset, I don't know if this is any faster than what you have, but I think it's a fair bit prettier, so you might have more luck starting with this: -- | windows 3 [1..5] = [[1,2,3],[2,3,4],[3,4,5]] windows :: Int -> [a] -> [[a]] windows n xs = foldr (zipWith (:)) (repeat []) (take n (iterate (drop 1) xs)) and then averaging each list. Hope that helps. Alex From daniel.is.fischer at web.de Sun Nov 22 14:15:24 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Nov 22 13:56:45 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal Message-ID: <200911222015.24432.daniel.is.fischer@web.de> Guideline: NEVER, *never ever*, use 'length' ***unless you really want to know the exact length of a list*** Proposal: rename 'length' to 'yesIReallyWantToKnowTheExactLengthOfThisListSoPleaseCalculateItForMe' to reduce performance bugs caused by naive uses of length. From jfredett at gmail.com Sun Nov 22 14:26:40 2009 From: jfredett at gmail.com (Joe Fredette) Date: Sun Nov 22 14:01:54 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal In-Reply-To: <200911222015.24432.daniel.is.fischer@web.de> References: <200911222015.24432.daniel.is.fischer@web.de> Message-ID: Well then, on a similar note, I propose the following name changes: (+) is now "yesIShouldReallyLikeToKnowTheSumOfTheseTwoThingsOverWhichTheOperationOfSummationIsDulyAndTotallyDefined " (-) is the same, but with "Summation" changed to "AdditiveInverseAndSummation" the `do` construct ought to be renamed "doThisMonadicComputationForMePleaseByDesugaringThisConvienentNotationAndTurningItIntoASequenceOfBindFunctionsAndLambdaAbstractionsSuchThatMyIntendedMeaningInFactIsReflected " Further, things like "unsafePerformIO" is not nearly descriptive enough, however, I leave it's appropriate renaming as an exercise to the reader... /Joe On Nov 22, 2009, at 2:15 PM, Daniel Fischer wrote: > Guideline: > > NEVER, *never ever*, use 'length' ***unless you really want to know > the exact length of a > list*** > > Proposal: > rename 'length' to > 'yesIReallyWantToKnowTheExactLengthOfThisListSoPleaseCalculateItForMe' > to reduce performance bugs caused by naive uses of length. > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From michael at snoyman.com Sun Nov 22 14:32:13 2009 From: michael at snoyman.com (Michael Snoyman) Date: Sun Nov 22 14:07:26 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal In-Reply-To: References: <200911222015.24432.daniel.is.fischer@web.de> Message-ID: <29bf512f0911221132y300eda06u6cb61c4df88d3635@mail.gmail.com> I should think the more obvious examples would be last and init... Michael On Sun, Nov 22, 2009 at 9:26 PM, Joe Fredette wrote: > Well then, on a similar note, I propose the following name changes: > > > (+) is now > "yesIShouldReallyLikeToKnowTheSumOfTheseTwoThingsOverWhichTheOperationOfSummationIsDulyAndTotallyDefined" > > (-) is the same, but with "Summation" changed to > "AdditiveInverseAndSummation" > > the `do` construct ought to be renamed > "doThisMonadicComputationForMePleaseByDesugaringThisConvienentNotationAndTurningItIntoASequenceOfBindFunctionsAndLambdaAbstractionsSuchThatMyIntendedMeaningInFactIsReflected" > > Further, things like "unsafePerformIO" is not nearly descriptive enough, > however, I leave it's appropriate renaming as an exercise to the reader... > > /Joe > > > On Nov 22, 2009, at 2:15 PM, Daniel Fischer wrote: > > Guideline: >> >> NEVER, *never ever*, use 'length' ***unless you really want to know the >> exact length of a >> list*** >> >> Proposal: >> rename 'length' to >> 'yesIReallyWantToKnowTheExactLengthOfThisListSoPleaseCalculateItForMe' >> to reduce performance bugs caused by naive uses of length. >> _______________________________________________ >> 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/20091122/e5532ca9/attachment.html From stephen.tetley at gmail.com Sun Nov 22 14:33:21 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sun Nov 22 14:08:33 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal In-Reply-To: <200911222015.24432.daniel.is.fischer@web.de> References: <200911222015.24432.daniel.is.fischer@web.de> Message-ID: <5fdc56d70911221133n18a3ef50y9a7fad9390a409b9@mail.gmail.com> Hi Daniel Hmm, maybe the docs in Data.List should say that length is recursively calculated. I know you can view the source from Haddock, and its also obvious once you think of list as being defined by an algebriac type, but lists in other languages (read OO) often have track length as part of the ADT making it constant time to get hold of. Best wishes Stephen 2009/11/22 Daniel Fischer : > Guideline: > > NEVER, *never ever*, use 'length' ***unless you really want to know the exact length of a > list*** > > Proposal: > rename 'length' to 'yesIReallyWantToKnowTheExactLengthOfThisListSoPleaseCalculateItForMe' > to reduce performance bugs caused by naive uses of length. > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From daniel.is.fischer at web.de Sun Nov 22 14:55:56 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Nov 22 14:34:57 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal In-Reply-To: <5fdc56d70911221133n18a3ef50y9a7fad9390a409b9@mail.gmail.com> References: <200911222015.24432.daniel.is.fischer@web.de> <5fdc56d70911221133n18a3ef50y9a7fad9390a409b9@mail.gmail.com> Message-ID: <200911222055.56660.daniel.is.fischer@web.de> Am Sonntag 22 November 2009 20:33:21 schrieb Stephen Tetley: > Hi Daniel > > Hmm, maybe the docs in Data.List should say that length is recursively > calculated. I never noticed the docs didn't say anything about the complexity of length. That should indeed be mentioned. > I know you can view the source from Haddock, and its also > obvious once you think of list as being defined by an algebriac type, > but lists in other languages (read OO) often have track length as part > of the ADT making it constant time to get hold of. Which of course is not easy for infinite lists, even harder for lists of which you don't know yet whether they're finite or not (list of prime-twins, e.g.). > > Best wishes > > Stephen > > 2009/11/22 Daniel Fischer : > > Guideline: > > > > NEVER, *never ever*, use 'length' ***unless you really want to know the > > exact length of a list*** > > > > Proposal: > > rename 'length' to > > 'yesIReallyWantToKnowTheExactLengthOfThisListSoPleaseCalculateItForMe' to > > reduce performance bugs caused by naive uses of length. From daniel.is.fischer at web.de Sun Nov 22 15:07:50 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Nov 22 14:44:28 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal In-Reply-To: <92e42b740911221143l5f8a09dfy86ce3f886827c127@mail.gmail.com> References: <200911222015.24432.daniel.is.fischer@web.de> <5fdc56d70911221133n18a3ef50y9a7fad9390a409b9@mail.gmail.com> <92e42b740911221143l5f8a09dfy86ce3f886827c127@mail.gmail.com> Message-ID: <200911222107.51230.daniel.is.fischer@web.de> Am Sonntag 22 November 2009 20:43:54 schrieb Keith Sheppard: > ... or just say that it's O(n) in the docs. And if n is infinity > you'll be waiting for a while. http://hackage.haskell.org/trac/ghc/ticket/3680 Ticket opened. From keithshep at gmail.com Sun Nov 22 14:43:54 2009 From: keithshep at gmail.com (Keith Sheppard) Date: Sun Nov 22 14:46:42 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal In-Reply-To: <5fdc56d70911221133n18a3ef50y9a7fad9390a409b9@mail.gmail.com> References: <200911222015.24432.daniel.is.fischer@web.de> <5fdc56d70911221133n18a3ef50y9a7fad9390a409b9@mail.gmail.com> Message-ID: <92e42b740911221143l5f8a09dfy86ce3f886827c127@mail.gmail.com> ... or just say that it's O(n) in the docs. And if n is infinity you'll be waiting for a while. (Sorry Stephen... meant that for the list) On Sun, Nov 22, 2009 at 2:33 PM, Stephen Tetley wrote: > Hi Daniel > > Hmm, maybe the docs in Data.List should say that length is recursively > calculated. I know you can view the source from Haddock, and its also > obvious once you think of list as being defined by an algebriac type, > but lists in other languages (read OO) often have track length as part > of the ADT making it constant time to get hold of. > > Best wishes > > Stephen > > > 2009/11/22 Daniel Fischer : >> Guideline: >> >> NEVER, *never ever*, use 'length' ***unless you really want to know the exact length of a >> list*** >> >> Proposal: >> rename 'length' to 'yesIReallyWantToKnowTheExactLengthOfThisListSoPleaseCalculateItForMe' >> to reduce performance bugs caused by naive uses of length. >> _______________________________________________ >> 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 > -- keithsheppard.name From stephen.tetley at gmail.com Sun Nov 22 15:25:27 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sun Nov 22 15:00:39 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal In-Reply-To: <200911222055.56660.daniel.is.fischer@web.de> References: <200911222015.24432.daniel.is.fischer@web.de> <5fdc56d70911221133n18a3ef50y9a7fad9390a409b9@mail.gmail.com> <200911222055.56660.daniel.is.fischer@web.de> Message-ID: <5fdc56d70911221225y28c14d9ay69c58114c63c9e6d@mail.gmail.com> 2009/11/22 Daniel Fischer : > I never noticed the docs didn't say anything about the complexity of length. > That should indeed be mentioned. Maybe not too usual, neither the OCaml or MzScheme docs mention that length is not constant time (caveat - I'm not at the latest release of either). Actually I was a bit surprised that getting the length in MzScheme was an iterative calculation rather than constant-time lookup, it's something I never noticed in years of using MzScheme. http://caml.inria.fr/cgi-bin/viewcvs.cgi/ocaml/trunk/stdlib/list.ml?rev=7597&view=markup http://svn.plt-scheme.org/plt/trunk/src/mzscheme/src/list.c see scheme_list_length Best wishes Stephen From allbery at ece.cmu.edu Sun Nov 22 15:28:00 2009 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sun Nov 22 15:03:27 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal In-Reply-To: <5fdc56d70911221225y28c14d9ay69c58114c63c9e6d@mail.gmail.com> References: <200911222015.24432.daniel.is.fischer@web.de> <5fdc56d70911221133n18a3ef50y9a7fad9390a409b9@mail.gmail.com> <200911222055.56660.daniel.is.fischer@web.de> <5fdc56d70911221225y28c14d9ay69c58114c63c9e6d@mail.gmail.com> Message-ID: On Nov 22, 2009, at 15:25 , Stephen Tetley wrote: > 2009/11/22 Daniel Fischer : > I never noticed the docs didn't say anything about the complexity of > length. >> That should indeed be mentioned. > > Maybe not too usual, neither the OCaml or MzScheme docs mention that > length is not constant time (caveat - I'm not at the latest release of > either). But laziness means that it's not always obvious what time complexity a given function has, so it's a good idea to document it in all cases. -- 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/20091122/dfdaefce/PGP-0001.bin From patrick.leboutillier at gmail.com Sun Nov 22 17:04:11 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Sun Nov 22 16:39:24 2009 Subject: Fwd: [Haskell-beginners] combinatorial In-Reply-To: References: <4B0911A9.8030208@alumni.caltech.edu> Message-ID: Forgot to forward my response to the list... ---------- Forwarded message ---------- From: Patrick LeBoutillier Date: Sun, Nov 22, 2009 at 5:03 PM Subject: Re: [Haskell-beginners] combinatorial To: "Michael P. Mossey" Michael, Here's how I would go about this: type MidiPitch = Int range :: [MidiPitch] range = [10..90] -- Just a dummy eval function, allows up or down one unit eval ps | length ps <= 1 = Just 1.0 eval ps | length ps > 1 ?= ?let a = last ps ? ? ?b = last . init $ ps in ?if abs (a - b) == 1 ? ? then Just 1.0 ? ? else Nothing coolFunc :: Int -> MidiPitch -> ([MidiPitch] -> Maybe Float) -> [[MidiPitch]] coolFunc n p f = generate n f [[p]] -- Generate MidiPitch lists up to a given length, making sure each step -- satisfies the eval function generate :: Int -> ([MidiPitch] -> Maybe Float) -> [[MidiPitch]] -> [[MidiPitch]] generate n f cs | n == 1 = cs generate n f cs = generate (n-1) f $ concat . map (\p -> try p cs) $ range -- Tries to add a MidiPitch to each of the MidiPitch lists, keep -- only the sequences that pass the eval. try :: MidiPitch -> [[MidiPitch]] -> [[MidiPitch]] try p = filter (not . null) . map (test p) ?where test p ps = ? ? ? ? ?let ps' = ps ++ [p] in ? ? ? ? ?case eval ps' of ? ? ? ? ? ?Nothing ? -> [] ? ? ? ? ? ?otherwise -> ps' It's seems to work, although I'm sure many bits sould be made more elegant... Note: After that another pass would be required over the result set to find the sequences that have the highest scores. Patrick On Sun, Nov 22, 2009 at 5:25 AM, Michael P. Mossey wrote: > I'm trying to write a combinatorial search algorithm with evaluation, and > kind of stuck. Not sure how to do this. > > I'm constructing a musical phrase, which is a list of MidiPitch: > > [MidiPitch] > > I have an evaluation function that determines the fitness of any given > phrase: > > eval :: [MidiPitch] -> Maybe Float > > This returns Nothing if the phrase is completely unacceptable. > > The idea is to build up a phrase one midi pitch at a time, choosing all > possible next pitches (notes) from a range: > > next pitch comes from: [10..90] > > Most of the pitches will result in a phrase that evaluates to Nothing, so > the combinatoral "explosion" will be limited. > > I'd like to write a function that constructs a phrase of length n, and in > fact will have to return a list of all phrases that have equal scores of the > maximum. > > -- ? ? ? ? -> -> -> > -- ? ? ? ? > coolFunc :: Int -> MidiPitch -> ([MidiPitch] -> Maybe Float) -> > ? ? ? ? ? [[MidiPitch]] > > I am stuck on how to write this. > > thanks, > Mike > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From mpm at alumni.caltech.edu Sun Nov 22 17:30:57 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Sun Nov 22 17:06:15 2009 Subject: [Haskell-beginners] combinatorial In-Reply-To: <1258913625-sup-9282@ezyang> References: <4B0911A9.8030208@alumni.caltech.edu> <1258913625-sup-9282@ezyang> Message-ID: <4B09BBA1.2040303@alumni.caltech.edu> Edward Z. Yang wrote: > We can relax this requirement by returning a list of all phrases that > are of length n (and were not unacceptable) and then doing some kind > of fold. Thanks for the advice and code. > Note that since your evaluation function is not incremental > (i.e. I can't pass it a partial evaluation) I don't maintain scores > in workFunc. I'm not totally exactly sure what you mean here, but my evaluation function can in fact evaluate phrases of any length. In fact, I realized after seeing your reply that I failed to describe my problem well at all. Here's what I had in mind for a search algorithm. The idea is to combine features of greedy and broad search. I have no idea is this is a good idea. It's just a thought. Let's say we start by evaluating all lists of length 2 and picking those tied for the maximum score. Then the algorithm is, for each input list of length 2 tied for maximum, make all lists of length 3 that are acceptable (that don't return Nothing when evaluated) concat all those evaluate all of them and pick all tied for the maximum feed into next step (continue with lengths 4..N.) The idea is that's a greedy algorithm that still allows for some breadth of search by looking at ties. In my scoring system there will often be ties. Thanks, Mike From ajb at spamcop.net Sun Nov 22 21:54:10 2009 From: ajb at spamcop.net (ajb@spamcop.net) Date: Sun Nov 22 21:29:20 2009 Subject: [Haskell-beginners] Important coding guideline and library proposal In-Reply-To: <200911222015.24432.daniel.is.fischer@web.de> References: <200911222015.24432.daniel.is.fischer@web.de> Message-ID: <20091122215410.aqwbhyiog2sc44cc-nwo@webmail.spamcop.net> G'day all. Quoting Daniel Fischer : > Proposal: > rename 'length' to > 'yesIReallyWantToKnowTheExactLengthOfThisListSoPleaseCalculateItForMe' > to reduce performance bugs caused by naive uses of length. genericYesIReallyWantToKnowTheExactLengthOfThisListSoPleaseCalculateItForMe Another option is to rename Data.List to Data.List.YesIKnowThisIsNotAnArray. Cheers, Andrew Bromage From iaefai at me.com Mon Nov 23 02:35:00 2009 From: iaefai at me.com (Jeffrey Drake) Date: Mon Nov 23 02:10:12 2009 Subject: [Haskell-beginners] FFI and Cabal Message-ID: <91887885400682927252573119286481217153-Webmail@me.com> I am trying to use FFI to access some windows console functions via two simple C functions I created. Essentially my module looks like is this: {-# CFILES mouse.c #-} {-# LANGUAGE ForeignFunctionInterface #-} module Mouse where -- import Foreign import Foreign.C.Types foreign import ccall unsafe "mouse.h SetupConsole" c_setupConsole :: IO CInt foreign import ccall unsafe "mouse.h MouseEvent" c_mouseEvent :: IO CInt setupConsole :: IO Bool setupConsole = do c <- c_setupConsole return $ if c == 0 then True else False mouseEvent :: IO (Maybe (Int, Int)) mouseEvent = do c <- c_mouseEvent let d = toInteger c let e = (fromInteger d)::Int return $ if e < 0 then Nothing else Just (e `mod` 256, e `div` 256) It seems to compile fine. The problem comes when I need to link. Linking dist\build\BoardGames\BoardGames.exe ... dist\build\BoardGames\BoardGames-tmp\Mouse.o:fake:(.text+0x15): undefined reference to `SetupConsole' dist\build\BoardGames\BoardGames-tmp\Mouse.o:fake:(.text+0x11d): undefined reference to `MouseEvent' collect2: ld returned 1 exit status The problem seems obvious - it isn't compiling OR linking mouse.c which is this: #include int SetupConsole() { HANDLE hStdin; DWORD fdwMode, fdwSaveOldMode; int counter=0; hStdin = GetStdHandle(((DWORD)-10)); if (hStdin == ((HANDLE)(LONG_PTR)-1)) return -3; if (! GetConsoleMode(hStdin, &fdwSaveOldMode) ) return -2; fdwMode = 0x0010; if (! SetConsoleMode(hStdin, fdwMode) ) return -1; return 0; } int MouseEvent() { HANDLE hStdin; INPUT_RECORD irInBuf[128]; short x, y; unsigned i; DWORD cNumRead; static int ignoreNext = 0; hStdin = GetStdHandle(((DWORD)-10)); if (hStdin == ((HANDLE)(LONG_PTR)-1)) return -2; if (!ReadConsoleInputW( hStdin, irInBuf, 128, &cNumRead) ) return -1; for (i = 0; i < cNumRead; i++) { if (irInBuf[i].EventType == 0x0002 && irInBuf[i].Event.MouseEvent.dwEventFlags == 0) { if (ignoreNext == 1) { ignoreNext = 0; return -1; } x = irInBuf[i].Event.MouseEvent.dwMousePosition.X; y = irInBuf[i].Event.MouseEvent.dwMousePosition.Y; ignoreNext = 1; return x + (y << 8); } else { continue; } } return -1; } So far, I have only tested this with MSVC (it works), but not with haskell platform's mingw (which includes windows.h - so I would have to wait for this...) In my cabal file I have: c-sources: mouse.c So that basically sums up what I have, I just don't know how to do this. The cabal documentation says for this directive: c-sources: filename list A list of C source files to be compiled and linked with the Haskell files. Which is what I expected it to do - but to no avail. I should note that when I try to comment out with -- the c-sources line I get this: Linking dist\build\BoardGames\BoardGames.exe ... dist\build\BoardGames\BoardGames-tmp\Main.o:fake:(.text+0x27d): undefined reference to `__stginit_Mouse_' dist\build\BoardGames\BoardGames-tmp\Main.o:fake:(.text+0xb4): undefined reference to `Mouse_a1_info' dist\build\BoardGames\BoardGames-tmp\Main.o:fake:(.text+0xcc): undefined reference to `Mouse_czusetupConsole_info' dist\build\BoardGames\BoardGames-tmp\Main.o:fake:(.text+0xf8): undefined reference to `Mouse_a1_info' dist\build\BoardGames\BoardGames-tmp\Main.o:fake:(.text+0x17a): undefined reference to `Mouse_czusetupConsole_info' dist\build\BoardGames\BoardGames-tmp\Main.o:fake:(.data+0x14): undefined reference to `Mouse_a1_closure' collect2: ld returned 1 exit status Any help that can be offered would be appreciated. I would tell you where to find the project, but patch-tag is being unavailable for me at this time. It is the 'BoardGames' project, under iaefai. Thank you again, iaefai. From dskw_86 at yahoo.com Mon Nov 23 09:31:05 2009 From: dskw_86 at yahoo.com (Dominic Sim) Date: Mon Nov 23 09:06:14 2009 Subject: [Haskell-beginners] Retrieving the decimal portion of a Double Message-ID: <226442.15547.qm@web34506.mail.mud.yahoo.com> ??? Hi all, ??? I am trying to retrieve the decimal portion of a Double. My code is: ??? getDecimal x = x - floor(x) ??? I would expect the following: ??? Main> getDecimal 1.23 ??? 0.23 :: [Double] ??? but instead, I get: ??? Main> getDecimal 1.23 ??? ERROR - Unresolved overloading ??? *** Type?????? : (RealFrac a, Integral a) => a ??? *** Expression : getDecimal 1.23 ??? I have tried adding "getDecimal :: Double -> Double" but it only causes the following message to appear: ??? ERROR file:C:\Documents and Settings\User\file.hs:60 - Instance of Integral Double required for definition of getDecimal ??? How should I define my function so that it'll work? Thanks! ??? Regards, ??? Dom -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091123/1ce2a1dc/attachment.html From shawn-haskell at willden.org Mon Nov 23 10:45:00 2009 From: shawn-haskell at willden.org (Shawn Willden) Date: Mon Nov 23 10:20:13 2009 Subject: [Haskell-beginners] Retrieving the decimal portion of a Double In-Reply-To: <226442.15547.qm@web34506.mail.mud.yahoo.com> References: <226442.15547.qm@web34506.mail.mud.yahoo.com> Message-ID: <200911230845.00819.shawn-haskell@willden.org> On Monday 23 November 2009 07:31:05 am Dominic Sim wrote: > ??? I am trying to retrieve the decimal portion of a Double. My code is: > > ??? getDecimal x = x - floor(x) The problem is that x is a double (or some other kind of floating point or fraction), and "floor x" is an integer, and you can't subtract an integer from a double. To convert "floor x" to a double (or to any other relevant type), use "fromIntegral", like: getDecimal x = x - fromIntegral(floor x) However, what I'd really suggest is that you use: getDecimal x = snd (properFraction x) or, in pointfree style: getDecimal = snd . properFraction Also, the type signature for getDecimal should be: getDecimal :: RealFrac a => a -> a That will allow it to be used with any Real or Fractional type. Shawn. From joe at fixieconsulting.com Mon Nov 23 15:08:46 2009 From: joe at fixieconsulting.com (Joe Van Dyk) Date: Mon Nov 23 14:44:17 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? Message-ID: There's no ubuntu package for 6.10 (only 6.8), and the haskell platform says you need 6.10 installed to build the source package. -- Joe Van Dyk http://fixieconsulting.com From tonymorris at gmail.com Mon Nov 23 15:12:23 2009 From: tonymorris at gmail.com (Tony Morris) Date: Mon Nov 23 14:47:35 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: References: Message-ID: <4B0AECA7.2080803@gmail.com> Hi Joe, You might consider installing the 6.8 package to bootstrap a 6.10 compile. I've done it a few times with high success and pretty straight-forward. Joe Van Dyk wrote: > There's no ubuntu package for 6.10 (only 6.8), and the haskell > platform says you need 6.10 installed to build the source package. > > > > -- Tony Morris http://tmorris.net/ From joe at fixieconsulting.com Mon Nov 23 16:07:19 2009 From: joe at fixieconsulting.com (Joe Van Dyk) Date: Mon Nov 23 15:42:47 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: <4B0AECA7.2080803@gmail.com> References: <4B0AECA7.2080803@gmail.com> Message-ID: That works for the haskell platform? On Mon, Nov 23, 2009 at 12:12 PM, Tony Morris wrote: > Hi Joe, > You might consider installing the 6.8 package to bootstrap a 6.10 > compile. I've done it a few times with high success and pretty > straight-forward. > > Joe Van Dyk wrote: >> There's no ubuntu package for 6.10 (only 6.8), and the haskell >> platform says you need 6.10 installed to build the source package. >> >> >> >> > > -- > Tony Morris > http://tmorris.net/ > > > -- Joe Van Dyk http://fixieconsulting.com From mle+hs at mega-nerd.com Mon Nov 23 16:24:13 2009 From: mle+hs at mega-nerd.com (Erik de Castro Lopo) Date: Mon Nov 23 15:59:27 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: References: Message-ID: <20091124082413.25801bd7.mle+hs@mega-nerd.com> Joe Van Dyk wrote: > There's no ubuntu package for 6.10 (only 6.8), and the haskell > platform says you need 6.10 installed to build the source package. At work we use hardy and to get the latest haskell stuff I did the following: a) Install ghc-6.8. b) Add this to /etc/apt/sources.list: deb-src http://ftp.au.debian.org/debian unstable main non-free contrib c) Get the sources to ghc-6.10 using: apt-get build-dep ghc6 apt-get source ghc-6.10 d) Build the package and install it. e) Apt get the sources to the libraries and build/install them. Its painful and you do need to be reasonably comfortable with building debian packages, but it worked for me. Cheers, Erik -- ---------------------------------------------------------------------- Erik de Castro Lopo http://www.mega-nerd.com/ From juanmaiz at gmail.com Mon Nov 23 17:10:02 2009 From: juanmaiz at gmail.com (Juan Maiz) Date: Mon Nov 23 16:45:14 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: <20091124082413.25801bd7.mle+hs@mega-nerd.com> References: <20091124082413.25801bd7.mle+hs@mega-nerd.com> Message-ID: In Jaunty it's available. On Mon, Nov 23, 2009 at 7:24 PM, Erik de Castro Lopo > wrote: > Joe Van Dyk wrote: > > > There's no ubuntu package for 6.10 (only 6.8), and the haskell > > platform says you need 6.10 installed to build the source package. > > At work we use hardy and to get the latest haskell stuff I did > the following: > > a) Install ghc-6.8. > b) Add this to /etc/apt/sources.list: > > deb-src http://ftp.au.debian.org/debian unstable main non-free > contrib > > c) Get the sources to ghc-6.10 using: > > apt-get build-dep ghc6 > apt-get source ghc-6.10 > > d) Build the package and install it. > e) Apt get the sources to the libraries and build/install them. > > Its painful and you do need to be reasonably comfortable with building > debian packages, but it worked for me. > > Cheers, > Erik > -- > ---------------------------------------------------------------------- > Erik de Castro Lopo > http://www.mega-nerd.com/ > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Juan Maiz Lulkin Flores da Cunha --------------------------------------------------------------------------- Softa Consultoria para Desenvolvimento http://www.softa.com.br http://www.mailee.me - Finalmente e-mail marketing 2.0 http://www.linkedin.com/in/juanmaiz http://workingwithrails.com/recommendation/new/person/9354-juan-maiz ?The most exciting breakthroughs of the 21st century will not occur because of technology but because of an expanding concept of what it means to be human? John Naisbitt -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091123/8160aecf/attachment.html From mle+hs at mega-nerd.com Mon Nov 23 17:55:39 2009 From: mle+hs at mega-nerd.com (Erik de Castro Lopo) Date: Mon Nov 23 17:30:52 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: References: <20091124082413.25801bd7.mle+hs@mega-nerd.com> Message-ID: <20091124095539.d77fae6a.mle+hs@mega-nerd.com> Juan Maiz wrote: > In Jaunty it's available. And in Karmic, but the original poster asked about Hardy. Erik -- ---------------------------------------------------------------------- Erik de Castro Lopo http://www.mega-nerd.com/ From juanmaiz at gmail.com Mon Nov 23 18:31:05 2009 From: juanmaiz at gmail.com (Juan Maiz) Date: Mon Nov 23 18:06:17 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: <20091124095539.d77fae6a.mle+hs@mega-nerd.com> References: <20091124082413.25801bd7.mle+hs@mega-nerd.com> <20091124095539.d77fae6a.mle+hs@mega-nerd.com> Message-ID: But it's worthy to upgrade. :D On Mon, Nov 23, 2009 at 8:55 PM, Erik de Castro Lopo > wrote: > Juan Maiz wrote: > > > In Jaunty it's available. > > And in Karmic, but the original poster asked about Hardy. > > Erik > -- > ---------------------------------------------------------------------- > Erik de Castro Lopo > http://www.mega-nerd.com/ > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Juan Maiz Lulkin Flores da Cunha --------------------------------------------------------------------------- Softa Consultoria para Desenvolvimento http://www.softa.com.br http://www.mailee.me - Finalmente e-mail marketing 2.0 http://www.linkedin.com/in/juanmaiz http://workingwithrails.com/recommendation/new/person/9354-juan-maiz ?The most exciting breakthroughs of the 21st century will not occur because of technology but because of an expanding concept of what it means to be human? John Naisbitt -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091123/14af753b/attachment.html From mle+hs at mega-nerd.com Mon Nov 23 20:16:24 2009 From: mle+hs at mega-nerd.com (Erik de Castro Lopo) Date: Mon Nov 23 19:51:39 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: References: <20091124082413.25801bd7.mle+hs@mega-nerd.com> <20091124095539.d77fae6a.mle+hs@mega-nerd.com> Message-ID: <20091124121624.067220fc.mle+hs@mega-nerd.com> Juan Maiz wrote: > But it's worthy to upgrade. :D I've got close to 1000 kiosk style machines in the field, with the vast majority being spread out across the US (I live in Australia). These machines have no keyboard, just a network connection (not particularly high bandwidth). How do you propose that I upgrade these machines? What do I do with the machines that fail during upgrade? Upgrading is not always the right answer. Erik -- ---------------------------------------------------------------------- Erik de Castro Lopo http://www.mega-nerd.com/ From juanmaiz at gmail.com Mon Nov 23 20:28:21 2009 From: juanmaiz at gmail.com (Juan Maiz) Date: Mon Nov 23 20:03:30 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: <20091124121624.067220fc.mle+hs@mega-nerd.com> References: <20091124082413.25801bd7.mle+hs@mega-nerd.com> <20091124095539.d77fae6a.mle+hs@mega-nerd.com> <20091124121624.067220fc.mle+hs@mega-nerd.com> Message-ID: Well I think the fact my sentence ended with a :D says everything. On Mon, Nov 23, 2009 at 11:16 PM, Erik de Castro Lopo > wrote: > Juan Maiz wrote: > > > But it's worthy to upgrade. :D > > I've got close to 1000 kiosk style machines in the field, with the > vast majority being spread out across the US (I live in Australia). > These machines have no keyboard, just a network connection (not > particularly high bandwidth). > > How do you propose that I upgrade these machines? What do I do > with the machines that fail during upgrade? > > Upgrading is not always the right answer. > > Erik > -- > ---------------------------------------------------------------------- > Erik de Castro Lopo > http://www.mega-nerd.com/ > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Juan Maiz Lulkin Flores da Cunha --------------------------------------------------------------------------- Softa Consultoria para Desenvolvimento http://www.softa.com.br http://www.mailee.me - Finalmente e-mail marketing 2.0 http://www.linkedin.com/in/juanmaiz http://workingwithrails.com/recommendation/new/person/9354-juan-maiz ?The most exciting breakthroughs of the 21st century will not occur because of technology but because of an expanding concept of what it means to be human? John Naisbitt -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091123/1fd2b478/attachment-0001.html From dav.vire+haskell at gmail.com Tue Nov 24 01:42:57 2009 From: dav.vire+haskell at gmail.com (David Virebayre) Date: Tue Nov 24 01:18:10 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: References: Message-ID: <4c88418c0911232242r6fd5c578p75eae29192af4bff@mail.gmail.com> On Mon, Nov 23, 2009 at 9:08 PM, Joe Van Dyk wrote: > There's no ubuntu package for 6.10 (only 6.8), and the haskell > platform says you need 6.10 installed to build the source package. > When I was on Hardy, I just installed 6.10 from the binary tarball. (Kubuntu) David. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091124/e6342cda/attachment.html From zsolt.ero at gmail.com Tue Nov 24 02:00:52 2009 From: zsolt.ero at gmail.com (Zsolt Ero) Date: Tue Nov 24 01:36:20 2009 Subject: [Haskell-beginners] questions about quickCheck Message-ID: <905fcb430911232300p10b762d2u8d3aae3a083e393@mail.gmail.com> Hi, I have just started learning Haskell this semester, and I have some questions of things which puzzles me: 1. I would like to ask that how is it possible to set quickCheck test numbers to something else then the default 100 passes? I have found an article which says: deepCheck p = check (defaultConfig { configMaxTest = 10000}) p which I tried and it works at a home Ubuntu install but when I tried it at my university network, it says: Not in scope: `check' Not in scope: `defaultConfig' Not in scope: `configMaxTest' Isn't there a way of making quickCheck use a different number by using '==>' functions for example? Is quickCheck p = check (defaultConfig) p? 2. How could I print the result of a complex quickCheck generator? I mean if there is an error is says it, but what if I would like to generate just random expressions which quickCheck can do? Zsolt From zsolt.ero at gmail.com Tue Nov 24 02:11:25 2009 From: zsolt.ero at gmail.com (Zsolt Ero) Date: Tue Nov 24 01:46:53 2009 Subject: [Haskell-beginners] how to install "import Foreign.C.Types( CFloat )" in Ubuntu Message-ID: <905fcb430911232311j166fa301oc9e09708616b73c1@mail.gmail.com> I am trying to run a file, which works well on the university system, but I don't know what do I need to do to make it work on my home Ubuntu system. The particular line which makes the error is: import Foreign.C.Types( CFloat ) And the error is: ----------------------------------------------------------- LSystem.hs:130:4: No instance for (ColorComponent CFloat) arising from a use of `color' at LSystem.hs:130:4-26 Possible fix: add an instance declaration for (ColorComponent CFloat) ..... ------------------------------------------------------------- If I write "import Foreign.C.Types" at the Prelude it says nothing. If I write "import Foreign.C.Types( CFloat )" at the Prelude, it says :1:0: parse error on input `import' What can it be? Cheers, Zsolt From daniel.is.fischer at web.de Tue Nov 24 08:43:43 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Nov 24 08:20:16 2009 Subject: [Haskell-beginners] questions about quickCheck In-Reply-To: <905fcb430911232300p10b762d2u8d3aae3a083e393@mail.gmail.com> References: <905fcb430911232300p10b762d2u8d3aae3a083e393@mail.gmail.com> Message-ID: <200911241443.43549.daniel.is.fischer@web.de> Am Dienstag 24 November 2009 08:00:52 schrieb Zsolt Ero: > Hi, > > I have just started learning Haskell this semester, and I have some > questions of things which puzzles me: > > 1. I would like to ask that how is it possible to set quickCheck test > numbers to something else then the default 100 passes? That depends on whether you're using QuickCheck 1.* or QuickCheck 2.*. In 1.*, you'd use customCheck p = check (defaultConfig{ configMaxTest = whatever }) p -- perhaps you would also want to set other fields of the config, e.g. configMaxFail In 2.*, things have been reorganised, so that QC 2.* is incompatible with 1.*, there you'd use customCheck p = quickCheckWith (stdArgs{ maxSuccess = whatever }) p -- perhaps you also want to set other fields of args, e.g. maxDiscard > > I have found an article which says: > deepCheck p = check (defaultConfig { configMaxTest = 10000}) p > > which I tried and it works at a home Ubuntu install but when I tried > it at my university network, it says: > > Not in scope: `check' > Not in scope: `defaultConfig' > Not in scope: `configMaxTest' Probably QC 1.* at home, QC 2.* at the university. > > Isn't there a way of making quickCheck use a different number by using > '==>' functions for example? Not a good one. > > Is quickCheck p = check (defaultConfig) p? In 1.*, yes, but indirectly. You can verify such things yourself by looking at the docs + source in hackage, e.g. http://hackage.haskell.org/packages/archive/QuickCheck/1.2.0.0/doc/html/src/Test- QuickCheck.html#quickCheck vs. http://hackage.haskell.org/packages/archive/QuickCheck/2.1.0.2/doc/html/src/Test- QuickCheck-Test.html#quickCheck > > 2. How could I print the result of a complex quickCheck generator? I > mean if there is an error is says it, but what if I would like to > generate just random expressions which quickCheck can do? ?? perhaps you want to use verboseCheck in QC 1.* (prints out the tested data), look at QC 2.*'s sources to find how to do it there, maybe sample' could be used. > > Zsolt From daniel.is.fischer at web.de Tue Nov 24 09:00:37 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Nov 24 08:37:11 2009 Subject: [Haskell-beginners] how to install "import Foreign.C.Types( CFloat )" in Ubuntu In-Reply-To: <905fcb430911232311j166fa301oc9e09708616b73c1@mail.gmail.com> References: <905fcb430911232311j166fa301oc9e09708616b73c1@mail.gmail.com> Message-ID: <200911241500.37777.daniel.is.fischer@web.de> Am Dienstag 24 November 2009 08:11:25 schrieb Zsolt Ero: > I am trying to run a file, which works well on the university system, > but I don't know what do I need to do to make it work on my home > Ubuntu system. > > The particular line which makes the error is: > import Foreign.C.Types( CFloat ) > > And the error is: > ----------------------------------------------------------- > LSystem.hs:130:4: > No instance for (ColorComponent CFloat) > arising from a use of `color' at LSystem.hs:130:4-26 > Possible fix: > add an instance declaration for (ColorComponent CFloat) > ..... > ------------------------------------------------------------- The problem is not Foreign.C.Types, it's in your OpenGL lib. Probably different versions at home and university. Try adding instance ColorComponent CFloat to LSystem.hs If that doesn't work, replacing (color x) with (color $ realToFrac x) in all pertinent places should make it work. > > If I write "import Foreign.C.Types" at the Prelude it says nothing. If > I write "import Foreign.C.Types( CFloat )" at the Prelude, it says > :1:0: parse error on input `import' Yes, the import at the ghci-prompt is restricted, you can only do import Module there, no import lists, no hiding, no import qualified M as P. > > What can it be? > > Cheers, > Zsolt From ezyang at MIT.EDU Tue Nov 24 13:18:06 2009 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Tue Nov 24 12:53:48 2009 Subject: [Haskell-beginners] combinatorial In-Reply-To: <4B09BBA1.2040303@alumni.caltech.edu> References: <4B0911A9.8030208@alumni.caltech.edu> <1258913625-sup-9282@ezyang> <4B09BBA1.2040303@alumni.caltech.edu> Message-ID: <1259086537-sup-7822@ezyang> Excerpts from Michael Mossey's message of Sun Nov 22 17:30:57 -0500 2009: > I'm not totally exactly sure what you mean here, but my evaluation function > can in fact evaluate phrases of any length. Say I have [A, B] which evaluates to 3. If I want to know the score of [A, B, C], I can't say, "Oh, but remember that [A, B] is 3." It's not a fold, essentially. > Here's what I had in mind for a search algorithm. The idea is to combine > features of greedy and broad search. I have no idea is this is a good idea. > It's just a thought. If by greedy you mean depth-first and by broad you mean breadth-first, this is a certainly a good idea. If you'd like to look it up further, check "beam search". > Let's say we start by evaluating all lists of length 2 and picking those > tied for the maximum score. Then the algorithm is, > > for each input list of length 2 tied for maximum, > make all lists of length 3 that are acceptable (that don't return > Nothing when evaluated) > concat all those > evaluate all of them and pick all tied for the maximum > feed into next step (continue with lengths 4..N.) > > The idea is that's a greedy algorithm that still allows for some breadth of > search by looking at ties. In my scoring system there will often be ties. It sounds like you've basically got the algorithm written down, you have to translate it to Haskell. Do you have a specific problem? Cheers, Edward From mpm at alumni.caltech.edu Tue Nov 24 15:50:41 2009 From: mpm at alumni.caltech.edu (Michael Mossey) Date: Tue Nov 24 15:25:53 2009 Subject: [Haskell-beginners] combinatorial In-Reply-To: <1259086537-sup-7822@ezyang> References: <4B0911A9.8030208@alumni.caltech.edu> <1258913625-sup-9282@ezyang> <4B09BBA1.2040303@alumni.caltech.edu> <1259086537-sup-7822@ezyang> Message-ID: <4B0C4721.1070208@alumni.caltech.edu> Edward Z. Yang wrote: > > If by greedy you mean depth-first and by broad you mean breadth-first, > this is a certainly a good idea. If you'd like to look it up further, > check "beam search". > I think I mean that. Thanks for the tip. > > It sounds like you've basically got the algorithm written down, you have to > translate it to Haskell. Do you have a specific problem? > No, I think I've got it now, but it is always interesting to me to see what new things I learn when the more experienced members on the list give me their thoughts. I'm just checking if anyone wants to suggest that I'm off course and a better way exists. Thanks, Mike From erm.dot.at at gmail.com Wed Nov 25 21:37:57 2009 From: erm.dot.at at gmail.com (Emile Melnicov) Date: Wed Nov 25 21:24:31 2009 Subject: [Haskell-beginners] Easier alternatives to existential types? Message-ID: <200911260637.57252.erm.dot.at@gmail.com> Hello everyone. I'm trying to write RIFF parser and can't decide what to do with "container" type. "Container" chunk should hold a header (two Word32's), a "type" (Word32 like "WAVE" etc) and a "list" of other chunks. Of course lists can't be used because we have far more than one chunk types. What can I do with this? I discovered existentials for myself recently, but those could be too hard for me yet. It feels like I'm missing something very obvious here. Thanks for attention. -- Emile. From felipe.lessa at gmail.com Wed Nov 25 22:41:40 2009 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Wed Nov 25 22:16:47 2009 Subject: [Haskell-beginners] Easier alternatives to existential types? In-Reply-To: <200911260637.57252.erm.dot.at@gmail.com> References: <200911260637.57252.erm.dot.at@gmail.com> Message-ID: <20091126034140.GB32370@kira.casa> On Thu, Nov 26, 2009 at 06:37:57AM +0400, Emile Melnicov wrote: > I'm trying to write RIFF parser and can't decide what to do with > "container" type. "Container" chunk should hold a header (two > Word32's), a "type" (Word32 like "WAVE" etc) and a "list" of other chunks. > Of course lists can't be used because we have far more than one chunk > types. What can I do with this? data Header = H {fieldAbc :: Word32 ,filedXyz :: Word32} data Type = AU | WAVE | ... data ContainerChunk = Chunk Header Type [ContainerChunk] Well, yes, I know that almost certanly that was not what you were thinking when you wrote the question. The code above is how I interpreted your question. I'm writing it so that you can clarify the question if the others don't understand as well. Maybe, something like this? data WaveChunk = Wave {...} data AuChunk = Au {...} data Container = ...any chunk above... doSomethingWillAllThoseFiles :: [Container] -> IO () You may want to keep it simple and just use data Container = TypeWave WaveChunk | TypeAu AuChunk If you really want existentials, though, I'd recommend using GADT syntax as in class Chunk c where ... instance Chunk WaveChunk where ... instance Chunk AuChunk where ... data Container where AudioChunk :: Chunk c => c -> Container x,y :: Container x = AudioChunk (Wave {...}) y = AudioChunk (Au {...}) f :: Chunk c => c -> IO () f = ... g :: Container -> IO () g (AudioChunk c) = f c -- pattern match brings (Chunk c) into context. Note that 'c' above doesn't appear in the type of the Container. This roughly means that it will be existentially qualified. HTH! -- Felipe. From erm.dot.at at gmail.com Thu Nov 26 13:01:32 2009 From: erm.dot.at at gmail.com (Emile Melnicov) Date: Thu Nov 26 12:36:45 2009 Subject: [Haskell-beginners] Easier alternatives to existential types? Message-ID: <200911262201.32626.erm.dot.at@gmail.com> > Well, yes, I know that almost certanly that was not what you > were thinking when you wrote the question. Sorry, I should include my code snippet indeed. data Chunk a = Chunk { cHeader :: Header, cData :: a } data Header = Header { hID :: Word32, hSize :: Word32 } data Format = Format { ... } newtype Data = Data ByteString h :: Header ... formatChunk :: Chunk Format ... dataChunk :: Chunk Data ... data Container a = Container { ctHeader :: Header, ctType :: Word32, ctContent :: [Chunk a] } -- Very naive. containerChunk :: Container a containerChunk = Container h 42 [formatChunk, dataChunk] I'm interested in common pattern used in Haskell for this kind of problems. > If you really want existentials, though, I'd recommend using > GADT syntax OK, I'll try it out. I'm already know about GADT's, but can't catch the difference between regular Algebraic Data Types and Generalised ones (in terms of disjoint union etc.). Can you recommend some paper where GADT's are described, but without very deep mathematical entities? From patrick.leboutillier at gmail.com Thu Nov 26 13:23:53 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Thu Nov 26 12:58:53 2009 Subject: [Haskell-beginners] FFI: FinalizerPtr and freeHaskellFunPtr Message-ID: Hi, I'm trying to write a binding to a C library, and so far here is the code I have: {-# LANGUAGE ForeignFunctionInterface #-} import Foreign.Ptr import Foreign.ForeignPtr newtype C_mlp_context = C_mlp_context (Ptr C_mlp_context) data MLPContext = MLPContext !(ForeignPtr C_mlp_context) deriving (Show) foreign import ccall "wrapper" makeFinalizer :: (Ptr a -> IO ()) -> IO (FinalizerPtr a) foreign import ccall unsafe "mlp.h mlp_context_new" c_new :: IO (Ptr C_mlp_context) new :: IO MLPContext new = do mlp_context <- c_new fin <- mlp_context_finalizer fctx <- newForeignPtr fin mlp_context return $ MLPContext fctx mlp_context_finalizer :: IO (FinalizerPtr C_mlp_context) mlp_context_finalizer = do makeFinalizer $ \ctx -> do c_delete ctx foreign import ccall unsafe "mlp.h mlp_context_delete" c_delete :: Ptr C_mlp_context -> IO () main = do ctx <- new putStrLn $ show ctx This seems to work as expected, but I read that I'm supposed to call freeHaskellFunPtr on the finalizer when I'm done with it. However I don't know how I can do this since it is called by the GC... Can anyone offer any advice? Thanks, Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From byorgey at seas.upenn.edu Thu Nov 26 13:41:41 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Thu Nov 26 13:16:40 2009 Subject: [Haskell-beginners] Easier alternatives to existential types? In-Reply-To: <200911262201.32626.erm.dot.at@gmail.com> References: <200911262201.32626.erm.dot.at@gmail.com> Message-ID: <20091126184141.GA2268@seas.upenn.edu> On Thu, Nov 26, 2009 at 10:01:32PM +0400, Emile Melnicov wrote: > > Well, yes, I know that almost certanly that was not what you > > were thinking when you wrote the question. > > Sorry, I should include my code snippet indeed. > > data Chunk a = Chunk { cHeader :: Header, cData :: a } > data Header = Header { hID :: Word32, hSize :: Word32 } > data Format = Format { ... } > newtype Data = Data ByteString > > h :: Header > ... > formatChunk :: Chunk Format > ... > dataChunk :: Chunk Data > ... > > data Container a = > Container { ctHeader :: Header, ctType :: Word32, > ctContent :: [Chunk a] } Do you *really* need 'Chunk' to be able to hold *any* type of data? Or are there just a few alternatives? If there are only a few alternatives, you can put the alternatives together in a data type, like this: data Content = ConH Header | ConD Data | ... other alternatives ... -- Chunk is no longer polymorphic data Chunk = Chunk { cHeader :: Header, cData :: Content } Then you can pattern-match on things of type Content to see which sort of content it is. Existential types are not required unless you really want to be able to put any type of content at all inside a Chunk. -Brent From zsolt.ero at gmail.com Thu Nov 26 14:20:03 2009 From: zsolt.ero at gmail.com (Zsolt Ero) Date: Thu Nov 26 13:55:22 2009 Subject: [Haskell-beginners] some help on do and preservingMatrix Message-ID: <905fcb430911261120m6f29a058yadcee09fc8534f15@mail.gmail.com> Could someone point me to some help on how does "do" work and how does preservingMatrix? I am trying to write a program starting from the OpenGL tutorial on the wiki, but I never used do's. My very basic question is that how do I generally repeat a command many times? I understand "do" can do it, but it's not clear to me how to use it and how it works. So if I would like to write the following in one line, how could I write it?: spiral 0.7 spiral 0.8 spiral 0.9 spiral 1.0 I don't understand in which cases I can use "map something [0.7,0.8..1]" and in which cases I need do and how could I map using do. >From the tutorial, I could write this line, which works, but I don't really know what does mapM_ and preservingMatrix do. mapM_ (\x -> preservingMatrix $ do scale x x (1::GLfloat) rotate (x*(200)) $ Vector3 0 0 (1::GLfloat) spiral ((sin(a/50))^2/2+0.5) ) $ ([0.5,0.6..1::GLfloat]) Zsolt From stephen.tetley at gmail.com Thu Nov 26 15:01:19 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Thu Nov 26 14:36:21 2009 Subject: [Haskell-beginners] Easier alternatives to existential types? In-Reply-To: <20091126184141.GA2268@seas.upenn.edu> References: <200911262201.32626.erm.dot.at@gmail.com> <20091126184141.GA2268@seas.upenn.edu> Message-ID: <5fdc56d70911261201y6540e14eo56acea6d1a4cb319@mail.gmail.com> 2009/11/26 Brent Yorgey : > Do you *really* need 'Chunk' to be able to hold *any* type of data? > Or are there just a few alternatives? ?If there are only a few > alternatives, you can put the alternatives together in a data type, > like this: Horribly enough, RIFF files do seem to support any type of data. A processor of RIFF files would presumably parse chunk types that it knows to expect and discard the rest. Data.Dynamic from the Hierarchical libs shipped with GHC is another option. Or a home brewed union type: data Chunk = WaveChunk { ... } | AuChunk { ... } | UnintrepretedChunk ByteString Best wishes Stephen From josh.bronson at gmail.com Thu Nov 26 23:06:21 2009 From: josh.bronson at gmail.com (Josh Bronson) Date: Thu Nov 26 22:41:21 2009 Subject: [Haskell-beginners] fail: wxhaskell with cabal Message-ID: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> Greetings Haskellers, Happy Thanksgiving! I'm using Ubuntu 9.10. I've performed the following steps: # apt-get install ghc6 I then successfully did a local install of the Haskell platform in ~/mine/install Now I am trying to get wxhaskell to install: $ cabal install wx [snip] Configuring wxcore-0.12.1.2... setup: Missing dependencies on foreign libraries: * Missing C libraries: wx_baseu-2.8, wx_baseu_net-2.8, wx_baseu_xml-2.8 This problem can usually be solved by installing the system packages that provide these libraries (you may need the "-dev" versions). If the libraries are already installed but in a non-standard location then you can use the flags --extra-include-dirs= and --extra-lib-dirs= to specify where they are. cabal: Error: some packages failed to install: wx-0.12.1.2 depends on wxcore-0.12.1.2 which failed to install. wxcore-0.12.1.2 failed during the configure step. The exception was: exit: ExitFailure 1 $ ls /usr/lib/libwx* /usr/lib/libwx_baseu-2.8.so /usr/lib/libwx_baseu_net-2.8.so.0.6.0 /usr/lib/libwx_baseu-2.8.so.0 /usr/lib/libwx_baseu_xml-2.8.so /usr/lib/libwx_baseu-2.8.so.0.6.0 /usr/lib/libwx_baseu_xml-2.8.so.0 /usr/lib/libwx_baseu_net-2.8.so /usr/lib/libwx_baseu_xml-2.8.so.0.6.0 /usr/lib/libwx_baseu_net-2.8.so.0 It looks like the libraries are there to me! any ideas? From daniel.is.fischer at web.de Thu Nov 26 23:19:12 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Nov 26 22:55:35 2009 Subject: [Haskell-beginners] fail: wxhaskell with cabal In-Reply-To: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> References: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> Message-ID: <200911270519.12238.daniel.is.fischer@web.de> Am Freitag 27 November 2009 05:06:21 schrieb Josh Bronson: > Greetings Haskellers, > > Happy Thanksgiving! I'm using Ubuntu 9.10. I've performed the following > steps: > > # apt-get install ghc6 > > I then successfully did a local install of the Haskell platform in > ~/mine/install > > Now I am trying to get wxhaskell to install: > > $ cabal install wx > [snip] > Configuring wxcore-0.12.1.2... > setup: Missing dependencies on foreign libraries: > * Missing C libraries: wx_baseu-2.8, wx_baseu_net-2.8, wx_baseu_xml-2.8 > This problem can usually be solved by installing the system packages that > provide these libraries (you may need the "-dev" versions). If the > libraries are already installed but in a non-standard location then you can > use the flags --extra-include-dirs= and --extra-lib-dirs= to specify where > they are. cabal: Error: some packages failed to install: > wx-0.12.1.2 depends on wxcore-0.12.1.2 which failed to install. > wxcore-0.12.1.2 failed during the configure step. The exception was: > exit: ExitFailure 1 > > $ ls /usr/lib/libwx* > /usr/lib/libwx_baseu-2.8.so /usr/lib/libwx_baseu_net-2.8.so.0.6.0 > /usr/lib/libwx_baseu-2.8.so.0 /usr/lib/libwx_baseu_xml-2.8.so > /usr/lib/libwx_baseu-2.8.so.0.6.0 /usr/lib/libwx_baseu_xml-2.8.so.0 > /usr/lib/libwx_baseu_net-2.8.so /usr/lib/libwx_baseu_xml-2.8.so.0.6.0 > /usr/lib/libwx_baseu_net-2.8.so.0 > > It looks like the libraries are there to me! any ideas? Perhaps cabal configure uses pkg-config to detect those libraries and you have no wx_***.pc in /usr/lib/pkgconfig ? That occasionally happens to me. From chaddai.fouche at gmail.com Fri Nov 27 01:34:03 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Fri Nov 27 01:09:03 2009 Subject: [Haskell-beginners] fail: wxhaskell with cabal In-Reply-To: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> References: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> Message-ID: On Fri, Nov 27, 2009 at 5:06 AM, Josh Bronson wrote: > Now I am trying to get wxhaskell to install: > > $ cabal install wx > [snip] > Configuring wxcore-0.12.1.2... > setup: Missing dependencies on foreign libraries: > * Missing C libraries: wx_baseu-2.8, wx_baseu_net-2.8, wx_baseu_xml-2.8 > This problem can usually be solved by installing the system packages that > provide these libraries (you may need the "-dev" versions). If the libraries > are already installed but in a non-standard location then you can use the > flags --extra-include-dirs= and --extra-lib-dirs= to specify where they are. > cabal: Error: some packages failed to install: > wx-0.12.1.2 depends on wxcore-0.12.1.2 which failed to install. > wxcore-0.12.1.2 failed during the configure step. The exception was: > exit: ExitFailure 1 > > $ ls /usr/lib/libwx* > /usr/lib/libwx_baseu-2.8.so ? ? ? ?/usr/lib/libwx_baseu_net-2.8.so.0.6.0 > /usr/lib/libwx_baseu-2.8.so.0 ? ? ?/usr/lib/libwx_baseu_xml-2.8.so > /usr/lib/libwx_baseu-2.8.so.0.6.0 ?/usr/lib/libwx_baseu_xml-2.8.so.0 > /usr/lib/libwx_baseu_net-2.8.so ? ?/usr/lib/libwx_baseu_xml-2.8.so.0.6.0 > /usr/lib/libwx_baseu_net-2.8.so.0 > > It looks like the libraries are there to me! any ideas? The shared libraries are there, but did you check if the miscellaneous headers were there ? In other word did you install the libwx*-dev packages as invited to do by cabal in its error message ? -- Jeda? From lev.broido at gmail.com Fri Nov 27 03:44:34 2009 From: lev.broido at gmail.com (Lev Broido) Date: Fri Nov 27 03:19:34 2009 Subject: [Haskell-beginners] Questions on GHCi 6.10.4 + general questions Message-ID: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: DdrController.hs Type: application/octet-stream Size: 4273 bytes Desc: not available Url : http://www.haskell.org/pipermail/beginners/attachments/20091127/601789b6/DdrController-0001.obj From aslatter at gmail.com Fri Nov 27 04:06:52 2009 From: aslatter at gmail.com (Antoine Latter) Date: Fri Nov 27 03:41:50 2009 Subject: [Haskell-beginners] Questions on GHCi 6.10.4 + general questions In-Reply-To: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> References: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> Message-ID: <694519c50911270106g957a31dh8efb326747fd08cd@mail.gmail.com> On Fri, Nov 27, 2009 at 2:44 AM, Lev Broido wrote: > Hi > I am getting the following message : > parse error on input `= > Code in question is attached . > On which line is the error occurring? I'm not used to seeing braces used without semi-colons, so the last bit is hard to follow. The 'where' clause after 'new_state' appears to be at the same indentation level as the 'new_state' declaration, which might confuse GHC. But I'm not sure what the rules are once you start throwing the braces around. Antoine From stephen.tetley at gmail.com Fri Nov 27 04:15:03 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Nov 27 03:50:01 2009 Subject: [Haskell-beginners] Questions on GHCi 6.10.4 + general questions In-Reply-To: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> References: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> Message-ID: <5fdc56d70911270115t4c8e86bak37a801a9b8df6b76@mail.gmail.com> Hi Lev Where clauses don't use braces so that's first problem. Also this line near the end has a problem: curr_bank_state = head . filter (\y -> y == (wr_bank,_) state What should it be doing? Best wishes Stephen 2009/11/27 Lev Broido : > Hi > I am getting the following message : > parse error on input `= > Code in question is attached . > > Another general question on haskell : > I am not sure I understand correctly? the 'where' clause usage , I'll > happily accept comments on the code > > Thanks, > Lev > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > From chaddai.fouche at gmail.com Fri Nov 27 04:22:28 2009 From: chaddai.fouche at gmail.com (=?UTF-8?B?Q2hhZGRhw68gRm91Y2jDqQ==?=) Date: Fri Nov 27 03:57:25 2009 Subject: [Haskell-beginners] Questions on GHCi 6.10.4 + general questions In-Reply-To: <5fdc56d70911270115t4c8e86bak37a801a9b8df6b76@mail.gmail.com> References: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> <5fdc56d70911270115t4c8e86bak37a801a9b8df6b76@mail.gmail.com> Message-ID: On Fri, Nov 27, 2009 at 10:15 AM, Stephen Tetley wrote: > Hi Lev > > Where clauses don't use braces so that's first problem. You are mistaken, where clauses can use braces to avoid having to use layout as all others layout-based constructs in Haskell (do, where, let, case _ of, even the top-level...). But in this case the semicolons are mandatory, since you're explicitly rejecting layout-based rules. That is one problem of this code (use of braces without the semicolons), I didn't check if there were others. -- Jeda? From stephen.tetley at gmail.com Fri Nov 27 04:23:14 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Nov 27 03:58:12 2009 Subject: [Haskell-beginners] Questions on GHCi 6.10.4 + general questions In-Reply-To: <5fdc56d70911270115t4c8e86bak37a801a9b8df6b76@mail.gmail.com> References: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> <5fdc56d70911270115t4c8e86bak37a801a9b8df6b76@mail.gmail.com> Message-ID: <5fdc56d70911270123q5eb4374bs144ae65abd7d11e6@mail.gmail.com> 2009/11/27 Stephen Tetley : > Where clauses don't use braces so that's first problem. Apologies where clauses can have braces - by convention people don't use them. Best wishes Stephen http://www.haskell.org/onlinereport/syntax-iso.html#sect9 From lev.broido at gmail.com Fri Nov 27 04:52:07 2009 From: lev.broido at gmail.com (Lev Broido) Date: Fri Nov 27 04:27:08 2009 Subject: [Haskell-beginners] Questions on GHCi 6.10.4 + general questions In-Reply-To: <607c3f970911270148r173e8505uc20b7ae3544e0eb1@mail.gmail.com> References: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> <5fdc56d70911270115t4c8e86bak37a801a9b8df6b76@mail.gmail.com> <607c3f970911270148r173e8505uc20b7ae3544e0eb1@mail.gmail.com> Message-ID: <607c3f970911270152l18e11b16n4cc4e764c51d093d@mail.gmail.com> On Fri, Nov 27, 2009 at 11:48 AM, Lev Broido wrote: > Thanks for reply . > I used braces , since previous error was on indentation and I wasn't sure > what was wrong . > The intent of the *curr_bank_state = head . filter (\y -> y == > (wr_bank,_) state was > *get first entry (only entry) from list of tuples (Time,BankStateSIngle) > matching condition Time == wr_bank . > > After removing braces the message is > DdrController.hs:112:8: > parse error (possibly incorrect indentation) > Failed, modules loaded: none. > > Thanks, > Lev > > > On Fri, Nov 27, 2009 at 11:15 AM, Stephen Tetley > wrote: > >> Hi Lev >> >> Where clauses don't use braces so that's first problem. >> >> Also this line near the end has a problem: >> >> curr_bank_state = head . filter (\y -> y == (wr_bank,_) state >> >> What should it be doing? >> >> Best wishes >> >> Stephen >> >> 2009/11/27 Lev Broido : >> > Hi >> > I am getting the following message : >> > parse error on input `= >> > Code in question is attached . >> > >> > Another general question on haskell : >> > I am not sure I understand correctly the 'where' clause usage , I'll >> > happily accept comments on the code >> > >> > Thanks, >> > Lev >> > >> > >> > _______________________________________________ >> > 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/20091127/217d4493/attachment.html From stephen.tetley at gmail.com Fri Nov 27 05:09:43 2009 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Nov 27 04:44:42 2009 Subject: [Haskell-beginners] Questions on GHCi 6.10.4 + general questions In-Reply-To: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> References: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> Message-ID: <5fdc56d70911270209x57a1f6baxdcf405a4bafb9912@mail.gmail.com> Hi Lev This one compiles with fairly minimal changes The main one is the new_state = ... line near the end has part commented out where there would otherwise be a type error. Also the nest where clause at the end was obscuring a variable binding that you needed, so I've removed the nesting. Pasted from my editor, hopefully, my mail client doesn't mangle the code: module DdrController where {- - DDR controller implements top function drive of original - list of commands . Assuming data is random . - The first version will drive commands from original command list - and adding to each command delta time , corresponding to minimum time - possible to execute -} -- Each command has it's set of attributes type Time = Int data DdrCmd = READ { bank :: Int, col :: Int } | READ_PCH { bank :: Int, col :: Int} | WRITE { bank :: Int, col :: Int} | WRITE_PCH { bank :: Int, col :: Int} | PCH_CMD {bank :: Int} | ACTIVATE {bank :: Int,row :: Int} | PCH_ALL | BST type DdrCommand = (Time,DdrCmd) -- Type of command containing offset -- Using tree to search for bank info data BankStateSingle = Single { bank_id :: Int , last_ras :: Time , last_cas :: Time , last_pch :: Time }; type BankEntry = (Int,BankStateSingle); type BankState = [BankEntry]; -- Check point events data TimingCheckPoint = RAS | CAS | PCH | NONE deriving Show type TimingCondition = (Int,TimingCheckPoint,TimingCheckPoint) -- All possible timing constraints data (Num a,Show a) => TimingParams a = TRP a | TRCD a | TRAS a -- Function to initialize timing params -- Randomly generates -- Create list of entries init_bank_set :: [BankStateSingle] -> BankState init_bank_set ba_list = zip [0..((length ba_list)-1)] ba_list timing_configuration :: [(Int,TimingCheckPoint,TimingCheckPoint)] timing_configuration = [ {-tRCD-}(4,RAS,CAS) , {-tRC-} (10,RAS,RAS),{-tRP-} (2,PCH,RAS)] -- Translation of timing check point cmd2timing_checkpoint :: DdrCmd -> TimingCheckPoint cmd2timing_checkpoint cmd = case cmd of READ _ _ -> CAS READ_PCH _ _ -> CAS WRITE _ _ -> CAS WRITE_PCH _ _-> CAS PCH_CMD _-> PCH ACTIVATE _ _ -> RAS PCH_ALL -> PCH BST -> NONE -- Return method from bank Id to bank selector func bank_timing_update :: Time -> TimingCheckPoint -> BankStateSingle -> BankStateSingle bank_timing_update time chk_point bank_state = new_bank_state where new_bank_state = case chk_point of RAS -> bank_state { last_ras = time } CAS -> bank_state { last_cas = time } PCH -> bank_state { last_pch = time } -- Change entry in list with other one if condition is met --upd_list :: (a -> Bool)->a->[a]->[a] --upd_list = () -- Calculate cmd delay and update bank state -- For each cmd define whether this is RAS,CAS or PCH command -- For each cmd , find bank it refers to -- For bank calculate new timing offset based on last occurrence beginning of arc -- and longest arc to satisfy updateCmdDelay :: DdrCommand -> BankState -> [TimingCondition] -> (DdrCommand,BankState) -- There are separate cases for commands -- PCH_ALL works on all banks and thus could not be issued before precharge -- timing ark is met for all cases updateCmdDelay (time,PCH_ALL) state timing = undefined updateCmdDelay (time,BST) state timing = ((time,BST),state) updateCmdDelay (time,(WRITE wr_bank wr_col)) state timing = -- Get all timing arcs to 'cmd2timing_checkpoint -- Find maximum by folding of delays and -- ((new_time,(WRITE wr_bank wr_col)),new_state) where { --new_state = num2bank wr_bank; new_time = if (earliest_time > time ) then earliest_time else time; new_state = (take ( wr_bank ) state) ++ {- [(wr_bank,curr_bank_state)] ++ -} (drop (wr_bank + 2) state); earliest_time = last_event_occur + (foldl max 0 delays); delays = [ time | (time,_,endpoint) <- timing ]; last_event_occur = case endpoint of { RAS -> last_ras $ snd curr_bank_state ; CAS -> last_cas $ snd curr_bank_state ; PCH -> last_pch $ snd curr_bank_state } ; -- Blabla endpoint = cmd2timing_checkpoint (WRITE wr_bank wr_col); curr_bank_state = head $ filter (\y -> fst y == wr_bank) state -- Update one of mields : last_ras,last_cas,last_pch -- For each bank } From lev.broido at gmail.com Fri Nov 27 05:20:57 2009 From: lev.broido at gmail.com (Lev Broido) Date: Fri Nov 27 04:55:56 2009 Subject: [Haskell-beginners] Questions on GHCi 6.10.4 + general questions In-Reply-To: <5fdc56d70911270209x57a1f6baxdcf405a4bafb9912@mail.gmail.com> References: <607c3f970911270044u16eb715fjdef389497d54b83b@mail.gmail.com> <5fdc56d70911270209x57a1f6baxdcf405a4bafb9912@mail.gmail.com> Message-ID: <607c3f970911270220h66ac756crc6596ba6ede38c9b@mail.gmail.com> Thank you very match On Fri, Nov 27, 2009 at 12:09 PM, Stephen Tetley wrote: > Hi Lev > > This one compiles with fairly minimal changes > > The main one is the new_state = ... line near the end has part > commented out where there would otherwise be a type error. > > Also the nest where clause at the end was obscuring a variable binding > that you needed, so I've removed the nesting. > > Pasted from my editor, hopefully, my mail client doesn't mangle the code: > > module DdrController where > {- > - DDR controller implements top function drive of original > - list of commands . Assuming data is random . > - The first version will drive commands from original command list > - and adding to each command delta time , corresponding to minimum time > - possible to execute > -} > > -- Each command has it's set of attributes > type Time = Int > > > data DdrCmd = > READ { bank :: Int, col :: Int } | > READ_PCH { bank :: Int, col :: Int} | > WRITE { bank :: Int, col :: Int} | > WRITE_PCH { bank :: Int, col :: Int} | > PCH_CMD {bank :: Int} | > ACTIVATE {bank :: Int,row :: Int} | > PCH_ALL | > BST > > type DdrCommand = (Time,DdrCmd) -- Type of command containing offset > > > -- Using tree to search for bank info > data BankStateSingle = Single { bank_id :: Int , last_ras :: Time , > last_cas :: Time , last_pch :: Time }; > > type BankEntry = (Int,BankStateSingle); > type BankState = [BankEntry]; > > > > -- Check point events > data TimingCheckPoint = RAS | CAS | PCH | NONE deriving Show > > > > type TimingCondition = (Int,TimingCheckPoint,TimingCheckPoint) > -- All possible timing constraints > data (Num a,Show a) => TimingParams a = TRP a | TRCD a | TRAS a > > -- Function to initialize timing params > -- Randomly generates > > -- Create list of entries > init_bank_set :: [BankStateSingle] -> BankState > init_bank_set ba_list = zip [0..((length ba_list)-1)] ba_list > > timing_configuration :: [(Int,TimingCheckPoint,TimingCheckPoint)] > timing_configuration = [ {-tRCD-}(4,RAS,CAS) , {-tRC-} > (10,RAS,RAS),{-tRP-} (2,PCH,RAS)] > > > -- Translation of timing check point > cmd2timing_checkpoint :: DdrCmd -> TimingCheckPoint > cmd2timing_checkpoint cmd = case cmd of > READ _ _ -> CAS > READ_PCH _ _ -> CAS > WRITE _ _ -> CAS > WRITE_PCH _ _-> CAS > PCH_CMD _-> PCH > ACTIVATE _ _ -> RAS > PCH_ALL -> PCH > BST -> NONE > > -- Return method from bank Id to bank selector func > > bank_timing_update :: Time -> TimingCheckPoint -> BankStateSingle -> > BankStateSingle > bank_timing_update time chk_point bank_state = new_bank_state > where > new_bank_state = > case chk_point of > RAS -> bank_state { last_ras = time } > CAS -> bank_state { last_cas = time } > PCH -> bank_state { last_pch = time } > > > -- Change entry in list with other one if condition is met > --upd_list :: (a -> Bool)->a->[a]->[a] > --upd_list = () > > -- Calculate cmd delay and update bank state > -- For each cmd define whether this is RAS,CAS or PCH command > -- For each cmd , find bank it refers to > -- For bank calculate new timing offset based on last occurrence > beginning of arc > -- and longest arc to satisfy > > updateCmdDelay :: DdrCommand -> BankState -> [TimingCondition] -> > (DdrCommand,BankState) > -- There are separate cases for commands > -- PCH_ALL works on all banks and thus could not be issued before > precharge > -- timing ark is met for all cases > updateCmdDelay (time,PCH_ALL) state timing = undefined > updateCmdDelay (time,BST) state timing = ((time,BST),state) > > updateCmdDelay (time,(WRITE wr_bank wr_col)) state timing = > > -- Get all timing arcs to 'cmd2timing_checkpoint > > -- Find maximum by folding of delays and > > -- > > ((new_time,(WRITE wr_bank wr_col)),new_state) > > where { > --new_state = num2bank wr_bank; > > new_time = if (earliest_time > time ) then earliest_time else time; > > > new_state = (take ( wr_bank ) state) ++ {- > [(wr_bank,curr_bank_state)] ++ -} (drop (wr_bank + 2) state); > > earliest_time = last_event_occur + (foldl max 0 delays); > > delays = [ time | (time,_,endpoint) <- timing ]; > > last_event_occur = case endpoint of > { RAS -> last_ras $ snd curr_bank_state ; > CAS -> last_cas $ snd curr_bank_state ; > PCH -> last_pch $ snd curr_bank_state } ; > > -- Blabla > endpoint = cmd2timing_checkpoint (WRITE wr_bank wr_col); > > > curr_bank_state = head $ filter (\y -> fst y == wr_bank) state > > -- Update one of mields : last_ras,last_cas,last_pch > -- For each bank > > > } > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20091127/d2366688/attachment-0001.html From josh.bronson at gmail.com Fri Nov 27 11:41:14 2009 From: josh.bronson at gmail.com (Josh Bronson) Date: Fri Nov 27 11:16:13 2009 Subject: [Haskell-beginners] fail: wxhaskell with cabal In-Reply-To: References: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> Message-ID: <9c9cf8a00911270841u277ea6d8wf4b5464d650597b@mail.gmail.com> Yes, I've installed libwxbase2.8-dev: $ dpkg -l 'libwxbase2.8*' Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Cfg-files/Unpacked/Failed-cfg/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Description +++-==============-==============-============================================ ii libwxbase2.8-0 2.8.10.1-0ubun wxBase library (runtime) - non-GUI support c ii libwxbase2.8-d 2.8.10.1-0ubun wxBase library (development) - non-GUI suppo $ dpkg -L libwxbase2.8-dev /. /usr /usr/lib /usr/lib/wx /usr/lib/wx/include /usr/lib/wx/include/base-unicode-release-2.8 /usr/lib/wx/include/base-unicode-release-2.8/wx /usr/lib/wx/include/base-unicode-release-2.8/wx/setup.h /usr/lib/wx/config /usr/lib/wx/config/base-unicode-release-2.8 /usr/share /usr/share/doc /usr/share/doc/libwxbase2.8-dev /usr/share/doc/libwxbase2.8-dev/changelog.gz /usr/share/doc/libwxbase2.8-dev/copyright /usr/share/doc/libwxbase2.8-dev/changelog.Debian.gz /usr/lib/libwx_baseu-2.8.so /usr/lib/libwx_baseu_net-2.8.so /usr/lib/libwx_baseu_xml-2.8.so On Fri, Nov 27, 2009 at 12:34 AM, Chadda? Fouch? wrote: > On Fri, Nov 27, 2009 at 5:06 AM, Josh Bronson wrote: >> Now I am trying to get wxhaskell to install: >> >> $ cabal install wx >> [snip] >> Configuring wxcore-0.12.1.2... >> setup: Missing dependencies on foreign libraries: >> * Missing C libraries: wx_baseu-2.8, wx_baseu_net-2.8, wx_baseu_xml-2.8 >> This problem can usually be solved by installing the system packages that >> provide these libraries (you may need the "-dev" versions). If the libraries >> are already installed but in a non-standard location then you can use the >> flags --extra-include-dirs= and --extra-lib-dirs= to specify where they are. >> cabal: Error: some packages failed to install: >> wx-0.12.1.2 depends on wxcore-0.12.1.2 which failed to install. >> wxcore-0.12.1.2 failed during the configure step. The exception was: >> exit: ExitFailure 1 >> >> $ ls /usr/lib/libwx* >> /usr/lib/libwx_baseu-2.8.so ? ? ? ?/usr/lib/libwx_baseu_net-2.8.so.0.6.0 >> /usr/lib/libwx_baseu-2.8.so.0 ? ? ?/usr/lib/libwx_baseu_xml-2.8.so >> /usr/lib/libwx_baseu-2.8.so.0.6.0 ?/usr/lib/libwx_baseu_xml-2.8.so.0 >> /usr/lib/libwx_baseu_net-2.8.so ? ?/usr/lib/libwx_baseu_xml-2.8.so.0.6.0 >> /usr/lib/libwx_baseu_net-2.8.so.0 >> >> It looks like the libraries are there to me! any ideas? > > The shared libraries are there, but did you check if the miscellaneous > headers were there ? In other word did you install the libwx*-dev > packages as invited to do by cabal in its error message ? > > -- > Jeda? > From josh.bronson at gmail.com Fri Nov 27 11:51:08 2009 From: josh.bronson at gmail.com (Josh Bronson) Date: Fri Nov 27 11:26:05 2009 Subject: [Haskell-beginners] fail: wxhaskell with cabal In-Reply-To: <200911270519.12238.daniel.is.fischer@web.de> References: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> <200911270519.12238.daniel.is.fischer@web.de> Message-ID: <9c9cf8a00911270851w69699633l6af25a842bb28643@mail.gmail.com> Hmm, there is no file of the type you mentioned: $ ls /usr/lib/pkgconfig/wx* ls: cannot access /usr/lib/pkgconfig/wx*: No such file or directory A Google search for "wx pkg-config" appears to reveal that wxwidgets does not support pkg-config, or at least it didn't a few years ago. Lots of people will try "cabal install wx," right? So it seems like that's probably not the problem, but I'm not sure where the code that is generating the following output lives: Configuring wxcore-0.12.1.2... setup: Missing dependencies on foreign libraries: * Missing C libraries: wx_baseu-2.8, wx_baseu_net-2.8, wx_baseu_xml-2.8 I tried untarring ~/.cabal/packages/hackage.haskell.org/wxcore/0.12.1.2/wxcore-0.12.1.2.tar.gz and looking at Setup.hs to no avail. If I could see what test is failing, I could probably figure it out. On Thu, Nov 26, 2009 at 10:19 PM, Daniel Fischer wrote: > Am Freitag 27 November 2009 05:06:21 schrieb Josh Bronson: >> Greetings Haskellers, >> >> Happy Thanksgiving! I'm using Ubuntu 9.10. I've performed the following >> steps: >> >> # apt-get install ghc6 >> >> I then successfully did a local install of the Haskell platform in >> ~/mine/install >> >> Now I am trying to get wxhaskell to install: >> >> $ cabal install wx >> [snip] >> Configuring wxcore-0.12.1.2... >> setup: Missing dependencies on foreign libraries: >> * Missing C libraries: wx_baseu-2.8, wx_baseu_net-2.8, wx_baseu_xml-2.8 >> This problem can usually be solved by installing the system packages that >> provide these libraries (you may need the "-dev" versions). If the >> libraries are already installed but in a non-standard location then you can >> use the flags --extra-include-dirs= and --extra-lib-dirs= to specify where >> they are. cabal: Error: some packages failed to install: >> wx-0.12.1.2 depends on wxcore-0.12.1.2 which failed to install. >> wxcore-0.12.1.2 failed during the configure step. The exception was: >> exit: ExitFailure 1 >> >> $ ls /usr/lib/libwx* >> /usr/lib/libwx_baseu-2.8.so ? ? ?/usr/lib/libwx_baseu_net-2.8.so.0.6.0 >> /usr/lib/libwx_baseu-2.8.so.0 ? ?/usr/lib/libwx_baseu_xml-2.8.so >> /usr/lib/libwx_baseu-2.8.so.0.6.0 ?/usr/lib/libwx_baseu_xml-2.8.so.0 >> /usr/lib/libwx_baseu_net-2.8.so ? ?/usr/lib/libwx_baseu_xml-2.8.so.0.6.0 >> /usr/lib/libwx_baseu_net-2.8.so.0 >> >> It looks like the libraries are there to me! any ideas? > > Perhaps cabal configure uses pkg-config to detect those libraries and you have no > wx_***.pc in /usr/lib/pkgconfig ? > That occasionally happens to me. > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From daniel.is.fischer at web.de Fri Nov 27 14:07:39 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Nov 27 13:44:09 2009 Subject: [Haskell-beginners] fail: wxhaskell with cabal In-Reply-To: <9c9cf8a00911270851w69699633l6af25a842bb28643@mail.gmail.com> References: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> <200911270519.12238.daniel.is.fischer@web.de> <9c9cf8a00911270851w69699633l6af25a842bb28643@mail.gmail.com> Message-ID: <200911272007.40932.daniel.is.fischer@web.de> Am Freitag 27 November 2009 17:51:08 schrieb Josh Bronson: > Hmm, there is no file of the type you mentioned: > > $ ls /usr/lib/pkgconfig/wx* > ls: cannot access /usr/lib/pkgconfig/wx*: No such file or directory > > A Google search for "wx pkg-config" appears to reveal that wxwidgets > does not support pkg-config, or at least it didn't a few years ago. > Lots of people will try "cabal install wx," right? Dunno, I just tried, for me it dies with: src/cpp/eljdirdlg.cpp:24:0: warning: ?void wxDirDialogBase::SetStyle(long int)? is deprecated (declared at /usr/include/wx-2.8/wx/dirdlg.h:79) src/cpp/eljdirdlg.cpp: In function ?int wxDirDialog_GetStyle(void*)?: src/cpp/eljdirdlg.cpp:45:0: warning: ?long int wxDirDialogBase::GetStyle() const? is deprecated (declared at /usr/include/wx-2.8/wx/dirdlg.h:78) src/cpp/eljevent.cpp: In function ?int expEVT_DIALUP_CONNECTED()?: src/cpp/eljevent.cpp:1589:0: error: ?wxEVT_DIALUP_CONNECTED? was not declared in this scope src/cpp/eljevent.cpp: In function ?int expEVT_DIALUP_DISCONNECTED()?: src/cpp/eljevent.cpp:1598:0: error: ?wxEVT_DIALUP_DISCONNECTED? was not declared in this scope cabal: Error: some packages failed to install: wx-0.12.1.2 depends on wxcore-0.12.1.2 which failed to install. wxcore-0.12.1.2 failed during the building phase. The exception was: exit: ExitFailure 1 Which reminds me, I've *never* succeeded building wxhaskell, I wonder how many managed. > So it seems like that's probably not the problem, but I'm not sure where the code that > is generating the following output lives: > > Configuring wxcore-0.12.1.2... > setup: Missing dependencies on foreign libraries: > * Missing C libraries: wx_baseu-2.8, wx_baseu_net-2.8, wx_baseu_xml-2.8 > > I tried untarring > ~/.cabal/packages/hackage.haskell.org/wxcore/0.12.1.2/wxcore-0.12.1.2.tar.g >z and looking at Setup.hs to no avail. If I could see what test is > failing, I could probably figure it out. > Specify the locations via --extra-include-dirs and --extra-lib-dirs? From josh.bronson at gmail.com Fri Nov 27 16:22:03 2009 From: josh.bronson at gmail.com (Josh Bronson) Date: Fri Nov 27 15:57:00 2009 Subject: [Haskell-beginners] fail: wxhaskell with cabal In-Reply-To: <200911272007.40932.daniel.is.fischer@web.de> References: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> <200911270519.12238.daniel.is.fischer@web.de> <9c9cf8a00911270851w69699633l6af25a842bb28643@mail.gmail.com> <200911272007.40932.daniel.is.fischer@web.de> Message-ID: <9c9cf8a00911271322u680d5580ydaa87582be4f092c@mail.gmail.com> Ah. Is there a better GUI library to work with? 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 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. From daniel.is.fischer at web.de Fri Nov 27 17:18:55 2009 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Nov 27 16:55:17 2009 Subject: [Haskell-beginners] fail: wxhaskell with cabal In-Reply-To: <9c9cf8a00911271322u680d5580ydaa87582be4f092c@mail.gmail.com> References: <9c9cf8a00911262006g26211e12ld6c09484cf690078@mail.gmail.com> <200911272007.40932.daniel.is.fischer@web.de> <9c9cf8a00911271322u680d5580ydaa87582be4f092c@mail.gmail.com> Message-ID: <200911272318.55725.daniel.is.fischer@web.de> 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 legajid at free.fr Sun Nov 29 12:41:22 2009 From: legajid at free.fr (legajid) Date: Sun Nov 29 12:12:38 2009 Subject: [Haskell-beginners] Pattern matching with one, two or more arguments Message-ID: <4B12B242.9050606@free.fr> Hello, I'm writing a little word game that consists of the following : between a consonant and a vowel, insert "AV" so "fabien" becomes "fAVabAVien". When i type : f "fabine", the result is ok ("fAVabAVinAVe") When i type : f "fabien", the result is fAVabAVie *** exception :prelude empty list Here's my program voyelles="aeiouy" consonnes="bcdfghjklmnpqrstvwxz" est_voyelle x = x `elem` voyelles est_consonne x = x `elem` consonnes --f []=[] ; unuseful - conflict with f a = a f (a:b:c) = case trait a b of True -> a : (" AV " ++ f (b:c)) False -> a : f (b:c) f (a:b) = case trait a (head b) of True -> a : (" EP " ++ f ( b) ) False -> a : f ( b) f a = a -- detect a vowel following a consonant trait a b = est_consonne a && est_voyelle b f (a:b) is never invoked (i wrote EP instead of AV to trace the problem). f(a:b:c) seems to always take precedence over the other patterns. I expect f(a:b:c) to treat words greater than or equal to 3 letters, f(a:b) the last two letters of the word (no third part) and f a the last letter. Another trick : how can i calculate consonnes with a method that makes the difference between the two lists [a..z] and voyelles, rather than writing each consonant. As we can append two lists (++), can we compute the difference between lists, i.e. delete from the first list the elements that are present in the second one ? Last, with Ghci, is it possible to debug my program, especially for recursive functions, because it's hard to follow the successive calls and the parameters that are passed each turn. Greetings, Didier. From deniz.a.m.dogan at gmail.com Sun Nov 29 12:45:01 2009 From: deniz.a.m.dogan at gmail.com (Deniz Dogan) Date: Sun Nov 29 12:20:12 2009 Subject: [Haskell-beginners] Pattern matching with one, two or more arguments In-Reply-To: <4B12B242.9050606@free.fr> References: <4B12B242.9050606@free.fr> Message-ID: <7b501d5c0911290945h5ecbf329g9993072f4db0f34e@mail.gmail.com> 2009/11/29 legajid : > Another trick : how can i calculate consonnes with a method that makes the > difference between ?the two lists [a..z] and ?voyelles, rather ?than writing > each consonant. > As we can append two lists (++), can we compute the difference between > lists, i.e. delete from the first list the elements that are present in the > second one ? Use Data.List.\\ ['a'..'z'] \\ "aoeui" ==> "bcdfghjklmnpqrstvwxyz" -- Deniz Dogan From byorgey at seas.upenn.edu Sun Nov 29 13:13:31 2009 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Nov 29 12:48:23 2009 Subject: [Haskell-beginners] Pattern matching with one, two or more arguments In-Reply-To: <4B12B242.9050606@free.fr> References: <4B12B242.9050606@free.fr> Message-ID: <20091129181331.GA1486@seas.upenn.edu> On Sun, Nov 29, 2009 at 06:41:22PM +0100, legajid wrote: > Hello, > I'm writing a little word game that consists of the following : between a > consonant and a vowel, insert "AV" so "fabien" becomes "fAVabAVien". > > When i type : f "fabine", the result is ok ("fAVabAVinAVe") > When i type : f "fabien", the result is fAVabAVie *** exception :prelude > empty list > > Here's my program > > voyelles="aeiouy" > consonnes="bcdfghjklmnpqrstvwxz" > > est_voyelle x = x `elem` voyelles > est_consonne x = x `elem` consonnes > > --f []=[] ; unuseful - conflict with f a = a > > > -- detect a vowel following a consonant > trait a b = est_consonne a && est_voyelle b > > > > f (a:b) is never invoked (i wrote EP instead of AV to trace the problem). > f(a:b:c) seems to always take precedence over the other patterns. > I expect f(a:b:c) to treat words greater than or equal to 3 letters, f(a:b) > the last two letters of the word (no third part) and f a the last letter. This is not correct. The patern (a:b:c) matches words greater than or equal to TWO letters, not three. In the case of a two-letter word, c is the empty list. For example, the word "in" is ('i':'n':[]). > f (a:b:c) = > case trait a b of > True -> a : (" AV " ++ f (b:c)) > False -> a : f (b:c) > f (a:b) = > case trait a (head b) of > True -> a : (" EP " ++ f ( b) ) > False -> a : f ( b) > f a = a The problem is with the call to 'head b' -- when f is called on a one-letter word, it matches the pattern (a:b) with b the empty list, and the call to 'head' crashes. You do not need to check the trait in this case at all. In fact, you do not need this entire case at all! Just the first case and the third should suffice. -Brent From timothyea at comcast.net Sun Nov 29 16:52:39 2009 From: timothyea at comcast.net (Tim Attwood) Date: Sun Nov 29 16:27:49 2009 Subject: [Haskell-beginners] Re: Pattern matching with one, two or more arguments In-Reply-To: <4B12B242.9050606@free.fr> References: <4B12B242.9050606@free.fr> Message-ID: "legajid" wrote in message news:4B12B242.9050606@free.fr... > Hello, > I'm writing a little word game that consists of the following : between a > consonant and a vowel, insert "AV" so "fabien" becomes "fAVabAVien". > > When i type : f "fabine", the result is ok ("fAVabAVinAVe") > When i type : f "fabien", the result is fAVabAVie *** exception :prelude > empty list > > Here's my program > > voyelles="aeiouy" > consonnes="bcdfghjklmnpqrstvwxz" > > est_voyelle x = x `elem` voyelles > est_consonne x = x `elem` consonnes > > --f []=[] ; unuseful - conflict with f a = a > > f (a:b:c) = > case trait a b of > True -> a : (" AV " ++ f (b:c)) > False -> a : f (b:c) > f (a:b) = > case trait a (head b) of > True -> a : (" EP " ++ f ( b) ) > False -> a : f ( b) > f a = a > > -- detect a vowel following a consonant > trait a b = est_consonne a && est_voyelle b > > > > f (a:b) is never invoked (i wrote EP instead of AV to trace the problem). > f(a:b:c) seems to always take precedence over the other patterns. > I expect f(a:b:c) to treat words greater than or equal to 3 letters, > f(a:b) the last two letters of the word (no third part) and f a the last > letter. > > Another trick : how can i calculate consonnes with a method that makes the > difference between the two lists [a..z] and voyelles, rather than > writing each consonant. > As we can append two lists (++), can we compute the difference between > lists, i.e. delete from the first list the elements that are present in > the second one ? > > Last, with Ghci, is it possible to debug my program, especially for > recursive functions, because it's hard to follow the successive calls and > the parameters that are passed each turn. import Char voyelles = "aeiouyAEIOUY" est_voyelle x = x `elem` voyelles est_consonne x = (isAlpha x) && (x `notElem` voyelles) f :: String -> String f (a:b:c) | trait a b = [a]++"AV"++[b]++(f c) | otherwise = a : f (b:c) f a = a trait a b = (est_consonne a) && (est_voyelle b) From joe at fixieconsulting.com Mon Nov 30 01:39:14 2009 From: joe at fixieconsulting.com (Joe Van Dyk) Date: Mon Nov 30 01:14:23 2009 Subject: [Haskell-beginners] recommended way to get haskell 6.10 installed on ubuntu hardy? In-Reply-To: References: <20091124082413.25801bd7.mle+hs@mega-nerd.com> <20091124095539.d77fae6a.mle+hs@mega-nerd.com> Message-ID: Is it? Hardy is supposed for 5 years (as it's a LTS release). Don't think Jaunty is. On Mon, Nov 23, 2009 at 3:31 PM, Juan Maiz wrote: > But it's worthy to upgrade. :D > > On Mon, Nov 23, 2009 at 8:55 PM, Erik de Castro Lopo > wrote: >> >> Juan Maiz wrote: >> >> > In Jaunty it's available. >> >> And in Karmic, but the original poster asked about Hardy. >> >> Erik >> -- >> ---------------------------------------------------------------------- >> Erik de Castro Lopo >> http://www.mega-nerd.com/ >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners > > > > -- > Juan Maiz Lulkin Flores da Cunha > --------------------------------------------------------------------------- > Softa Consultoria para Desenvolvimento > http://www.softa.com.br > http://www.mailee.me - Finalmente e-mail marketing 2.0 > http://www.linkedin.com/in/juanmaiz > http://workingwithrails.com/recommendation/new/person/9354-juan-maiz > ?The most exciting breakthroughs of the 21st century will not occur because > of technology but because of an expanding concept of what it means to be > human? > John Naisbitt > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > -- Joe Van Dyk http://fixieconsulting.com From patrick.leboutillier at gmail.com Mon Nov 30 16:34:17 2009 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Mon Nov 30 16:09:06 2009 Subject: [Haskell-beginners] Tips for a FFI-wrapped C library? Message-ID: Hi all, I have wrapped, using FFI, a C-library I am writing that calls into different programming languages. I put everything in the IO monad. So far it works as expected but I find the resulting usage code somewhat ugly (especially the bits musing 'sequence'). I tried using finalizers to delete the resources but it couldn't respect my dependencies. Can anyone offer any advice on making it feel more natural in Haskell? Note: The FFI code is available here: http://svn.solucorp.qc.ca/repos/solucorp/mlp/trunk/lib/haskell/ import qualified MLP import qualified MLP.Error import qualified MLP.Context import qualified MLP.Language import qualified MLP.Runtime import qualified MLP.Value import qualified MLP.Object main = do ctx <- MLP.Context.new -- create a context MLP.Context.with ctx $ do lang <- MLP.Language.init ctx "perl" -- init a language, i.e. perl rt <- MLP.Runtime.new ctx lang -- create a runtime for the language MLP.Runtime.loadLibrary ctx rt "calc" -- load a library, i.e. calc.pm val <- MLP.Object.new ctx rt "calc" [] "" -- create a calc object, i.e. my $obj = new calc() ; obj <- MLP.Value.takeObject val -- extract the object from the value MLP.Value.delete ctx val args_add <- sequence [MLP.Value.newLong 2, MLP.Value.newLong 3] args_mul <- sequence [MLP.Value.newDouble 3.5, MLP.Value.newDouble 4.6] val_add <- MLP.Object.callMethod ctx rt obj "add" args_add "" sequence $ map (MLP.Value.delete ctx) args_add val_mul <- MLP.Object.callMethod ctx rt obj "mul" args_mul "" sequence $ map (MLP.Value.delete ctx) args_mul MLP.Object.delete ctx obj MLP.Value.getLong val_add >>= putStrLn . show >> MLP.Value.delete ctx val_add MLP.Value.getDouble val_mul >>= putStrLn . show >> MLP.Value.delete ctx val_mul MLP.Runtime.delete ctx rt MLP.Language.delete ctx lang Thanks, Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From builes.adolfo at googlemail.com Mon Nov 30 17:32:02 2009 From: builes.adolfo at googlemail.com (Adolfo Builes) Date: Wed Dec 2 21:13:26 2009 Subject: [Haskell-beginners] From Functional Dependencies to Type Families 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/20091130/38e9f0bc/attachment.html