Re: [Haskell-cafe] typeclass to select a list element
Hello everyone, I'm still trying to resolve my problem. I try to restate it in a simpler way. Is it possible to write extract and update functions for L ? import Data.Nat data family X (n::Nat) :: * data L (n::Nat) where Q :: L (Succ n) - X n - L n E :: L n extract :: L Zero - X n extract = undefined update :: L Zero - (X n - X n) - L Zero update = undefined Thanks for hints and help paolino 2013/10/7 Paolino paolo.verone...@gmail.com Hello, I'm trying to use a type class to select an element from a list. I would like to have a String CC as a value for l10'. {-# LANGUAGE MultiParamTypeClasses, GADTs,FlexibleInstances, DataKinds ,TypeFamilies, KindSignatures, FlexibleContexts, OverlappingInstances, StandaloneDeriving, UndecidableInstances #-} import Data.Nat import Data.Monoid data family X (n::Nat) :: * data L (n::Nat) where Q :: (Monoid (X n), Show (X n)) = L (Succ n) - X n - L n E :: Monoid (X n) = L n deriving instance Show (L n) data instance X n = String String instance Monoid (X n) where String x `mappend` String y = String $ x `mappend` y mempty = String deriving instance Show (X n) class Compose n n' where compose :: L n - L n - X n' instance Compose n n where compose (Q _ x) (Q _ y) = x `mappend` y compose _ _ = mempty instance Compose n n' where compose (Q x _) (Q y _) = compose x y compose _ _ = mempty l0 :: L Zero l0 = Q (Q E $ String C) $ String A l0' :: L Zero l0' = Q (Q E $ String C) $ String B l10' :: X (Succ Zero) l10' = compose l0 l0' l00' :: X Zero l00' = compose l0 l0' {- *Main l00' String AB *Main l10' String -} Thanks for help. paolino ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] typeclass to select a list element
Hello, I'm trying to use a type class to select an element from a list. I would like to have a String CC as a value for l10'. {-# LANGUAGE MultiParamTypeClasses, GADTs,FlexibleInstances, DataKinds ,TypeFamilies, KindSignatures, FlexibleContexts, OverlappingInstances, StandaloneDeriving, UndecidableInstances #-} import Data.Nat import Data.Monoid data family X (n::Nat) :: * data L (n::Nat) where Q :: (Monoid (X n), Show (X n)) = L (Succ n) - X n - L n E :: Monoid (X n) = L n deriving instance Show (L n) data instance X n = String String instance Monoid (X n) where String x `mappend` String y = String $ x `mappend` y mempty = String deriving instance Show (X n) class Compose n n' where compose :: L n - L n - X n' instance Compose n n where compose (Q _ x) (Q _ y) = x `mappend` y compose _ _ = mempty instance Compose n n' where compose (Q x _) (Q y _) = compose x y compose _ _ = mempty l0 :: L Zero l0 = Q (Q E $ String C) $ String A l0' :: L Zero l0' = Q (Q E $ String C) $ String B l10' :: X (Succ Zero) l10' = compose l0 l0' l00' :: X Zero l00' = compose l0 l0' {- *Main l00' String AB *Main l10' String -} Thanks for help. paolino ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Over general types are too easy to make.
Hello Timothy GADTs let you catch more errors at compile time. With them you can give different types to constructors of the same datatype. regards paolino 2012/8/31 timothyho...@seznam.cz Sure, but that's relying on the promise that you're passing it a valid BadFrog... Consider then: deBadFrog $ BadFrogType (BadBar { badFoo = 1}) -- Původní zpráva -- Od: John Wiegley jo...@newartisans.com Datum: 31. 8. 2012 Předmět: Re: [Haskell-cafe] Over general types are too easy to make. timothyho...@seznam.cz writes: data BadFoo = BadBar{ badFoo::Int} | BadFrog{ badFrog::String, badChicken::Int} This is fine, until we want to write a function that acts on Frogs but not on Bars. The best we can do is throw a runtime error when passed a Bar and not a Foo: You can use wrapper types to solve this: data BadBarType = BadBarType BadFoo data BadFrogType = BadFrogType BadFoo Now you can have: deBadFrog :: BadFrogType - String And call it as: deBadFrog $ BadFrogType (BadFrog { badFrog = Hey, badChicken = 1}) Needless to say, you will have to create helper functions for creating Bars and Frogs, and not allow your BadBar or BadFrog value constructors to be visible outside your module. John ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Dealing poker hands, redux
hello matthew, I commented your gist on github adding the missing pieces with minor fixes. Anyway, I suggest giving up RVar's which are overkill for your task. You could implement your shuffle as an exercise, or use random-shuffle package as I do in the code below. Also I'd avoid State monad for such a simple task of remembering the remaining deck after each deal. You should switch to using a monad after you are comfortable with pure code. import Control.Arrow import System.Random.Shuffle import Control.Monad.Random.Class -- |Cards. data Suit = Hearts | Diamonds | Clubs | Spades deriving (Enum, Bounded, Show) data Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King deriving (Enum, Bounded, Show) data Card = Flat Rank Suit | Jolly deriving Show type Deck = [Card] type Hand = [Card] deck :: Deck deck = [ Flat s r | s - [minBound .. maxBound] , r - [minBound .. maxBound]]++ [Jolly,Jolly] -- deal n cards m times from the given deck and return the rest along the hands dealHands :: Int - Int - Deck - ([Hand],Deck) dealHands n m = (map (take n) *** head) . splitAt m . iterate (drop n) -- same as dealHands, but shuffle the deck before randomDealHands :: (Functor m, MonadRandom m) = Int - Int - Deck - m ([Hand],Deck) randomDealHands n m xs = dealHands n m `fmap` shuffleM xs test :: IO ([Hand],Deck) test = randomDealHands 5 4 $ deck ++ deck You can run randomDealHands in IO (ghci prompt) as IO is both a Functor and a MonadRandom instance regards paolino 2012/8/25 Matthew wonderzom...@gmail.com So I've finally got some code which shuffles a deck of cards and deals out an arbitrary number of hands. https://gist.github.com/19916435df2b116e0edc type DealerState = State [Card] [[Card]] deck :: [Card] deck = [ (s, r) | s - suits, r - ranks ] shuffleDeck :: Int - RVar [Card] shuffleDeck n = shuffle $ concat $ replicate n deck deal :: Int - ([[Card]] - DealerState) deal n = \xs - state $ \s - (xs ++ [take n s], drop n s) -- |Deal a number of hands a number of cards each. dealHands :: Int - Int - ([[Card]] - DealerState) dealHands hs cs = foldr1 (=) $ replicate hs (deal cs) First of all, I have no idea if this is any good. The way I end up calling dealHands and getting a real result is `runState (dealHands 3 7 []) deck`. And I see that I've got nested lambdas all in `deal`. But hey it took me forever to figure it out and it works. I'm using `shuffle` from Data.Random.Extras, which results in an RVar, and thus the beginning of my perplexity. I'm happy to end up with RVar inside a State monad, but I'm not sure where to start. To be honest, I'm only barely understanding what I'm doing with the State monad as it is. :) Happy for any help whatsoever! - Matthew ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Combining State and List Monads
Hello, the state should be inside, to count, so type is ListT (State Int) (Int,Int) the runner is then runState (runListT countCalls) 0 but [] is not of type ListT m so you need to wrap it in ListT . return import Control.Monad.List import Control.Monad.State import Control.Monad.Instances countCalls :: ListT (State Int) (Int,Int) countCalls = do a - ListT . return $ [1..2] b - ListT . return $ [1..2] modify (+1) return (a,b) regards paolino 2012/8/25 Henry Laxen nadine.and.he...@pobox.com Dear Cafe, It seems to me there should be some simple way of doing this, but thus far it eludes me. I am trying to combine the State and List monads to do the following: countCalls = do a - [1..2] b - [1..2] modify (+1) return (a,b) where with some combination of ListT, StateT, List, State, or who knows what would result in: ([(1,1),(1,2),(2,1),(2,2)],4) assuming we initialize the state to 0 Is there any way to make this happen? Thanks in advance. Henry Laxen ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Adding to / subtracting from a LocalTime?
Hello. This is a part of a solution, with explicit TimeZone Prelude Data.Time :t \z s t - utcToLocalTime z $ addUTCTime (fromIntegral s) (localTimeToUTC z t) \z s t - utcToLocalTime z $ addUTCTime (fromIntegral s) (localTimeToUTC z t) :: Integral a = TimeZone - a - LocalTime - LocalTime where the Integral arguments is in seconds, by docs regards paolino 2012/8/18 Adde Nilsson trialc...@gmail.com Hi. How do you add to or subtract from a LocalTime? I'm trying to subtract a second from a LocalTime value but the only API's I can find act only on the TimeOfDay part. subSec :: LocalTime - LocalTime subSec (LocalTime d t) = LocalTime d $ timeToTimeOfDay ((timeOfDayToTime t) - (secondsToDiffTime 1)) I'm obviously on the wrong track as this looks way too complex for what it's trying to achieve. Calling with '2012-08-18 00:00:00' gives '2012-08-18 -01:59:59' which isn't very helpful. How do I get to '2012-08-17 23:59:59'? Thanks, Adde ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Key-Parametrized Lookup Table
Hello, I made some trial and error with ghci to make it happy. I'm not really sure this has the type safety you asked. {-# LANGUAGE TypeFamilies, ExistentialQuantification, FlexibleContexts #-} import Prelude hiding (lookup) import Data.Typeable class Typeable a = Key a where type Value a :: * data Assoc = forall a . (Typeable (Value a),Key a) = Assoc a (Value a) insert :: (Typeable (Value a), Key a) = a - Value a - [Assoc] - [Assoc] insert k v = (Assoc k v :) lookup :: (Typeable (Value a), Eq a, Key a) = a - [Assoc] - Value a lookup k [] = error noassoc lookup k ((Assoc k' v):xs) = case cast k' of Nothing - lookup k xs Just k'' - if k'' == k then case cast v of Nothing - error nocast Just v' - v' else lookup k xs I've tried without the typeclass with no luck. For some reasons type family Key a :: * type family Value a :: * and adding Typeable (Key a) to the contexts and Key 'a' in place of 'a' leads to a lot of type errors. Maybe it's possible with more help. Hope I got it right. Regards paolino 2012/7/31 Alexander Foremny alexanderfore...@gmail.com Hello list, I am currently thinking that a problem of mine would best be solved if there was a Map-like data structure in which the value returned is parametrized over the lookup type. I wonder is this makes sense and if such a data structure exists or if it could be created while still being well typed. I essentially want to statically define a scope of Key values and dynamically define a list of keys. -- Scope of possible keys. type Label = String data Key a where KeyStr :: Label - Key String KeyInt :: Label - Key Int KeyChoice :: Label - [a] - Key a -- Some key values, to be extended at runtime. strKey Some String strKey' Another String intKey Some integer choiceKey Chose one [ a, b, c ] :: KeyChoice String Now I need a data structure to possibly associate a value to the key. data MapG = ... type Value a = a insert :: Key a - Value a - MapG Key Value - MapG Key Value lookup :: Key a - MapG Key Value - Maybe (Value a) I tried implementing this with multiple Map k a's. I tried adding a phantom type on some storage type of to implement KeyChoice as of type Key Int, but I ran into troubles with this approach. I wonder if Dynamic or Type Families could achieve this, but I am quite at a loss and would like to hear your opinion. I did try to search for this a bit, but I don't quite know how to phrase my problem. I'd like to apologize in advance if this question has been asked already. Regards, Alexander Foremny ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Key-Parametrized Lookup Table
This is without class :-) {-# LANGUAGE TypeFamilies, ExistentialQuantification, FlexibleContexts #-} import Prelude hiding (lookup) import Data.Typeable type family Value a :: * data Assoc = forall a . (Typeable (Value a), Typeable a) = Assoc a (Value a) insert :: (Typeable (Value a), Typeable a) = a - Value a - [Assoc] - [Assoc] insert k v = (Assoc k v :) lookup :: (Typeable (Value a), Typeable a, Eq a) = a - [Assoc] - Value a lookup k [] = error noassoc lookup k ((Assoc k' v):xs) = case cast k' of Nothing - lookup k xs Just k'' - if k'' == k then case cast v of Nothing - error nocast Just v' - v' else lookup k xs *Main type instance Value Integer = Char *Main type instance Value Int = String *Main let u = insert (1::Integer) 'c' $ insert (1::Int) ciao [] *Main lookup (1 :: Integer) u 'c' *Main lookup (1 :: Int) u ciao *Main Regards paolino 2012/8/1 Paolino paolo.verone...@gmail.com Hello, I made some trial and error with ghci to make it happy. I'm not really sure this has the type safety you asked. {-# LANGUAGE TypeFamilies, ExistentialQuantification, FlexibleContexts #-} import Prelude hiding (lookup) import Data.Typeable class Typeable a = Key a where type Value a :: * data Assoc = forall a . (Typeable (Value a),Key a) = Assoc a (Value a) insert :: (Typeable (Value a), Key a) = a - Value a - [Assoc] - [Assoc] insert k v = (Assoc k v :) lookup :: (Typeable (Value a), Eq a, Key a) = a - [Assoc] - Value a lookup k [] = error noassoc lookup k ((Assoc k' v):xs) = case cast k' of Nothing - lookup k xs Just k'' - if k'' == k then case cast v of Nothing - error nocast Just v' - v' else lookup k xs I've tried without the typeclass with no luck. For some reasons type family Key a :: * type family Value a :: * and adding Typeable (Key a) to the contexts and Key 'a' in place of 'a' leads to a lot of type errors. Maybe it's possible with more help. Hope I got it right. Regards paolino 2012/7/31 Alexander Foremny alexanderfore...@gmail.com Hello list, I am currently thinking that a problem of mine would best be solved if there was a Map-like data structure in which the value returned is parametrized over the lookup type. I wonder is this makes sense and if such a data structure exists or if it could be created while still being well typed. I essentially want to statically define a scope of Key values and dynamically define a list of keys. -- Scope of possible keys. type Label = String data Key a where KeyStr :: Label - Key String KeyInt :: Label - Key Int KeyChoice :: Label - [a] - Key a -- Some key values, to be extended at runtime. strKey Some String strKey' Another String intKey Some integer choiceKey Chose one [ a, b, c ] :: KeyChoice String Now I need a data structure to possibly associate a value to the key. data MapG = ... type Value a = a insert :: Key a - Value a - MapG Key Value - MapG Key Value lookup :: Key a - MapG Key Value - Maybe (Value a) I tried implementing this with multiple Map k a's. I tried adding a phantom type on some storage type of to implement KeyChoice as of type Key Int, but I ran into troubles with this approach. I wonder if Dynamic or Type Families could achieve this, but I am quite at a loss and would like to hear your opinion. I did try to search for this a bit, but I don't quite know how to phrase my problem. I'd like to apologize in advance if this question has been asked already. Regards, Alexander Foremny ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] combining predicates, noob question
You can still use the monadic combinators, with the price of wrapping and unwrapping in case of newtype. newtype P a = P {unP :: a - Bool} liftM2'P :: (Bool - Bool - Bool) - P a - P a - P a liftM2'P op = (P .) . on (liftM2 op) unP paolino 2012/7/8 Sebastián Krynski skryn...@gmail.com Ok , thanks for the answers, I understand now what liftM2 does. In this case would it be silly to use combinerPred (and maybe a newType Predicate a = a - Bool) for the sake of readability or shoud I stick with a - Bool and liftM2? thanks, Sebastián 2012/7/6 Brent Yorgey byor...@seas.upenn.edu On Fri, Jul 06, 2012 at 03:17:54PM -0300, Felipe Almeida Lessa wrote: On Fri, Jul 6, 2012 at 2:11 PM, Sebastián Krynski skryn...@gmail.com wrote: As I was using predicates (a - bool) , it appeared the need for combining them with a boolean operator (bool - bool - bool) in order to get a new predicate combining the previous two. So I wrote my function combinerPred (see code below). While I think this is JUST ok, i'm feeling a monad in the air. So.. where is the monad? combinerPred :: (a - Bool) - (a - Bool) - (Bool - Bool - Bool) - (a - Bool) combinerPred pred1 pred2 op = \x - op (pred1 x) (pred2 x) That's the `(-) a` monad: import Control.Applicative combinerPred :: (a - Bool) - (a - Bool) - (Bool - Bool - Bool) - (a - Bool) combinerPred pred1 pred2 op = op $ pred1 * pred2 By the way, I find it more natural to make 'op' the first argument, because it is more useful to partially apply combinerPred to an operation that it is to some predicates. Also, in that case combinerPred is simply liftA2: import Control.Applicative combinerPred :: (Bool - Bool - Bool) - (a - Bool) - (a - Bool) - (a - Bool) combinerPred = liftA2 -Brent ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] existential types and cast
Hi Corentin, This is how I would model your request (without concrete constructors for Player and Rule) I'm sure there are better descriptions also as I'm not an expert. paolino {-# LANGUAGE DataKinds, GADTs, KindSignatures #-} data Player data Rule data Data = Player | Rule data EventKind = Action | Reaction data Event :: EventKind - * where NewPlayer :: Player - Event Action NewRule:: Rule - Event Action NewHandler :: (Event Action - IO ()) - Event Reaction handle :: Event Action - Event Reaction - IO () handle x (NewHandler f) = f x reaction :: Event a - [Event Reaction] - IO [Event Reaction] reaction f@(NewHandler _) es = return $ f:es reaction p@(NewPlayer _) es = mapM_ (handle p) es return es reaction r@(NewRule _) es = mapM_ (handle r) es return es 2012/7/4 Corentin Dupont corentin.dup...@gmail.com Hi, for example, in my game (Nomic) if a new player arrives, I trigger a NewPlayer event. All handlers registered for that event should be triggered, and passed a structure Player containing all the infos of the incoming player. If there is a new rule submitted, that the same: the event NewRule is triggered and the handlers are passed a structure Rule. Thus I want the handlers registered on NewPlayer to have the type Player - xxx, and on NewRule to have the type Rule - xxx. I want to be able to associate an arbitrary data type (here Player and Rule) to an event. The handlers are inherently of different types, but I want to store them in a unique list hence the existential... On Wed, Jul 4, 2012 at 4:33 PM, Paolino paolo.verone...@gmail.com wrote: Hi Corentin, If you could explain *why* there should be a type associated to each event value, it would help, maybe. If it's a design choice , maybe it's wrong design. One reason to use dynamic typing would be to plug in new type of events. But if you already have the events semantics , this is not useful. If the language of events is complex , possibly recursive, you can use GADTs to enforce their validity by construction and you don't need to typefy the event values, but some of their characteristics. Remember type machinery is good to give correctness at the compilation time which Typeable defeats moving checks at runtime. So lifting values to types and eliminating this information with existentials and casting seems wrong. paolino 2012/7/4 Corentin Dupont corentin.dup...@gmail.com Hi Paolino, the user can add as many handlers he wants for each event. When a event is triggered along with a data, all handlers associated to that event should be triggered and passed the data. The trick is, there is one type of data associated with each event. That's why I cannot use a Event datatype: how to associate a data type to each event value? This would be some sort of dependant typing if I'm not mistaken. That's why my events exists both on type level and value level: *data NewPlayer = NewPlayer * wich allows me to associate it a typf data with type indexing.*.. * Regards Corentin On Wed, Jul 4, 2012 at 12:58 PM, Paolino paolo.verone...@gmail.comwrote: Hi How many handlers for each type of event in the list of handlers ? If you have only one handler for each type , it should go in the typeclass, and you don't need typeable. If you have more than one maybe you can avoid using type indexing at all, because it doesn't resolve the handler selection issue. By the way , it's not clear to me why you don't have a simple Event datatype describing all the possible events in advance. Regards paolino 2012/7/3 Corentin Dupont corentin.dup...@gmail.com Hi all, I read somewhere (here: http://stackoverflow.com/questions/2300275/how-to-unpack-a-haskell-existential-type) that it's bad to try to unbox an existential type using a cast. OK, but without I really can't figure out how to do what I want: *data NewPlayer = NewPlayer deriving (Typeable, Eq) data NewRule = NewRule deriving (Typeable, Eq) class (Eq e, Typeable e) = Event e where data EventData e instance Event NewPlayer where data EventData NewPlayer = P Int instance Event NewRule where data EventData NewRule = R Int instance Typeable1 EventData where typeOf1 _ = mkTyConApp (mkTyCon EventData) [] data EventHandler = forall e . (Event e) = EH e (EventData e - IO ()) addEvent :: (Event e) = e - (EventData e - IO ()) - [EventHandler] - [EventHandler] addEvent e h ehs = (EH e h):ehs triggerEvent :: (Event e) = e - (EventData e) - [EventHandler] - IO () triggerEvent e d ehs = do let r = find (\(EH myEvent _) - cast e == Just myEvent) ehs case r of Nothing - return () Just (EH _ h) - case cast h of Just castedH - castedH d Nothing - return ()* How to remove the casts from triggerEvent? All that I want is to apply the handler found on the data passed in parameter. I tried to add a function apply in the class, without success: *apply :: (EventData e
Re: [Haskell-cafe] existential types and cast
Sorry, drop the data Data line, I was experimenting with a deeper description. paolino 2012/7/4 Paolino paolo.verone...@gmail.com Hi Corentin, This is how I would model your request (without concrete constructors for Player and Rule) I'm sure there are better descriptions also as I'm not an expert. paolino {-# LANGUAGE DataKinds, GADTs, KindSignatures #-} data Player data Rule data Data = Player | Rule data EventKind = Action | Reaction data Event :: EventKind - * where NewPlayer :: Player - Event Action NewRule:: Rule - Event Action NewHandler :: (Event Action - IO ()) - Event Reaction handle :: Event Action - Event Reaction - IO () handle x (NewHandler f) = f x reaction :: Event a - [Event Reaction] - IO [Event Reaction] reaction f@(NewHandler _) es = return $ f:es reaction p@(NewPlayer _) es = mapM_ (handle p) es return es reaction r@(NewRule _) es = mapM_ (handle r) es return es 2012/7/4 Corentin Dupont corentin.dup...@gmail.com Hi, for example, in my game (Nomic) if a new player arrives, I trigger a NewPlayer event. All handlers registered for that event should be triggered, and passed a structure Player containing all the infos of the incoming player. If there is a new rule submitted, that the same: the event NewRule is triggered and the handlers are passed a structure Rule. Thus I want the handlers registered on NewPlayer to have the type Player - xxx, and on NewRule to have the type Rule - xxx. I want to be able to associate an arbitrary data type (here Player and Rule) to an event. The handlers are inherently of different types, but I want to store them in a unique list hence the existential... On Wed, Jul 4, 2012 at 4:33 PM, Paolino paolo.verone...@gmail.comwrote: Hi Corentin, If you could explain *why* there should be a type associated to each event value, it would help, maybe. If it's a design choice , maybe it's wrong design. One reason to use dynamic typing would be to plug in new type of events. But if you already have the events semantics , this is not useful. If the language of events is complex , possibly recursive, you can use GADTs to enforce their validity by construction and you don't need to typefy the event values, but some of their characteristics. Remember type machinery is good to give correctness at the compilation time which Typeable defeats moving checks at runtime. So lifting values to types and eliminating this information with existentials and casting seems wrong. paolino 2012/7/4 Corentin Dupont corentin.dup...@gmail.com Hi Paolino, the user can add as many handlers he wants for each event. When a event is triggered along with a data, all handlers associated to that event should be triggered and passed the data. The trick is, there is one type of data associated with each event. That's why I cannot use a Event datatype: how to associate a data type to each event value? This would be some sort of dependant typing if I'm not mistaken. That's why my events exists both on type level and value level: *data NewPlayer = NewPlayer * wich allows me to associate it a typf data with type indexing.*.. * Regards Corentin On Wed, Jul 4, 2012 at 12:58 PM, Paolino paolo.verone...@gmail.comwrote: Hi How many handlers for each type of event in the list of handlers ? If you have only one handler for each type , it should go in the typeclass, and you don't need typeable. If you have more than one maybe you can avoid using type indexing at all, because it doesn't resolve the handler selection issue. By the way , it's not clear to me why you don't have a simple Event datatype describing all the possible events in advance. Regards paolino 2012/7/3 Corentin Dupont corentin.dup...@gmail.com Hi all, I read somewhere (here: http://stackoverflow.com/questions/2300275/how-to-unpack-a-haskell-existential-type) that it's bad to try to unbox an existential type using a cast. OK, but without I really can't figure out how to do what I want: *data NewPlayer = NewPlayer deriving (Typeable, Eq) data NewRule = NewRule deriving (Typeable, Eq) class (Eq e, Typeable e) = Event e where data EventData e instance Event NewPlayer where data EventData NewPlayer = P Int instance Event NewRule where data EventData NewRule = R Int instance Typeable1 EventData where typeOf1 _ = mkTyConApp (mkTyCon EventData) [] data EventHandler = forall e . (Event e) = EH e (EventData e - IO ()) addEvent :: (Event e) = e - (EventData e - IO ()) - [EventHandler] - [EventHandler] addEvent e h ehs = (EH e h):ehs triggerEvent :: (Event e) = e - (EventData e) - [EventHandler] - IO () triggerEvent e d ehs = do let r = find (\(EH myEvent _) - cast e == Just myEvent) ehs case r of Nothing - return () Just (EH _ h) - case cast h of Just castedH - castedH d Nothing - return ()* How to remove the casts from triggerEvent? All that I
Re: [Haskell-cafe] existential types and cast
Hi Corentin, If you could explain *why* there should be a type associated to each event value, it would help, maybe. If it's a design choice , maybe it's wrong design. One reason to use dynamic typing would be to plug in new type of events. But if you already have the events semantics , this is not useful. If the language of events is complex , possibly recursive, you can use GADTs to enforce their validity by construction and you don't need to typefy the event values, but some of their characteristics. Remember type machinery is good to give correctness at the compilation time which Typeable defeats moving checks at runtime. So lifting values to types and eliminating this information with existentials and casting seems wrong. paolino 2012/7/4 Corentin Dupont corentin.dup...@gmail.com Hi Paolino, the user can add as many handlers he wants for each event. When a event is triggered along with a data, all handlers associated to that event should be triggered and passed the data. The trick is, there is one type of data associated with each event. That's why I cannot use a Event datatype: how to associate a data type to each event value? This would be some sort of dependant typing if I'm not mistaken. That's why my events exists both on type level and value level: *data NewPlayer = NewPlayer *wich allows me to associate it a typf data with type indexing.*.. * Regards Corentin On Wed, Jul 4, 2012 at 12:58 PM, Paolino paolo.verone...@gmail.comwrote: Hi How many handlers for each type of event in the list of handlers ? If you have only one handler for each type , it should go in the typeclass, and you don't need typeable. If you have more than one maybe you can avoid using type indexing at all, because it doesn't resolve the handler selection issue. By the way , it's not clear to me why you don't have a simple Event datatype describing all the possible events in advance. Regards paolino 2012/7/3 Corentin Dupont corentin.dup...@gmail.com Hi all, I read somewhere (here: http://stackoverflow.com/questions/2300275/how-to-unpack-a-haskell-existential-type) that it's bad to try to unbox an existential type using a cast. OK, but without I really can't figure out how to do what I want: *data NewPlayer = NewPlayer deriving (Typeable, Eq) data NewRule = NewRule deriving (Typeable, Eq) class (Eq e, Typeable e) = Event e where data EventData e instance Event NewPlayer where data EventData NewPlayer = P Int instance Event NewRule where data EventData NewRule = R Int instance Typeable1 EventData where typeOf1 _ = mkTyConApp (mkTyCon EventData) [] data EventHandler = forall e . (Event e) = EH e (EventData e - IO ()) addEvent :: (Event e) = e - (EventData e - IO ()) - [EventHandler] - [EventHandler] addEvent e h ehs = (EH e h):ehs triggerEvent :: (Event e) = e - (EventData e) - [EventHandler] - IO () triggerEvent e d ehs = do let r = find (\(EH myEvent _) - cast e == Just myEvent) ehs case r of Nothing - return () Just (EH _ h) - case cast h of Just castedH - castedH d Nothing - return ()* How to remove the casts from triggerEvent? All that I want is to apply the handler found on the data passed in parameter. I tried to add a function apply in the class, without success: *apply :: (EventData e - IO ()) - (EventData e) - IO () apply = ($)* Thanks! Corentin ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] existential types and cast
Hi How many handlers for each type of event in the list of handlers ? If you have only one handler for each type , it should go in the typeclass, and you don't need typeable. If you have more than one maybe you can avoid using type indexing at all, because it doesn't resolve the handler selection issue. By the way , it's not clear to me why you don't have a simple Event datatype describing all the possible events in advance. Regards paolino 2012/7/3 Corentin Dupont corentin.dup...@gmail.com Hi all, I read somewhere (here: http://stackoverflow.com/questions/2300275/how-to-unpack-a-haskell-existential-type) that it's bad to try to unbox an existential type using a cast. OK, but without I really can't figure out how to do what I want: *data NewPlayer = NewPlayer deriving (Typeable, Eq) data NewRule = NewRule deriving (Typeable, Eq) class (Eq e, Typeable e) = Event e where data EventData e instance Event NewPlayer where data EventData NewPlayer = P Int instance Event NewRule where data EventData NewRule = R Int instance Typeable1 EventData where typeOf1 _ = mkTyConApp (mkTyCon EventData) [] data EventHandler = forall e . (Event e) = EH e (EventData e - IO ()) addEvent :: (Event e) = e - (EventData e - IO ()) - [EventHandler] - [EventHandler] addEvent e h ehs = (EH e h):ehs triggerEvent :: (Event e) = e - (EventData e) - [EventHandler] - IO () triggerEvent e d ehs = do let r = find (\(EH myEvent _) - cast e == Just myEvent) ehs case r of Nothing - return () Just (EH _ h) - case cast h of Just castedH - castedH d Nothing - return ()* How to remove the casts from triggerEvent? All that I want is to apply the handler found on the data passed in parameter. I tried to add a function apply in the class, without success: *apply :: (EventData e - IO ()) - (EventData e) - IO () apply = ($)* Thanks! Corentin ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Arithmetic expressions with GADTs: parsing
Very useful to get a gadt back to monotype without an existential, which would mean to use classes for future uses of it with its load of object oriented thinking. Thanks for sharing. paolino 2012/6/4 Ryan Ingram ryani.s...@gmail.com Another option is to reify the type so that you can get it back somehow. Here's a few diffs to your file (I've attached the full code): A new type: data Typed f where TDouble :: f Double - Typed f TBool :: f Bool - Typed f runT :: (f Double - a) - (f Bool - a) - Typed f - a runT k _ (TDouble x) = k x runT _ k (TBool x) = k x New version of pExpr that can parse both expression types, by tagging with the type -- pExpr = pArit | pBool | pEqual pExpr = (TDouble $ pArit) | (TBool $ pBool) | (TDouble $ pEqual) and now main: main = do line - getLine case parse pExpr line of Left msg - putStrLn (show msg) Right e - putStrLn (runT (show . eval) (show . eval) e) What I'm doing here is reifying the possible types of top level expressions and then providing a handler in main which works on all possible types. There are other ways to do this (embed any expression in an existential, for example), but this makes it really clear what is going on, and shows the way forward for parsing a larger typed language. -- ryan On Wed, May 2, 2012 at 6:08 AM, j.romi...@gmail.com wrote: On Wed, May 02, 2012 at 03:02:46PM +0300, Roman Cheplyaka wrote: * j.romi...@gmail.com j.romi...@gmail.com [2012-05-02 08:03:45-0300] [...] The alternatives given to | must be of the same type. In your case, one is Expr Double and one is Expr Bool. Inclusion of pBool in pFactor is probably a mistake — unless you're going to multiply booleans. You are right in the sense that I cannot mix Expr Bool and Expr Double in a (O op l r) expression. But the parser should be able to parse any form of expressions. So I rewrite my program to take this into account. The new versions still does not compile: Expr.hs:27:23: Couldn't match expected type `Double' with actual type `Bool' Expected type: ParsecT String () Data.Functor.Identity.Identity (Expr Double) Actual type: ParsecT String () Data.Functor.Identity.Identity (Expr Bool) In the first argument of `(|)', namely `pBool' In the second argument of `(|)', namely `pBool | pEqual' Romildo ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Can Haskell outperform C++?
Hello, I would like to add questions to yours. I'm not sure that C++ programs are same performance as C actually, so I can have a bad logic. How much is hard to port a haskell program to C ? If it will become harder and harder, (i.e. for parallelizations) than it's fair to choose haskell for performance, but if it's not, I think it's hard to think that such a high level language could ever compile down to something running faster than its port to C. Many of the abstractions used for nice haskell code are based on boxing values, so we have to take away all the boxing to make it run faster, and so we are porting to C. Will hardware really go for hundreds of cores ? If yes than all languages supporting simple parallelization will be used to code, but this will not make C slower, just more difficult to use in contests. Also a leading haskell point is , how does it take to make a correct code, which can be performance in the wild. So it makes some sense to choose haskell for performance to me, but not to try to compete in sequential algorithmic performance, with the exception for who do it to learn what is behind the abstractions that makes their code slow and not compile down to perfect C. paolino P.S. The performance problems are actually learning haskell programming abstractions and the intuition development on when to use each. 2012/5/6 Janek S. fremenz...@poczta.onet.pl: Hi, a couple of times I've encountered a statement that Haskell programs can have performance comparable to programs in C/C++. I've even read that thanks to functional nature of Haskell, compiler can reason and make guarantess about the code and use that knowledge to automatically parallelize the program without any explicit parallelizing commands in the code. I haven't seen any sort of evidence that would support such claims. Can anyone provide a code in Haskell that performs better in terms of execution speed than a well-written C/C++ program? Both Haskell and C programs should implement the same algorithm (merge sort in Haskell outperforming bubble sort in C doesn't count), though I guess that using Haskell-specific idioms and optimizations is of course allowed. Jan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Subcategories on Hackage
I think there are two reasons to browse the hackage database. First reason reflects the common need to find a library that suites one's needs. In this case it's very easy to find it with google adding hackage haskell to the submitted word list. Second reason is to have a nice landscape of packages when one enters the site. For the second reason, which is real browsing, categories are a pain, whoever and however they are done. The more they are correct , the more they are difficult to understand. The more they are easy like tags the more it's difficult to put them in a hierarchy. One well known solution is to put tags in a high dimensional space where the tag names and distance between tags is defined by statistics on the tags cloud of each tag holder (packages). In this case browsing is jumping from one tag to another *near* one in the tag space and see the packages *around* , while inserting new packages changes the position of the tags in their space. An easiest , but somewhat wrong, solution is give each tag a dimension and have the packages in the space to browse. Ontologies are more on formalising the meaning (seen as interrelations) of concepts, which tags are not, and I don't think even software categories are. But this is really debatable. my 2 cents paolino 2011/6/5 Evan Laforge qdun...@gmail.com On Sat, Jun 4, 2011 at 7:46 PM, Felipe Almeida Lessa felipe.le...@gmail.com wrote: tl;dr: I don't think ontologies are suitable for Hackage. I think I agree. For instance, I just uploaded fix-imports and had to decide which categories it is in. It manages imports, which is IDE-like and people looking for IDE-like features might be interested, so IDE. It's concerned with haskell itself, so Haskell. And it's meant to be used with an editor, though it isn't an editor itself, so Editor. It's actually none of those things, but there's no specific category for it, and if there were I think it would be too small to be useful. So I picked things I think people who might be interested in it would be searching for. I don't think a hierarchy would have helped in this case, but tags would be appropriate. Actually, I wound up using the categories like tags. I think we just need better search, e.g. +tag +tag or something. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] template haskell for typeclass synonyms
It's first time I use TH. It would be nice to point out the motivations for using it. If everything TH does is doable without it, the point of using it is write less code, eliminating some necessary and automatically computable code. But I guess there is some more . paolino 2010/11/2 Antoine Latter aslat...@gmail.com 2010/11/1 Paolino paolo.verone...@gmail.com: I think I've got something nice in the end. http://hpaste.org/41042/classsynonymhs example: class (ParteDi (Servizio a) s ,Read a ,Eq a , Show a , Integer `ParteDi` s ) = SClass s a $(classSynonym ''SClass) ghci :i SClass command is printing some strange type variables but it compiles Template Haskell might be overkill for this. In the past, I've done: class (Eq b, Show b, MyClass b, MyOtherClass b) = MySynonym b instance (Eq b, Show b, MyClass b, MyOtherClass b) = MySynonym b I think this requires a couple of GHC extensions, but TemplateHaskell is an extension as well. Maybe there are pitfalls with this approach. Antoine ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] template haskell for typeclass synonyms
Hello. I'd like to have a template haskell function that take some constraints and a class name and write an empty class from those and relative empty instance to simulate typeclass synonyms. As I've never written TH and couldn't find a easily adaptable code around, I ask here for the code, or some hints on how to arrive there. Thanks paolino ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] template haskell for typeclass synonyms
Thanks. I annotated the function http://hpaste.org/paste/41035/test_simpleclasssynonym It seems to produce the right code. How should I use the Parents synonym in my functions? This is a noob question I suppose. paolino 2010/11/1 Gábor Lehel illiss...@gmail.com On Mon, Nov 1, 2010 at 6:09 PM, Christopher Done chrisd...@googlemail.com wrote: On 1 November 2010 17:53, Paolino paolo.verone...@gmail.com wrote: I'd like to have a template haskell function that take some constraints and a class name and write an empty class from those and relative empty instance to simulate typeclass synonyms. As I've never written TH and couldn't find a easily adaptable code around, I ask here for the code, or some hints on how to arrive there. I took Justin Bailey's haskelldb-th library as a TH example to work from and rewrote one TH function to try my hand at it, it's quite easy to follow with a simple example: http://hpaste.org/paste/41035/demo Maybe this is enough example to get you going. The rest you can find syntax parts from the TH Haddock documentation. A useful FYI: the API docs are (almost) completely devoid of comments, but if you click to see the source, it does have some additional information in comments there, just not Haddock-formatted. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe -- Work is punishment for failing to procrastinate effectively. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] template haskell for typeclass synonyms
I think I've got something nice in the end. http://hpaste.org/41042/classsynonymhs example: class (ParteDi (Servizio a) s ,Read a ,Eq a , Show a , Integer `ParteDi` s ) = SClass s a $(classSynonym ''SClass) ghci :i SClass command is printing some strange type variables but it compiles paolino 2010/11/1 Gábor Lehel illiss...@gmail.com On Mon, Nov 1, 2010 at 6:09 PM, Christopher Done chrisd...@googlemail.com wrote: On 1 November 2010 17:53, Paolino paolo.verone...@gmail.com wrote: I'd like to have a template haskell function that take some constraints and a class name and write an empty class from those and relative empty instance to simulate typeclass synonyms. As I've never written TH and couldn't find a easily adaptable code around, I ask here for the code, or some hints on how to arrive there. I took Justin Bailey's haskelldb-th library as a TH example to work from and rewrote one TH function to try my hand at it, it's quite easy to follow with a simple example: http://hpaste.org/paste/41035/demo Maybe this is enough example to get you going. The rest you can find syntax parts from the TH Haddock documentation. A useful FYI: the API docs are (almost) completely devoid of comments, but if you click to see the source, it does have some additional information in comments there, just not Haddock-formatted. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe -- Work is punishment for failing to procrastinate effectively. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Long running Haskell program
Also, a *service* should have a persistence periodical action which should evaluate (most part of) the state thunks in their values to be serialized. This work for the structure similarity of NFData and Show/Binary classes. When there is a not directly serializable part of the state , things can get complicate, but resolving the persistence issue for those parts should resolve also the space leak, I think. paolino 2009/11/11 Paolino paolo.verone...@gmail.com Hello leimy, the only simple solution I have found to avoid a leaking state of a server is doing a periodical rnf of it, this implying the NFData constraint on its datatype. The reader should leak only if you nest forever the local function. paolino 2009/11/11 David Leimbach leim...@gmail.com As some of you may know, I've been writing commercial Haskell code for a little bit here (about a year and a half) and I've just recently had to write some code that was going to run have to run for a really long time before being restarted, possibly months or years if all other parts of the system cooperate as it's part of a server infrastructure management system. I recently ran into some serious space leak difficulties that would ultimately cause this program to crash some time after startup (my simulator is also written in Haskell, and runs a LOT faster than the real application ever could, this has enabled me to fast forward a bit the data growth issues and crash in minutes instead of days!) Anyway, rather than try to paste it all here with images and such I thought I'd stick it up on my blog so others could maybe benefit from the anecdote. It's difficult to disclose enough useful information as it is commercial code not under an open source license, but there's neat diagrams and stuff there so hopefully the colors are at least amusing :-) http://leimy9.blogspot.com/2009/11/long-running-haskell-applications.html Dave ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Problem with JHC
FWIW, I just compiled JHC 0.7.2 with ghc 6.12 , doing a couple of corrections to make it compile, which I don't think they are related to this *bug*. Testing the given code, it aborts for every inputs I give it L 1, T AND [L 1,L 2] included. I couldn't make it compile using function reads instead. paolino 2009/11/11 Ross Mellgren rmm-hask...@z.odi.ac According to the paste you gave for the JHC test run: Here is what happens when I try to run it: phi...@desktop:~/jhctut$ ./jtree Give me a tree: T AND (L 1, L 2) jtree_code.c:2670: case fell off Aborted You gave it parens not square brackets. -Ross On Nov 11, 2009, at 11:45 AM, Philippos Apolinarius wrote: you declared 'T Op [Tree]' so you should give 'T AND [L 1, L 2]' as the tree, right? Hi, Felipe. You are right. This means that I gave the correct input to the program. As you can see, I typed 'T AND [L 1, L 2]'. Therefore, JHC was expected to parse and print it. However, it failed to parse it. The program works perfectly well in GHC. Here is the GHC output: phi...@desktop:~/jhctut$ ghc tree.hs --make [1 of 1] Compiling Main ( tree.hs, tree.o ) Linking tree ... phi...@desktop:~/jhctut$ ./tree Give me a tree: T AND [L 1, L 2] T AND [L 1,L 2] --- On *Wed, 11/11/09, Felipe Lessa felipe.le...@gmail.com* wrote: From: Felipe Lessa felipe.le...@gmail.com Subject: Re: [Haskell-cafe] Problem with JHC To: haskell-cafe@haskell.org Received: Wednesday, November 11, 2009, 6:23 AM On Wed, Nov 11, 2009 at 04:32:05AM -0800, Philippos Apolinarius wrote: data Op = AND | OR | NOT deriving (Show, Read) data Tree= L Int | T Op [Tree] deriving (Show, Read) Hmm, you see, phi...@desktop:~/jhctut$ ./jtree Give me a tree: T AND (L 1, L 2) jtree_code.c:2670: case fell off Aborted you declared 'T Op [Tree]' so you should give 'T AND [L 1, L 2]' as the tree, right? -- Felipe. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe -- Get the name you've always wanted http://ca.promos.yahoo.com/jacko/! *@ ymail.com *or *...@rocketmail.com* .___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Long running Haskell program
Hello leimy, the only simple solution I have found to avoid a leaking state of a server is doing a periodical rnf of it, this implying the NFData constraint on its datatype. The reader should leak only if you nest forever the local function. paolino 2009/11/11 David Leimbach leim...@gmail.com As some of you may know, I've been writing commercial Haskell code for a little bit here (about a year and a half) and I've just recently had to write some code that was going to run have to run for a really long time before being restarted, possibly months or years if all other parts of the system cooperate as it's part of a server infrastructure management system. I recently ran into some serious space leak difficulties that would ultimately cause this program to crash some time after startup (my simulator is also written in Haskell, and runs a LOT faster than the real application ever could, this has enabled me to fast forward a bit the data growth issues and crash in minutes instead of days!) Anyway, rather than try to paste it all here with images and such I thought I'd stick it up on my blog so others could maybe benefit from the anecdote. It's difficult to disclose enough useful information as it is commercial code not under an open source license, but there's neat diagrams and stuff there so hopefully the colors are at least amusing :-) http://leimy9.blogspot.com/2009/11/long-running-haskell-applications.html Dave ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] STM semantics
I have a doubt that this code works like I want because actual STM implementation exposes its effects import Control.Concurrent import Control.Concurrent.STM main = do c - atomically $ newTChan :: IO (TChan ()) r - atomically $ newTVar False forkIO $ do atomically $ do r0 - readTVar r case r0 of True - return () False - readTChan c myThreadId = killThread threadDelay 100 atomically (writeTVar r True) The thread stops on readTChan, but exits when I change the TVar, which happens before the readTChan. Should I trust this is the correct STM behaviour , and will not change in different implementations ? thanks paolino ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] STM semantics
Thanks, atomicity is what I was missing in the STM semantics. Now it is clear. The retry primitive is not saying block here and this can imply no more pass here, which is somewhat difficult to express with locks paolino 2009/10/24 Matthew Brecknell matt...@brecknell.net: Hi Paolino, You wrote: I have a doubt that this code works like I want because actual STM implementation exposes its effects import Control.Concurrent import Control.Concurrent.STM main = do c - atomically $ newTChan :: IO (TChan ()) r - atomically $ newTVar False forkIO $ do atomically $ do r0 - readTVar r case r0 of True - return () False - readTChan c myThreadId = killThread threadDelay 100 atomically (writeTVar r True) The thread stops on readTChan, but exits when I change the TVar, which happens before the readTChan. Should I trust this is the correct STM behaviour , and will not change in different implementations ? This is correct behaviour. Remember, STM transactions execute atomically, so it doesn't make sense to think of a transaction as being blocked at a particular point in the code. A blocked transaction is just waiting for a state in which it can execute all at once. Calling retry is saying that this transaction is not yet ready to execute. As noted by Alberto, readTChan calls retry to indicate that it (and whatever transaction called it) cannot execute when the channel is empty. Putting it all together, you can see that your transaction will execute when (and only when) r contains True, or when c is not empty. Hope that helps, Matthew ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] testing par with simple program
Hi, reading a previous thread I got interested. I simplified the example pointed by dons in import Control.Parallel main = a `par` b `pseq` print (a + b ) where a = ack 3 11 b = ack 3 11 ack 0 n = n+1 ack m 0 = ack (m-1) 1 ack m n = ack (m-1) (ack m (n-1)) compiled with ghc --make prova -O2 -threaded timings paol...@paolino-casa:~$ time ./prova +RTS -N1 32762 real0m7.031s user0m6.304s sys0m0.004s paol...@paolino-casa:~$ time ./prova +RTS -N2 32762 real0m6.997s user0m6.728s sys0m0.020s paol...@paolino-casa:~$ without optimizations it gets worse paol...@paolino-casa:~$ time ./prova +RTS -N1 32762 real1m20.706s user1m18.197s sys0m0.104s paol...@paolino-casa:~$ time ./prova +RTS -N2 32762 real1m38.927s user1m45.039s sys0m0.536s paol...@paolino-casa:~$ staring at the resource usage graph I can see it does use 2 cores when told to do it, but with -N1 the used cpu goes 100% and with -N2 they both run just over 50% thanks for comments paolino ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] testing par with simple program
A better test program import Control.Parallel main = a `par` b `pseq` print (a + b ) where a = ack 3 11 b = fib 39 ack 0 n = n+1 ack m 0 = ack (m-1) 1 ack m n = ack (m-1) (ack m (n-1)) fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) running it , these are the results paol...@paolino-casa:~$ ghc --make prova -threaded [1 of 1] Compiling Main ( prova.hs, prova.o ) Linking prova ... paol...@paolino-casa:~$ time ./prova +RTS -N1 63262367 real1m17.485s user1m16.473s sys0m0.392s paol...@paolino-casa:~$ time ./prova +RTS -N2 63262367 real1m20.186s user1m31.554s sys0m0.600s paol...@paolino-casa:~$ touch prova.hs paol...@paolino-casa:~$ ghc --make prova -O2 -threaded [1 of 1] Compiling Main ( prova.hs, prova.o ) Linking prova ... paol...@paolino-casa:~$ time ./prova +RTS -N1 63262367 real0m17.652s user0m15.277s sys0m0.108s paol...@paolino-casa:~$ time ./prova +RTS -N2 63262367 real0m13.650s user0m15.121s sys0m0.188s From the resource graph and the timings it is clear that the program is not able to use all the 2 cores powers, considering computing 'a' alone is about 7 seconds and 'b' alone 9. What is retaining the cpu's to run full power ? paolino 2009/8/21 Don Stewart d...@galois.com paolo.veronelli: Hi, reading a previous thread I got interested. I simplified the example pointed by dons in import Control.Parallel main = a `par` b `pseq` print (a + b ) where a = ack 3 11 b = ack 3 11 ack 0 n = n+1 ack m 0 = ack (m-1) 1 ack m n = ack (m-1) (ack m (n-1)) compiled with ghc --make prova -O2 -threaded timings paol...@paolino-casa:~$ time ./prova +RTS -N1 32762 real0m7.031s user0m6.304s sys0m0.004s paol...@paolino-casa:~$ time ./prova +RTS -N2 32762 real0m6.997s user0m6.728s sys0m0.020s paol...@paolino-casa:~$ without optimizations it gets worse paol...@paolino-casa:~$ time ./prova +RTS -N1 32762 real1m20.706s user1m18.197s sys0m0.104s paol...@paolino-casa:~$ time ./prova +RTS -N2 32762 real1m38.927s user1m45.039s sys0m0.536s paol...@paolino-casa:~$ staring at the resource usage graph I can see it does use 2 cores when told to do it, but with -N1 the used cpu goes 100% and with -N2 they both run just over 50% thanks for comments Firstly, a and b are identical, so GHC commons them up. The compiler transforms it into: a `par` a `seq` print (a + a) So you essentially fork a spark to evaluate 'a', and then have the main thread also evaluate 'a' again. One of them wins, then you add the result to itself. The runtime may choose not to convert your first spark into a thread. Running with a 2009 GHC head snapshot, we can see with +RTS -sstderr SPARKS: 1 (0 converted, 0 pruned) That indeed, it doesn't convert your `par` into a real thread. While, for example, the helloworld on the wiki: http://haskell.org/haskellwiki/Haskell_in_5_steps Converts 2 sparks to 2 theads: SPARKS: 2 (2 converted, 0 pruned) ./B +RTS -threaded -N2 -sstderr 2.13s user 0.04s system 137% cpu 1.570 total -- Don ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] iteratee enumHandle
I'm testing iteratee. This is the possible bug I've found import Data.Iteratee.IO import Data.Iteratee.Base import Data.Iteratee.Char import System.IO import Control.Exception main = do h - openFile mamma23 ReadWriteMode hPutStrLn h ciao hSeek h AbsoluteSeek 0 l - (enumHandle h stream2list :: IO (Iteratee IO String)) = run print $ assert (l == ciao) () assertion failed This aside, I'd like to know if there is a way to use parsec library to make an Iteratee, so if it's possible to make parsec spit out a continuation on EOF, or maybe as in delcont language to capture it. thanks paolino ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] parallelism or concurrency ? if they are different
thanks Henk-Jan, someone just helped me saying that my function is pure as long as I make a cache of it, indexed on arguments. This operationally proves that concurrent IO code can be purified with unsafePerformIO, when it's semantic is not changed by that kind of cache. Really doing the cache then it's an implementation choice. It would be nice to have a suffix for this kind of functions, something remembering the unrepeatability of them when not cached. Sorry for my lacks of structure, I did my best. paolino 2009/2/17, Henk-Jan van Tuyl hjgt...@chello.nl: On Fri, 13 Feb 2009 11:09:35 +0100, Paolino paolo.verone...@gmail.com wrote: When I came to haskell, I arrived with a small and only evolutionary background in programming. First monad I met was MonadState StdGen m. Everything was in someway acceptable, I had no problem in explicitating the need for the generator. The lesson was referential transparency. To me referential tranparency is still obscure as a feature. Not using the monad , my functions pass around a generator, then they are repeatable, same generator , same computation. Years pass by, now evolutionary algorithms need to scale multicores. But multicore can be used with threads or par, the difference is that par is pure, because it respects referential transparency. But threads not. They are always unrespectful ? Or it's an implementation issue of preemptive choice? Can I have a baton to pass around like I had for random generator, so that the computation ends without IO (unsafe performed) , without breaking tranparency, something like (runIOThreads :: ThreadsIO a - ThreadsBaton - a) ? From Real World Haskell my algorithm have to be parallelized as they don't do some kind of IO, they don't deal with the world, but where is it stated that it is possible to write them with par (I couldn't) ? More , I'm not caring that my computation is unrepeatable, for me it's fine that the runtime system gives me the cached results for same arguments computation. The fact that it doesn't ,and recompute the function giving out something fuzzily different from before, is enough to coerce me to spit out IO values ? Finally, why and where the optimizer will substitute a value with its definition, so that it possibly get computed twice ? Thanks paolino I am not an expert in this matter, but as nobody answered sofar (perhaps people were frightened off by a lack of structure in your text), I will try to give some pointers: - You can start a function with parameters in a thread like this threadId - forkIO (foo 42) where foo has type Int - IO () - Communication between threads can be done with MVars, see: http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent-MVar.html - You can find concurrency demos at: http://www.haskell.org/haskellwiki/Concurrency_demos - Links to articles about parallelism: http://www.haskell.org/haskellwiki/Blog_articles/Parallel - To prevent recomputing, read: http://www.haskell.org/haskellwiki/Memoization -- Regards, Henk-Jan van Tuyl -- http://functor.bamikanarie.com http://Van.Tuyl.eu/ -- ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] parallelism or concurrency ? if they are different
When I came to haskell, I arrived with a small and only evolutionary background in programming. First monad I met was MonadState StdGen m. Everything was in someway acceptable, I had no problem in explicitating the need for the generator. The lesson was referential transparency. To me referential tranparency is still obscure as a feature. Not using the monad , my functions pass around a generator, then they are repeatable, same generator , same computation. Years pass by, now evolutionary algorithms need to scale multicores. But multicore can be used with threads or par, the difference is that par is pure, because it respects referential transparency. But threads not. They are always unrespectful ? Or it's an implementation issue of preemptive choice? Can I have a baton to pass around like I had for random generator, so that the computation ends without IO (unsafe performed) , without breaking tranparency, something like (runIOThreads :: ThreadsIO a - ThreadsBaton - a) ? From Real World Haskell my algorithm have to be parallelized as they don't do some kind of IO, they don't deal with the world, but where is it stated that it is possible to write them with par (I couldn't) ? More , I'm not caring that my computation is unrepeatable, for me it's fine that the runtime system gives me the cached results for same arguments computation. The fact that it doesn't ,and recompute the function giving out something fuzzily different from before, is enough to coerce me to spit out IO values ? Finally, why and where the optimizer will substitute a value with its definition, so that it possibly get computed twice ? Thanks paolino ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] WriterT [w] IO is not lazy in reading [w]
As someone suggested me, I can read the logs from Writer and WriterT as computation goes by, if the monoid for the Writer is lazy readable. This has been true until I tried to put the IO inside WriterT {-# LANGUAGE FlexibleContexts #-} import Control.Monad.Writer k :: (MonadWriter [Int] m) = m [Int] k = let f x = tell [x] f (x + 1) in f 0 works :: [Int] works = snd $ runWriter k hangs :: IO [Int] hangs = snd `liftM` runWriterT k main = take 20 `liftM` hangs = print The main hangs both interpreted and compiled on ghc 6.10.1. The issue is not exposing with IO alone as main = print test main is a working program. Thanks for explanations. paolino ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] WriterT [w] IO is not lazy in reading [w]
I must ask why runWriterT k :: State s (a,[Int]) is working. Looks like I could runIO the same way I evalState there. In that case I wouldn't wait for the State s action to finish. Thanks 2008/12/31 Derek Elkins derek.a.elk...@gmail.com On Wed, 2008-12-31 at 21:48 +0100, Paolino wrote: As someone suggested me, I can read the logs from Writer and WriterT as computation goes by, if the monoid for the Writer is lazy readable. This has been true until I tried to put the IO inside WriterT {-# LANGUAGE FlexibleContexts #-} import Control.Monad.Writer k :: (MonadWriter [Int] m) = m [Int] k = let f x = tell [x] f (x + 1) in f 0 works :: [Int] works = snd $ runWriter k hangs :: IO [Int] hangs = snd `liftM` runWriterT k runWriterT :: MonadWriter w m a = WriterT w m a - m (a, w) which is to say runWriterT k :: IO (a, [Int]) It's not going to return anything until the IO action terminates, which is to say never. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] WriterT [w] IO is not lazy in reading [w]
How do I read IO is not lazy ? Is IO (=) forcing the evaluation of its arguments, causing the unwanted neverending loop? And, this happens even in (MonadTrans t = t IO) (=) ? Thanks paolino 2008/12/31 Ryan Ingram ryani.s...@gmail.com IO is not lazy; you never make it to print. Consider this program: k = f 0 where f n = do lift (print n) tell [n] f (n+1) weird :: IO [Int] weird = do (_, ns) - runWriterT k return (take 20 ns) What should weird print? According to k, it prints every Int from 0 up. Aside from the extra printing, it has the same behavior as your writer. For the result of a WriterT to be lazy readable, you need both the monoid to be lazy readable, and the transformed monad to be lazy, which IO isn't. -- ryan 2008/12/31 Paolino paolo.verone...@gmail.com: As someone suggested me, I can read the logs from Writer and WriterT as computation goes by, if the monoid for the Writer is lazy readable. This has been true until I tried to put the IO inside WriterT {-# LANGUAGE FlexibleContexts #-} import Control.Monad.Writer k :: (MonadWriter [Int] m) = m [Int] k = let f x = tell [x] f (x + 1) in f 0 works :: [Int] works = snd $ runWriter k hangs :: IO [Int] hangs = snd `liftM` runWriterT k main = take 20 `liftM` hangs = print The main hangs both interpreted and compiled on ghc 6.10.1. The issue is not exposing with IO alone as main = print test main is a working program. Thanks for explanations. paolino ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] Parsing words with parsec
On 3/30/07, Stefan O'Rear [EMAIL PROTECTED] wrote: On Fri, Mar 30, 2007 at 05:43:34AM +0200, paolino wrote: Hi, I had a bad time trying to parse the words of a text. I suspect I miss some parsec knowledge. I'd start by not sextuple-posting, it just sextuples the ugliness ;-) Mhh, still I don't see any them in my inbox mails , probably something buggy in gmail configuration, sorry :/. import Char( isAlpha ) import List( groupBy ) equating f x y = f x == f y -- in Data.Eq, iff you have GHC 6.7 isLetter x = isAlpha x || x == '_' || x == '@' myWords = filter (isLetter . head) . groupBy (equating isLetter) Testing your code, it misses the words with numbers inside exclusion and uses the number as separators. !runhaskell prova.hs [[EMAIL PROTECTED],sara,mimmo,ab,a,b,ab,cd] Thanks ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] A simple parsing task for parsec.
Hi, I had a bad time trying to parse the words of a text. I suspect I miss some parsec knowledge. In the end it seems working, though I haven't tested much and this example contains the main features I was looking. *Main parseTest (parseLine eof) [EMAIL PROTECTED] sara,mimmo! 9ab a9b ab9 cd\n [[EMAIL PROTECTED],sara,mimmo,cd] - manyTillT body terminator joiner = liftM2 joiner (manyTill body (lookAhead terminator)) terminator wordChar = letter | oneOf _@ ? a valid word character nonSeparator = wordChar | digit wordEnd = do x - wordChar notFollowedBy nonSeparator return x word = manyTillT wordChar (try wordEnd) (\b t - b ++ [t]) ? a word wordStart = do (try nonSeparator unexpected non separator) | anyChar lookAhead wordChar nextWord = manyTill anyChar (try wordStart) (try word | nextWord) parseLine end = do f - option [] $ return `fmap` try word r - many $ try nextWord manyTill anyChar end return (f ++ r) --- Any comment to simplify this code is welcome. Paolino. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] Parsing words with parsec
Hi, I had a bad time trying to parse the words of a text. I suspect I miss some parsec knowledge. In the end it seems working, though I haven't tested much and this example contains the main features I was looking. *Main parseTest (parseLine eof) [EMAIL PROTECTED] sara,mimmo! 9ab a9b ab9 cd\n [[EMAIL PROTECTED],sara,mimmo,cd] - manyTillT body terminator joiner = liftM2 joiner (manyTill body (lookAhead terminator)) terminator wordChar = letter | oneOf _@ ? a valid word character nonSeparator = wordChar | digit wordEnd = do x - wordChar notFollowedBy nonSeparator return x word = manyTillT wordChar (try wordEnd) (\b t - b ++ [t]) ? a word wordStart = do (try nonSeparator unexpected non separator) | anyChar lookAhead wordChar nextWord = manyTill anyChar (try wordStart) (try word | nextWord) parseLine end = do f - option [] $ return `fmap` try word r - many $ try nextWord manyTill anyChar end return (f ++ r) --- Any comment to simplify this code is welcome. Paolino. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
[Haskell-cafe] Parsing words with parsec
Hi, I had a bad time trying to parse the words of a text. I suspect I miss some parsec knowledge. In the end it seems working, though I haven't tested much and this example contains the main features I was looking. *Main parseTest (parseLine eof) [EMAIL PROTECTED] sara,mimmo! 9ab a9b ab9 cd\n [[EMAIL PROTECTED],sara,mimmo,cd] - manyTillT body terminator joiner = liftM2 joiner (manyTill body (lookAhead terminator)) terminator wordChar = letter | oneOf _@ ? a valid word character nonSeparator = wordChar | digit wordEnd = do x - wordChar notFollowedBy nonSeparator return x word = manyTillT wordChar (try wordEnd) (\b t - b ++ [t]) ? a word wordStart = do (try nonSeparator unexpected non separator) | anyChar lookAhead wordChar nextWord = manyTill anyChar (try wordStart) (try word | nextWord) parseLine end = do f - option [] $ return `fmap` try word r - many $ try nextWord manyTill anyChar end return (f ++ r) --- Any comment to simplify this code is welcome. Paolino. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe