From brutallesale at gmail.com Mon Jan 2 17:05:57 2017 From: brutallesale at gmail.com (sasa bogicevic) Date: Mon, 2 Jan 2017 18:05:57 +0100 Subject: [Haskell-beginners] fnc explanation Message-ID: <4F6F35F4-E3FB-41FD-9EE5-BF8BD3FD27FA@gmail.com> Hi, I have some trouble understanding the following function: http://lpaste.net/350771 If someone can take the time and explain the part after WHERE clause that would be great since I kind of know what the function does but have problems with the param order for the go anonymous function. Thanks, Sasa { name: Bogicevic Sasa phone: +381606006200 } From daniel.trstenjak at gmail.com Mon Jan 2 17:20:58 2017 From: daniel.trstenjak at gmail.com (Daniel Trstenjak) Date: Mon, 2 Jan 2017 18:20:58 +0100 Subject: [Haskell-beginners] fnc explanation In-Reply-To: <4F6F35F4-E3FB-41FD-9EE5-BF8BD3FD27FA@gmail.com> References: <4F6F35F4-E3FB-41FD-9EE5-BF8BD3FD27FA@gmail.com> Message-ID: <20170102172058.GA28689@octa> Hi Sasa, > -- this confuses me, what is the _ here ? go is anonymous function, _ should stand for tuple ? and status xs from the top definition ? > go _ status@(_, False) = status The first argument of 'go' is '_', which means it's ignored. The second argument is 'status@(_, False)'. It's giving the tuple the name 'status' and pattern matching the tuple at once. If the pattern match succeeds, then the tuple named 'status' is returned by 'go' Greetings, Daniel From vale.cofershabica at gmail.com Mon Jan 2 21:21:31 2017 From: vale.cofershabica at gmail.com (Vale Cofer-Shabica) Date: Mon, 2 Jan 2017 16:21:31 -0500 Subject: [Haskell-beginners] fnc explanation In-Reply-To: <20170102172058.GA28689@octa> References: <4F6F35F4-E3FB-41FD-9EE5-BF8BD3FD27FA@gmail.com> <20170102172058.GA28689@octa> Message-ID: Hi Sasa, It might also help to look at the type of foldr: foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b The function go has type: go :: Ord a => a -> (Maybe a, Bool) -> (Maybe a, Bool) The tuple, initially (Nothing, True), will be passed to go as its *2nd* argument; the first argument will be an element of the list. The underscore, which means match anything and throw it away, is there because we don't care about any of the other elements once we know the list is not ordered. Hope that helps, vale -- vale cofer-shabica 401.267.8253 On Mon, Jan 2, 2017 at 12:20 PM, Daniel Trstenjak < daniel.trstenjak at gmail.com> wrote: > > Hi Sasa, > > > -- this confuses me, what is the _ here ? go is anonymous function, _ > should stand for tuple ? and status xs from the top definition ? > > go _ status@(_, False) = status > > The first argument of 'go' is '_', which means it's ignored. > > The second argument is 'status@(_, False)'. > It's giving the tuple the name 'status' and pattern matching the tuple at > once. > > If the pattern match succeeds, then the tuple named 'status' is returned > by 'go' > > > Greetings, > Daniel > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From brutallesale at gmail.com Mon Jan 2 22:59:36 2017 From: brutallesale at gmail.com (sasa bogicevic) Date: Mon, 2 Jan 2017 23:59:36 +0100 Subject: [Haskell-beginners] fnc explanation In-Reply-To: References: <4F6F35F4-E3FB-41FD-9EE5-BF8BD3FD27FA@gmail.com> <20170102172058.GA28689@octa> Message-ID: <1E922DF6-0379-4EBF-B82D-C2DA57D30B55@gmail.com> Thanks! I had to look at it multiple times to get it but it is clear now. It is still not intuitive for me since I come from imperative language world but I guess time heals all :) Thanks once again! Sasa Sasa Bogicevic { phone: +381606006200 } > On Jan 2, 2017, at 22:21, Vale Cofer-Shabica wrote: > > Hi Sasa, > > It might also help to look at the type of foldr: > foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b > > The function go has type: > go :: Ord a => a -> (Maybe a, Bool) -> (Maybe a, Bool) > > The tuple, initially (Nothing, True), will be passed to go as its *2nd* argument; the first argument will be an element of the list. The underscore, which means match anything and throw it away, is there because we don't care about any of the other elements once we know the list is not ordered. > > Hope that helps, > vale > > > -- > vale cofer-shabica > 401.267.8253 > >> On Mon, Jan 2, 2017 at 12:20 PM, Daniel Trstenjak wrote: >> >> Hi Sasa, >> >> > -- this confuses me, what is the _ here ? go is anonymous function, _ should stand for tuple ? and status xs from the top definition ? >> > go _ status@(_, False) = status >> >> The first argument of 'go' is '_', which means it's ignored. >> >> The second argument is 'status@(_, False)'. >> It's giving the tuple the name 'status' and pattern matching the tuple at once. >> >> If the pattern match succeeds, then the tuple named 'status' is returned by 'go' >> >> >> Greetings, >> Daniel >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From mike_k_houghton at yahoo.co.uk Sun Jan 8 20:06:33 2017 From: mike_k_houghton at yahoo.co.uk (mike h) Date: Sun, 8 Jan 2017 20:06:33 +0000 Subject: [Haskell-beginners] Rose tree Message-ID: Hi, I’m rapidly descending into a spiral of confusion! :) How do I add something to a rose tree? I have data Tree a = Node a [Tree a] deriving (Show) add :: Eq a => a -> a -> Tree a -> Tree a and the first ‘a’ is the thing to add and the second is its parent node. i.e. add :: Eq a => a -> a -> Tree a -> Tree a add x px (Node x' []) = Node x' [Node x []] ….. I’ve tried various ways for the more general case but always seem to lose part of the tree. Any advice would be very welcome. Thanks Mike From brutallesale at gmail.com Mon Jan 9 15:41:39 2017 From: brutallesale at gmail.com (sasa bogicevic) Date: Mon, 9 Jan 2017 16:41:39 +0100 Subject: [Haskell-beginners] Functor instance Message-ID: Hi all, Can someone explain to me why exactly when defining the Functor instance for type that has polimorphic parameter constraint I am not allowed to put that parameter in definition. So basically: data Four a b c d = Four a b c d instance Functor (Four a b c) where <-- why can't I specify also param d here ?? fmap f (Four a b c d) = Four a b c (f d) I asked the same question on IRC and got the answer that it is because of Functor has kind * -> *. I thought I understand it but it is not clear to me completely. I understand type kinds on examples I looked at before but when looking at this Functor instance why exactly I don't specify all params for the type and while we are at it why don't I also specify f param for the Functor like this "instance Functor f (Four a b c d) where ...". Thanks, Sasa { name: Bogicevic Sasa phone: +381606006200 } From fa-ml at ariis.it Mon Jan 9 16:00:55 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Mon, 9 Jan 2017 17:00:55 +0100 Subject: [Haskell-beginners] Functor instance In-Reply-To: References: Message-ID: <20170109160055.GA9425@casa.casa> On Mon, Jan 09, 2017 at 04:41:39PM +0100, sasa bogicevic wrote: > Hi all, > Can someone explain to me why exactly when defining the Functor > instance for type that has polimorphic parameter constraint I > am not allowed to put that parameter in definition. So basically: > > data Four a b c d = Four a b c d > > instance Functor (Four a b c) where <-- why can't I specify also > param d here ?? > fmap f (Four a b c d) = Four a b c (f d) Hello Sasa, think for a moment about functors you already know: Maybe a, [a], (Either e) a, etc. In every case there is an `a` and something preceding a (we can call it `f`). Now let's look at the class-definition of functor. class Functor f where -- etc. etc. Here you have it, `f`; so for the instance you should only place the `f`-part in there, like instance Functor Maybe where -- not Maybe a! instance Functor (Four a b c) where -- without the a too! It makes sense as `f` will stay the same and `a` will be mapped over (and change). Indeed you can very this with ghci (using :k Functor, :k Maybe etc.), but after a while it sinks in. Does this help? From mihai.maruseac at gmail.com Mon Jan 9 16:05:23 2017 From: mihai.maruseac at gmail.com (Mihai Maruseac) Date: Mon, 9 Jan 2017 08:05:23 -0800 Subject: [Haskell-beginners] Functor instance In-Reply-To: References: Message-ID: If you imagine a type as a box with some slots (each slot for each type variable), Functor only allows you to map on the last slot. That and the currying of functions lead to the intuition behind "Functor has kind * -> *" (aka: you need the type for the last slot to fully build the type that would be an instance of Functor) On Mon, Jan 9, 2017 at 7:41 AM, sasa bogicevic wrote: > Hi all, > Can someone explain to me why exactly when defining the Functor instance for type that has polimorphic parameter constraint I am not allowed to put that parameter in definition. So basically: > > data Four a b c d = Four a b c d > > instance Functor (Four a b c) where <-- why can't I specify also param d here ?? > fmap f (Four a b c d) = Four a b c (f d) > > I asked the same question on IRC and got the answer that it is because of Functor has kind * -> *. I thought I understand it but it is not clear to me completely. I understand type kinds on examples I looked at before but > when looking at this Functor instance why exactly I don't specify all params for the type and while we are at it why don't I also specify f param for the Functor like this "instance Functor f (Four a b c d) where ...". > > Thanks, Sasa > { > name: Bogicevic Sasa > phone: +381606006200 > } > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -- Mihai Maruseac (MM) "If you can't solve a problem, then there's an easier problem you can solve: find it." -- George Polya From brutallesale at gmail.com Mon Jan 9 16:26:12 2017 From: brutallesale at gmail.com (sasa bogicevic) Date: Mon, 9 Jan 2017 17:26:12 +0100 Subject: [Haskell-beginners] Functor instance In-Reply-To: <20170109160055.GA9425@casa.casa> References: <20170109160055.GA9425@casa.casa> Message-ID: <34F367D7-867F-4CF3-838E-04989D75747F@gmail.com> Good explanation! Thanks I understand it now Sasa Bogicevic { phone: +381606006200 } > On Jan 9, 2017, at 17:00, Francesco Ariis wrote: > >> On Mon, Jan 09, 2017 at 04:41:39PM +0100, sasa bogicevic wrote: >> Hi all, >> Can someone explain to me why exactly when defining the Functor >> instance for type that has polimorphic parameter constraint I >> am not allowed to put that parameter in definition. So basically: >> >> data Four a b c d = Four a b c d >> >> instance Functor (Four a b c) where <-- why can't I specify also >> param d here ?? >> fmap f (Four a b c d) = Four a b c (f d) > > Hello Sasa, > think for a moment about functors you already know: Maybe a, [a], > (Either e) a, etc. In every case there is an `a` and something preceding > a (we can call it `f`). > Now let's look at the class-definition of functor. > > class Functor f where -- etc. etc. > > Here you have it, `f`; so for the instance you should only place > the `f`-part in there, like > > instance Functor Maybe where -- not Maybe a! > instance Functor (Four a b c) where -- without the a too! > > It makes sense as `f` will stay the same and `a` will be mapped over > (and change). > Indeed you can very this with ghci (using :k Functor, :k Maybe etc.), > but after a while it sinks in. > > Does this help? > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From toad3k at gmail.com Mon Jan 9 16:40:23 2017 From: toad3k at gmail.com (David McBride) Date: Mon, 9 Jan 2017 11:40:23 -0500 Subject: [Haskell-beginners] Functor instance In-Reply-To: <34F367D7-867F-4CF3-838E-04989D75747F@gmail.com> References: <20170109160055.GA9425@casa.casa> <34F367D7-867F-4CF3-838E-04989D75747F@gmail.com> Message-ID: There is also a BiFunctor in base which allows you to fmap over the last two variables in your type. bimap :: (a -> b) -> (c -> d) -> p a c -> p b d And it conveniently has methods to map over only one at a time, if you want. first :: (a -> b) -> p a c -> p b c second :: (b -> c) -> p a b -> p a c This makes sense for types like Either a b, where sometimes you might want to fmap over one or both values. However, going beyond two would cause the number of options for mapping over such a type to blow up. At that point it is better to just use your own simple function to map over your own type. On Mon, Jan 9, 2017 at 11:26 AM, sasa bogicevic wrote: > Good explanation! Thanks I understand it now > > Sasa Bogicevic > { > phone: +381606006200 > } > >> On Jan 9, 2017, at 17:00, Francesco Ariis wrote: >> >>> On Mon, Jan 09, 2017 at 04:41:39PM +0100, sasa bogicevic wrote: >>> Hi all, >>> Can someone explain to me why exactly when defining the Functor >>> instance for type that has polimorphic parameter constraint I >>> am not allowed to put that parameter in definition. So basically: >>> >>> data Four a b c d = Four a b c d >>> >>> instance Functor (Four a b c) where <-- why can't I specify also >>> param d here ?? >>> fmap f (Four a b c d) = Four a b c (f d) >> >> Hello Sasa, >> think for a moment about functors you already know: Maybe a, [a], >> (Either e) a, etc. In every case there is an `a` and something preceding >> a (we can call it `f`). >> Now let's look at the class-definition of functor. >> >> class Functor f where -- etc. etc. >> >> Here you have it, `f`; so for the instance you should only place >> the `f`-part in there, like >> >> instance Functor Maybe where -- not Maybe a! >> instance Functor (Four a b c) where -- without the a too! >> >> It makes sense as `f` will stay the same and `a` will be mapped over >> (and change). >> Indeed you can very this with ghci (using :k Functor, :k Maybe etc.), >> but after a while it sinks in. >> >> Does this help? >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From brutallesale at gmail.com Mon Jan 9 18:07:17 2017 From: brutallesale at gmail.com (sasa bogicevic) Date: Mon, 9 Jan 2017 19:07:17 +0100 Subject: [Haskell-beginners] Functor instance In-Reply-To: References: <20170109160055.GA9425@casa.casa> <34F367D7-867F-4CF3-838E-04989D75747F@gmail.com> Message-ID: <452E2D46-E198-4876-B948-47A75B03ED61@gmail.com> I will look at bimap too, sounds usefull, thanks! Sasa Bogicevic { phone: +381606006200 } > On Jan 9, 2017, at 17:40, David McBride wrote: > > There is also a BiFunctor in base which allows you to fmap over the > last two variables in your type. > > bimap :: (a -> b) -> (c -> d) -> p a c -> p b d > > And it conveniently has methods to map over only one at a time, if you want. > > first :: (a -> b) -> p a c -> p b c > second :: (b -> c) -> p a b -> p a c > > This makes sense for types like Either a b, where sometimes you might > want to fmap over one or both values. > > However, going beyond two would cause the number of options for > mapping over such a type to blow up. At that point it is better to > just use your own simple function to map over your own type. > >> On Mon, Jan 9, 2017 at 11:26 AM, sasa bogicevic wrote: >> Good explanation! Thanks I understand it now >> >> Sasa Bogicevic >> { >> phone: +381606006200 >> } >> >>>> On Jan 9, 2017, at 17:00, Francesco Ariis wrote: >>>> >>>> On Mon, Jan 09, 2017 at 04:41:39PM +0100, sasa bogicevic wrote: >>>> Hi all, >>>> Can someone explain to me why exactly when defining the Functor >>>> instance for type that has polimorphic parameter constraint I >>>> am not allowed to put that parameter in definition. So basically: >>>> >>>> data Four a b c d = Four a b c d >>>> >>>> instance Functor (Four a b c) where <-- why can't I specify also >>>> param d here ?? >>>> fmap f (Four a b c d) = Four a b c (f d) >>> >>> Hello Sasa, >>> think for a moment about functors you already know: Maybe a, [a], >>> (Either e) a, etc. In every case there is an `a` and something preceding >>> a (we can call it `f`). >>> Now let's look at the class-definition of functor. >>> >>> class Functor f where -- etc. etc. >>> >>> Here you have it, `f`; so for the instance you should only place >>> the `f`-part in there, like >>> >>> instance Functor Maybe where -- not Maybe a! >>> instance Functor (Four a b c) where -- without the a too! >>> >>> It makes sense as `f` will stay the same and `a` will be mapped over >>> (and change). >>> Indeed you can very this with ghci (using :k Functor, :k Maybe etc.), >>> but after a while it sinks in. >>> >>> Does this help? >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From mike_k_houghton at yahoo.co.uk Mon Jan 9 21:06:35 2017 From: mike_k_houghton at yahoo.co.uk (mike h) Date: Mon, 9 Jan 2017 21:06:35 +0000 Subject: [Haskell-beginners] Rose tree In-Reply-To: References: Message-ID: <447E2083-42AF-4BA9-84C0-BAA2A5F4C3B8@yahoo.co.uk> add :: Eq a => a -> a -> RoseTree a -> RoseTree a add x px (Node x' []) = Node x' [Node x []] add x px (Node x' trees) | px == x' = Node x' $ (Node x []):trees | otherwise = Node x' $ (add x px) <$> trees seems to be correct. :) > On 8 Jan 2017, at 20:06, mike h wrote: > > Hi, > > I’m rapidly descending into a spiral of confusion! :) > > How do I add something to a rose tree? > > I have > > data Tree a = Node a [Tree a] deriving (Show) > > add :: Eq a => a -> a -> Tree a -> Tree a > > and the first ‘a’ is the thing to add and the second is its parent node. > i.e. > add :: Eq a => a -> a -> Tree a -> Tree a > add x px (Node x' []) = Node x' [Node x []] > ….. > > I’ve tried various ways for the more general case but always seem to lose part of the tree. > > Any advice would be very welcome. > > Thanks > > Mike From vmk8993 at gmail.com Tue Jan 10 02:17:17 2017 From: vmk8993 at gmail.com (Manikanda Krishnan) Date: Tue, 10 Jan 2017 07:47:17 +0530 Subject: [Haskell-beginners] Autogenerating tuple constructor of length n Message-ID: Hi, I am exploring haskell. Is there a way to generate a tuple constructor of n elements at runtime? Basically I want to convert a list of lists into a list of n tuples. Thanks in advance Mani -------------- next part -------------- An HTML attachment was scrubbed... URL: From dennis.raddle at gmail.com Tue Jan 10 02:45:05 2017 From: dennis.raddle at gmail.com (Dennis Raddle) Date: Mon, 9 Jan 2017 18:45:05 -0800 Subject: [Haskell-beginners] dynamic code compilation and loading Message-ID: Can I get a pointer to how to do dynamic code compilation and loading into a running program? D -------------- next part -------------- An HTML attachment was scrubbed... URL: From mva.led at gmail.com Tue Jan 10 22:46:23 2017 From: mva.led at gmail.com (=?utf-8?Q?Manuel_V=C3=A1zquez_Acosta?=) Date: Tue, 10 Jan 2017 17:46:23 -0500 Subject: [Haskell-beginners] Runtime error while feeding a binary to stdin Message-ID: <87r34acz40.fsf@pavla.com> Hi all, I'm quite new to Haskell. While following the "Real World Haskell" and doing some experimentation I came up with a anoying situation: Trying to read data from stdin it seems that binary data is not allowed. A simple "copy" program: -- file: copy.hs import System.IO main = do input <- hGetContents stdin hPutStr input Fails when I run it like: $ ghc copy.hs $ ./copy < input > output copy: : hGetContents: invalid argument (invalid byte sequence) input contains binary data. In fact of all the following programs only the first works with binary data: copy:: IO () copy = do bracket (openBinaryFile "input" ReadMode) hClose $ \hi -> do bracket (openBinaryFile "ouput" WriteMode) hClose $ \ho -> do input <- hGetContents hi hPutStr ho input copy2:: IO () copy2 = do -- Doesn't work with binary files source <- readFile "input" writeFile "output" source copy3:: IO () copy3 = do -- Doesn't work with binary files either interact (map $ \x -> x) copy4:: IO () copy4 = do input <- hGetContents stdin hPutStr stdout input But I lost any chance of piping and/or using '<', '>' in the shell. Best regards, Manuel. From tanuki at gmail.com Wed Jan 11 02:30:36 2017 From: tanuki at gmail.com (Theodore Lief Gannon) Date: Tue, 10 Jan 2017 18:30:36 -0800 Subject: [Haskell-beginners] Runtime error while feeding a binary to stdin In-Reply-To: <87r34acz40.fsf@pavla.com> References: <87r34acz40.fsf@pavla.com> Message-ID: Those System.IO functions *are* String-specific. Try the equivalents from Data.ByteString: http://hackage.haskell.org/package/bytestring-0.10.8.1/docs/Data-ByteString.html#g:29 On Tue, Jan 10, 2017 at 2:46 PM, Manuel Vázquez Acosta wrote: > Hi all, > > I'm quite new to Haskell. While following the "Real World Haskell" and > doing some experimentation I came up with a anoying situation: > > Trying to read data from stdin it seems that binary data is not > allowed. A simple "copy" program: > > > -- file: copy.hs > import System.IO > > main = do > input <- hGetContents stdin > hPutStr input > > Fails when I run it like: > > $ ghc copy.hs > $ ./copy < input > output > copy: : hGetContents: invalid argument (invalid byte sequence) > > input contains binary data. In fact of all the following programs only > the first works with binary data: > > copy:: IO () > copy = do > bracket (openBinaryFile "input" ReadMode) hClose $ \hi -> do > bracket (openBinaryFile "ouput" WriteMode) hClose $ \ho -> do > input <- hGetContents hi > hPutStr ho input > > > copy2:: IO () > copy2 = do > -- Doesn't work with binary files > source <- readFile "input" > writeFile "output" source > > > copy3:: IO () > copy3 = do > -- Doesn't work with binary files either > interact (map $ \x -> x) > > > copy4:: IO () > copy4 = do > input <- hGetContents stdin > hPutStr stdout input > > > But I lost any chance of piping and/or using '<', '>' in the shell. > > Best regards, > Manuel. > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mva.led at gmail.com Wed Jan 11 13:27:51 2017 From: mva.led at gmail.com (Manuel) Date: Wed, 11 Jan 2017 08:27:51 -0500 Subject: [Haskell-beginners] Runtime error while feeding a binary to stdin In-Reply-To: (Theodore Lief Gannon's message of "Tue, 10 Jan 2017 18:30:36 -0800") References: <87r34acz40.fsf@pavla.com> Message-ID: <87mvexvi94.fsf@pavla.com> Theodore Lief Gannon writes: Hi Theodore, Thanks, I didn't know about those functions. Best regards, Manuel. > Those System.IO functions *are* String-specific. Try the equivalents from > Data.ByteString: > > http://hackage.haskell.org/package/bytestring-0.10.8.1/docs/Data-ByteString.html#g:29 > > On Tue, Jan 10, 2017 at 2:46 PM, Manuel Vázquez Acosta > wrote: > >> Hi all, >> >> I'm quite new to Haskell. While following the "Real World Haskell" and >> doing some experimentation I came up with a anoying situation: >> >> Trying to read data from stdin it seems that binary data is not >> allowed. A simple "copy" program: >> >> >> -- file: copy.hs >> import System.IO >> >> main = do >> input <- hGetContents stdin >> hPutStr input >> >> Fails when I run it like: >> >> $ ghc copy.hs >> $ ./copy < input > output >> copy: : hGetContents: invalid argument (invalid byte sequence) >> >> input contains binary data. In fact of all the following programs only >> the first works with binary data: >> >> copy:: IO () >> copy = do >> bracket (openBinaryFile "input" ReadMode) hClose $ \hi -> do >> bracket (openBinaryFile "ouput" WriteMode) hClose $ \ho -> do >> input <- hGetContents hi >> hPutStr ho input >> >> >> copy2:: IO () >> copy2 = do >> -- Doesn't work with binary files >> source <- readFile "input" >> writeFile "output" source >> >> >> copy3:: IO () >> copy3 = do >> -- Doesn't work with binary files either >> interact (map $ \x -> x) >> >> >> copy4:: IO () >> copy4 = do >> input <- hGetContents stdin >> hPutStr stdout input >> >> >> But I lost any chance of piping and/or using '<', '>' in the shell. >> >> Best regards, >> Manuel. >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From cmscalzo at gmail.com Thu Jan 12 15:44:24 2017 From: cmscalzo at gmail.com (Carlo Matteo Scalzo) Date: Thu, 12 Jan 2017 15:44:24 +0000 Subject: [Haskell-beginners] Feedback needed - CLI app + guide In-Reply-To: References: Message-ID: Hi all, I'm new to the community here, so please do let me know if I'm doing something wrong :-) I've been learning Haskell over the last year or so, reading books etc., but I couldn't find a simple, real world example, so I decided to to write a simple command-line application in Haskell. The application and the code are free, and I've also written a short guide that uses the application as a use case to talk about Haskell and its features. Can you guys please download the guide (for free, of course) , and let me know if you found it useful? You can find it here: https://fifohaskell.com Please let me have your feedback (my personal email is on the website, if you don't want to reply here) - and thank you very much for your help! Carlo -------------- next part -------------- An HTML attachment was scrubbed... URL: From shamsi.saqib at gmail.com Fri Jan 13 16:05:54 2017 From: shamsi.saqib at gmail.com (Saqib Shamsi) Date: Fri, 13 Jan 2017 21:35:54 +0530 Subject: [Haskell-beginners] Better Code Message-ID: Hi, The problem that I wish to solve is to divide a (sored) list of integers into sublists such that each sublist contains numbers in consecutive sequence. For example, *Input:* [1,2,3,7,8,10,11,12] *Output:* [[1,2,3],[7,8],[10,11,12]] I have written the following code and it does the trick. -- Take a list and divide it at first point of non-consecutive number encounter divide :: [Int] -> [Int] -> ([Int], [Int]) divide first [] = (first, []) divide first second = if (last first) /= firstSecond - 1 then (first, second) else divide (first ++ [firstSecond]) (tail second) where firstSecond = head second -- Helper for breaking a list of numbers into consecutive sublists breakIntoConsecsHelper :: [Int] -> [[Int]] -> [[Int]] breakIntoConsecsHelper [] [[]] = [[]] breakIntoConsecsHelper lst ans = if two == [] then ans ++ [one] else ans ++ [one] ++ breakIntoConsecsHelper two [] where firstElem = head lst remaining = tail lst (one, two) = divide [firstElem] remaining -- Break the list into sublists of consective numbers breakIntoConsecs :: [Int] -> [[Int]] breakIntoConsecs lst = breakIntoConsecsHelper lst [[]] -- Take the tail of the result given by the function above to get the required list of lists. However, I was wondering if there was a better way of doing this. Any help would be highly appreciated. Thank you. Best Regards, Saqib Shamsi -------------- next part -------------- An HTML attachment was scrubbed... URL: From fa-ml at ariis.it Fri Jan 13 16:55:16 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Fri, 13 Jan 2017 17:55:16 +0100 Subject: [Haskell-beginners] Better Code In-Reply-To: References: Message-ID: <20170113165516.GB23022@casa.casa> On Fri, Jan 13, 2017 at 09:35:54PM +0530, Saqib Shamsi wrote: > The problem that I wish to solve is to divide a (sored) list of integers > into sublists such that each sublist contains numbers in consecutive > sequence. > > For example, > *Input:* [1,2,3,7,8,10,11,12] > *Output:* [[1,2,3],[7,8],[10,11,12]] > > [...] > > However, I was wondering if there was a better way of doing this. Any help > would be highly appreciated. Hello Saquib, you could try using a 'trick' like this: λ> zipWith (-) [1,2,3,7,8,10,11,12] (enumFrom 1) [0,0,0,3,3,4,4,4] Now you have an 'helper' list which can be glued to the first one with zip λ> zip [1,2,3,7,8,10,11,12] it [(1,0),(2,0),(3,0),(7,3),(8,3),(10,4),(11,4),(12,4)] and now grouped by using `groupBy` in Data.List. Does that help? From joel.neely at gmail.com Fri Jan 13 17:40:57 2017 From: joel.neely at gmail.com (Joel Neely) Date: Fri, 13 Jan 2017 11:40:57 -0600 Subject: [Haskell-beginners] Better Code In-Reply-To: <20170113165516.GB23022@casa.casa> References: <20170113165516.GB23022@casa.casa> Message-ID: The "helper list" technique is ingenious, but seems very specific to Int as the type within the list. I have had other tasks that seem to fit a more generalized problem statement, of which the original question appears to me as special case: Given a criterion of type a -> a -> Bool and a list [a], produce a list of lists [[a]] in which sub-lists are made up of consecutive elements from the original list that satisfy the criterion. It appears to me that List.groupBy may meet that need, but I'm not able to verify that at the moment (and would be glad of feedback). -jn- On Fri, Jan 13, 2017 at 10:55 AM, Francesco Ariis wrote: > On Fri, Jan 13, 2017 at 09:35:54PM +0530, Saqib Shamsi wrote: > > The problem that I wish to solve is to divide a (sored) list of integers > > into sublists such that each sublist contains numbers in consecutive > > sequence. > > > > For example, > > *Input:* [1,2,3,7,8,10,11,12] > > *Output:* [[1,2,3],[7,8],[10,11,12]] > > > > [...] > > > > However, I was wondering if there was a better way of doing this. Any > help > > would be highly appreciated. > > Hello Saquib, > you could try using a 'trick' like this: > > λ> zipWith (-) [1,2,3,7,8,10,11,12] (enumFrom 1) > [0,0,0,3,3,4,4,4] > > Now you have an 'helper' list which can be glued to the first one > with zip > > λ> zip [1,2,3,7,8,10,11,12] it > [(1,0),(2,0),(3,0),(7,3),(8,3),(10,4),(11,4),(12,4)] > > and now grouped by using `groupBy` in Data.List. > > Does that help? > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -- Beauty of style and harmony and grace and good rhythm depend on simplicity. - Plato -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.neely at gmail.com Fri Jan 13 19:14:56 2017 From: joel.neely at gmail.com (Joel Neely) Date: Fri, 13 Jan 2017 13:14:56 -0600 Subject: [Haskell-beginners] Better Code In-Reply-To: References: Message-ID: Had a chance to chat with ghci, so earlier conjecture not confirmed: Prelude Data.List> groupBy (\x y -> x == y-1) [1,2,3,7,8,10,11,12] [[1,2],[3],[7,8],[10,11],[12]] So close but no cigar. On Fri, Jan 13, 2017 at 10:05 AM, Saqib Shamsi wrote: > Hi, > > The problem that I wish to solve is to divide a (sored) list of integers > into sublists such that each sublist contains numbers in consecutive > sequence. > > For example, > *Input:* [1,2,3,7,8,10,11,12] > *Output:* [[1,2,3],[7,8],[10,11,12]] > > I have written the following code and it does the trick. > > -- Take a list and divide it at first point of non-consecutive number > encounter > divide :: [Int] -> [Int] -> ([Int], [Int]) > divide first [] = (first, []) > divide first second = if (last first) /= firstSecond - 1 then (first, > second) > else divide (first ++ [firstSecond]) (tail second) > where firstSecond = head second > > > -- Helper for breaking a list of numbers into consecutive sublists > breakIntoConsecsHelper :: [Int] -> [[Int]] -> [[Int]] > breakIntoConsecsHelper [] [[]] = [[]] > breakIntoConsecsHelper lst ans = if two == [] then ans ++ [one] > else ans ++ [one] ++ > breakIntoConsecsHelper two [] > where > firstElem = head lst > remaining = tail lst > (one, two) = divide [firstElem] > remaining > > > -- Break the list into sublists of consective numbers > breakIntoConsecs :: [Int] -> [[Int]] > breakIntoConsecs lst = breakIntoConsecsHelper lst [[]] > > -- Take the tail of the result given by the function above to get the > required list of lists. > > However, I was wondering if there was a better way of doing this. Any help > would be highly appreciated. > > Thank you. > Best Regards, > Saqib Shamsi > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Beauty of style and harmony and grace and good rhythm depend on simplicity. - Plato -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmscalzo at gmail.com Fri Jan 13 22:43:27 2017 From: cmscalzo at gmail.com (Carlo Matteo Scalzo) Date: Fri, 13 Jan 2017 22:43:27 +0000 Subject: [Haskell-beginners] Better Code Message-ID: Hi Saqib, perhaps something like this? divide :: [Int] -> [[Int]] divide [] = [] divide (x:xs) = divideAux xs [] [x] x divideAux :: [Int] -> [[Int]] -> [Int] -> Int -> [[Int]] divideAux [] result current max = result ++ [current] divideAux (x:xs) result current max = if x - max > 1 then divideAux xs (result ++ [current]) [x] x else divideAux xs result (current ++ [x]) x This can of course be generalised to other types (as per Joel's requirement) just by replacing the check on line 7, i.e., 'x - max > 1'. Happy to explain/talk about the code if you'd like me to :-) Cheers, Carlo On Fri, Jan 13, 2017 at 7:14 PM, Joel Neely wrote: > Had a chance to chat with ghci, so earlier conjecture not confirmed: > > Prelude Data.List> groupBy (\x y -> x == y-1) [1,2,3,7,8,10,11,12] > > [[1,2],[3],[7,8],[10,11],[12]] > > So close but no cigar. > > On Fri, Jan 13, 2017 at 10:05 AM, Saqib Shamsi > wrote: > >> Hi, >> >> The problem that I wish to solve is to divide a (sored) list of integers >> into sublists such that each sublist contains numbers in consecutive >> sequence. >> >> For example, >> *Input:* [1,2,3,7,8,10,11,12] >> *Output:* [[1,2,3],[7,8],[10,11,12]] >> >> I have written the following code and it does the trick. >> >> -- Take a list and divide it at first point of non-consecutive number >> encounter >> divide :: [Int] -> [Int] -> ([Int], [Int]) >> divide first [] = (first, []) >> divide first second = if (last first) /= firstSecond - 1 then (first, >> second) >> else divide (first ++ [firstSecond]) (tail second) >> where firstSecond = head second >> >> >> -- Helper for breaking a list of numbers into consecutive sublists >> breakIntoConsecsHelper :: [Int] -> [[Int]] -> [[Int]] >> breakIntoConsecsHelper [] [[]] = [[]] >> breakIntoConsecsHelper lst ans = if two == [] then ans ++ [one] >> else ans ++ [one] ++ >> breakIntoConsecsHelper two [] >> where >> firstElem = head lst >> remaining = tail lst >> (one, two) = divide [firstElem] >> remaining >> >> >> -- Break the list into sublists of consective numbers >> breakIntoConsecs :: [Int] -> [[Int]] >> breakIntoConsecs lst = breakIntoConsecsHelper lst [[]] >> >> -- Take the tail of the result given by the function above to get the >> required list of lists. >> >> However, I was wondering if there was a better way of doing this. Any >> help would be highly appreciated. >> >> Thank you. >> Best Regards, >> Saqib Shamsi >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > > > -- > Beauty of style and harmony and grace and good rhythm depend on > simplicity. - Plato > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Carlo Matteo Scalzo Mobile: +44 (0) 7934 583582 E-mail: cmscalzo at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From math.simplex at gmail.com Fri Jan 13 23:43:19 2017 From: math.simplex at gmail.com (Graham Gill) Date: Fri, 13 Jan 2017 18:43:19 -0500 Subject: [Haskell-beginners] Better Code In-Reply-To: References: Message-ID: <6ba448e9-d180-6ca7-6e04-f1ee3ebf46bd@gmail.com> Here's one that does what you want, doesn't require the list to be sorted, and groups together consecutive and equal terms: groupConsecutive :: (Enum a,Eq a) => [a] -> [[a]] groupConsecutive = foldr go [] where go x ls@(hd@(y:_):yss) | x == y || x == pred y = (x:hd):yss | otherwise = [x]:ls go x [] = [[x]] go x ([]:yss) = [x]:yss Then > groupConsecutive [1,2,3,7,8,10,11,12] [[1,2,3],[7,8],[10,11,12]] > groupConsecutive [1,2,2,3,2,3] [[1,2,2,3],[2,3]] and > groupConsecutive "bookkeeper understudy" ["b","oo","kk","ee","p","e","r"," ","u","n","de","rstu","d","y"] The third case of go will never be reached. If you use a type that is also an instance of Bounded, and if your list contains the minimum element of the type, you'll get a runtime error on the use of pred. For example: > groupConsecutive [True,False,True] *** Exception: Prelude.Enum.Bool.pred: bad argument Graham On 13-Jan-2017 11:05 AM, Saqib Shamsi wrote: > Hi, > > The problem that I wish to solve is to divide a (sored) list of > integers into sublists such that each sublist contains numbers in > consecutive sequence. > > For example, > *Input:* [1,2,3,7,8,10,11,12] > *Output:* [[1,2,3],[7,8],[10,11,12]] > > I have written the following code and it does the trick. > > -- Take a list and divide it at first point of non-consecutive number > encounter > divide :: [Int] -> [Int] -> ([Int], [Int]) > divide first [] = (first, []) > divide first second = if (last first) /= firstSecond - 1 then (first, > second) > else divide (first ++ [firstSecond]) (tail second) > where firstSecond = head second > > > -- Helper for breaking a list of numbers into consecutive sublists > breakIntoConsecsHelper :: [Int] -> [[Int]] -> [[Int]] > breakIntoConsecsHelper [] [[]] = [[]] > breakIntoConsecsHelper lst ans = if two == [] then ans ++ [one] > else ans ++ [one] ++ > breakIntoConsecsHelper two [] > where > firstElem = head lst > remaining = tail lst > (one, two) = divide [firstElem] > remaining > > > -- Break the list into sublists of consective numbers > breakIntoConsecs :: [Int] -> [[Int]] > breakIntoConsecs lst = breakIntoConsecsHelper lst [[]] > > -- Take the tail of the result given by the function above to get the > required list of lists. > > However, I was wondering if there was a better way of doing this. Any > help would be highly appreciated. > > Thank you. > Best Regards, > Saqib Shamsi > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From math.simplex at gmail.com Sat Jan 14 00:09:49 2017 From: math.simplex at gmail.com (Graham Gill) Date: Fri, 13 Jan 2017 19:09:49 -0500 Subject: [Haskell-beginners] Better Code In-Reply-To: <6ba448e9-d180-6ca7-6e04-f1ee3ebf46bd@gmail.com> References: <6ba448e9-d180-6ca7-6e04-f1ee3ebf46bd@gmail.com> Message-ID: Sorry, I mean, "groups together consecutive and equal terms, that occur sequentially". Examples speak louder than general descriptions! On 13-Jan-2017 6:43 PM, Graham Gill wrote: > Here's one that does what you want, doesn't require the list to be > sorted, and groups together consecutive and equal terms: From jeffbrown.the at gmail.com Sat Jan 14 01:14:54 2017 From: jeffbrown.the at gmail.com (Jeffrey Brown) Date: Fri, 13 Jan 2017 17:14:54 -0800 Subject: [Haskell-beginners] Better Code In-Reply-To: References: <6ba448e9-d180-6ca7-6e04-f1ee3ebf46bd@gmail.com> Message-ID: You could zip the original list to its own tail. On Fri, Jan 13, 2017 at 4:09 PM, Graham Gill wrote: > Sorry, I mean, "groups together consecutive and equal terms, that occur > sequentially". Examples speak louder than general descriptions! > > On 13-Jan-2017 6:43 PM, Graham Gill wrote: > >> Here's one that does what you want, doesn't require the list to be >> sorted, and groups together consecutive and equal terms: >> > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -- Jeff Brown | Jeffrey Benjamin Brown Website | Facebook | LinkedIn (spammy, so I often miss messages here) | Github -------------- next part -------------- An HTML attachment was scrubbed... URL: From math.simplex at gmail.com Sat Jan 14 07:35:17 2017 From: math.simplex at gmail.com (Graham Gill) Date: Sat, 14 Jan 2017 02:35:17 -0500 Subject: [Haskell-beginners] safe versions of pred and succ? Message-ID: Suppose I have a function f :: (Enum a) => a -> ... f x ... = ...pred x ... If a is also an instance of Bounded, then I get a runtime error if pred minBound is evaluated during evaluation of f. If I try to protect the use of pred x with a check using minBound, then I have to add a Bounded constraint on type a, which would mean, for example, that I can no longer use f with type Integer. Do I need two different versions of f, one for Bounded a and one for non-Bounded a? Is there a more elegant way to take care of this problem? I don't know much about all of the type magic available in GHC. For example, from another list message, groupConsecutive :: (Enum a,Eq a) => [a] -> [[a]] groupConsecutive = foldr go [] where go x ls@(hd@(y:_):yss) | x == y || x == pred y = (x:hd):yss | otherwise = [x]:ls go x [] = [[x]] > groupConsecutive [1,2,3,7,8,10,11,12] [[1,2,3],[7,8],[10,11,12]] > groupConsecutive ([1,0,1,2]::[Word]) *** Exception: Enum.pred{Word}: tried to take `pred' of minBound In the first go case, if type a is also Bounded, y == minBound and x /= y, then we know already that x /= pred y, we want the guard to fail and that we pass to the otherwise guard to start a new sublist. But how to implement it without making the function unavailable for un-Bounded types? Graham From michael at orlitzky.com Sun Jan 15 19:05:26 2017 From: michael at orlitzky.com (Michael Orlitzky) Date: Sun, 15 Jan 2017 14:05:26 -0500 Subject: [Haskell-beginners] safe versions of pred and succ? In-Reply-To: References: Message-ID: On 01/14/2017 02:35 AM, Graham Gill wrote: > > Do I need two different versions of f, one for Bounded a and one for > non-Bounded a? Is there a more elegant way to take care of this problem? > I don't know much about all of the type magic available in GHC. > You probably want your own typeclass instead of Enum, even if it means generating a bunch of very boring instances of it for the types you want "f" to work on. The fact that "pred" should throw a runtime error on "minBound" is a documented fact of the Enum typeclass, and you should stay far far away from such things in your own code. Besides that, there's a weird interaction between the semantic meaning of Enum and Bounded. For example, here's a perfectly valid enumeration of boolean values: True, False, True, False, ... In your case it would be fine to have (pred False) == True, but instead you get a runtime error thanks to the Bounded instance. So being Bounded rules out some otherwise valid (and fine for your purposes) Enum instances. Your "f" should also work on a singleton type: ghci> data Foo = Foo deriving (Eq,Show) ghci> instance Enum Foo where toEnum _ = Foo; fromEnum _ = 0; ghci> groupConsecutive [Foo,Foo,Foo,Foo] [[Foo,Foo,Foo,Foo]] But any Bounded instance for Foo would mess that up. Basically, the pre-existing Enum instances aren't exactly what you want. From shamsi.saqib at gmail.com Mon Jan 16 05:46:27 2017 From: shamsi.saqib at gmail.com (Saqib Shamsi) Date: Mon, 16 Jan 2017 11:16:27 +0530 Subject: [Haskell-beginners] Beginners Digest, Vol 103, Issue 8 In-Reply-To: References: Message-ID: Hello Francesco, Sorry for the late reply. Yes, your solution is elegant and does what I wanted. This is what I did -- zipped is the list of tuples formed as you mentioned λ> groupBy (\x y -> (snd x) == (snd y)) zipped [[(1,0),(2,0),(3,0)],[(7,3),(8,3)],[(10,4),(11,4),(12,4)]] λ> [[fst tpl | tpl <- x] | x <- it] [[1,2,3],[7,8],[10,11,12]] This works perfectly fine. Thank you. Regards, Saqib Shamsi On 14 January 2017 at 00:27, wrote: > Send Beginners mailing list submissions to > beginners at haskell.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > or, via email, send a message with subject or body 'help' to > beginners-request at haskell.org > > You can reach the person managing the list at > beginners-owner at haskell.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Beginners digest..." > > > Today's Topics: > > 1. Better Code (Saqib Shamsi) > 2. Re: Better Code (Francesco Ariis) > 3. Re: Better Code (Joel Neely) > 4. Re: Better Code (Joel Neely) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 13 Jan 2017 21:35:54 +0530 > From: Saqib Shamsi > To: beginners at haskell.org > Subject: [Haskell-beginners] Better Code > Message-ID: > gmail.com> > Content-Type: text/plain; charset="utf-8" > > Hi, > > The problem that I wish to solve is to divide a (sored) list of integers > into sublists such that each sublist contains numbers in consecutive > sequence. > > For example, > *Input:* [1,2,3,7,8,10,11,12] > *Output:* [[1,2,3],[7,8],[10,11,12]] > > I have written the following code and it does the trick. > > -- Take a list and divide it at first point of non-consecutive number > encounter > divide :: [Int] -> [Int] -> ([Int], [Int]) > divide first [] = (first, []) > divide first second = if (last first) /= firstSecond - 1 then (first, > second) > else divide (first ++ [firstSecond]) (tail second) > where firstSecond = head second > > > -- Helper for breaking a list of numbers into consecutive sublists > breakIntoConsecsHelper :: [Int] -> [[Int]] -> [[Int]] > breakIntoConsecsHelper [] [[]] = [[]] > breakIntoConsecsHelper lst ans = if two == [] then ans ++ [one] > else ans ++ [one] ++ > breakIntoConsecsHelper two [] > where > firstElem = head lst > remaining = tail lst > (one, two) = divide [firstElem] > remaining > > > -- Break the list into sublists of consective numbers > breakIntoConsecs :: [Int] -> [[Int]] > breakIntoConsecs lst = breakIntoConsecsHelper lst [[]] > > -- Take the tail of the result given by the function above to get the > required list of lists. > > However, I was wondering if there was a better way of doing this. Any help > would be highly appreciated. > > Thank you. > Best Regards, > Saqib Shamsi > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: attachments/20170113/3f37c4a5/attachment-0001.html> > > ------------------------------ > > Message: 2 > Date: Fri, 13 Jan 2017 17:55:16 +0100 > From: Francesco Ariis > To: beginners at haskell.org > Subject: Re: [Haskell-beginners] Better Code > Message-ID: <20170113165516.GB23022 at casa.casa> > Content-Type: text/plain; charset=utf-8 > > On Fri, Jan 13, 2017 at 09:35:54PM +0530, Saqib Shamsi wrote: > > The problem that I wish to solve is to divide a (sored) list of integers > > into sublists such that each sublist contains numbers in consecutive > > sequence. > > > > For example, > > *Input:* [1,2,3,7,8,10,11,12] > > *Output:* [[1,2,3],[7,8],[10,11,12]] > > > > [...] > > > > However, I was wondering if there was a better way of doing this. Any > help > > would be highly appreciated. > > Hello Saquib, > you could try using a 'trick' like this: > > λ> zipWith (-) [1,2,3,7,8,10,11,12] (enumFrom 1) > [0,0,0,3,3,4,4,4] > > Now you have an 'helper' list which can be glued to the first one > with zip > > λ> zip [1,2,3,7,8,10,11,12] it > [(1,0),(2,0),(3,0),(7,3),(8,3),(10,4),(11,4),(12,4)] > > and now grouped by using `groupBy` in Data.List. > > Does that help? > > > ------------------------------ > > Message: 3 > Date: Fri, 13 Jan 2017 11:40:57 -0600 > From: Joel Neely > To: The Haskell-Beginners Mailing List - Discussion of primarily > beginner-level topics related to Haskell > Subject: Re: [Haskell-beginners] Better Code > Message-ID: > gmail.com> > Content-Type: text/plain; charset="utf-8" > > The "helper list" technique is ingenious, but seems very specific to Int as > the type within the list. > > I have had other tasks that seem to fit a more generalized problem > statement, of which the original question appears to me as special case: > > Given a criterion of type a -> a -> Bool and a list [a], produce a list of > lists [[a]] in which sub-lists are made up of consecutive elements from the > original list that satisfy the criterion. > > It appears to me that List.groupBy may meet that need, but I'm not able to > verify that at the moment (and would be glad of feedback). > > -jn- > > > > > > On Fri, Jan 13, 2017 at 10:55 AM, Francesco Ariis wrote: > > > On Fri, Jan 13, 2017 at 09:35:54PM +0530, Saqib Shamsi wrote: > > > The problem that I wish to solve is to divide a (sored) list of > integers > > > into sublists such that each sublist contains numbers in consecutive > > > sequence. > > > > > > For example, > > > *Input:* [1,2,3,7,8,10,11,12] > > > *Output:* [[1,2,3],[7,8],[10,11,12]] > > > > > > [...] > > > > > > However, I was wondering if there was a better way of doing this. Any > > help > > > would be highly appreciated. > > > > Hello Saquib, > > you could try using a 'trick' like this: > > > > λ> zipWith (-) [1,2,3,7,8,10,11,12] (enumFrom 1) > > [0,0,0,3,3,4,4,4] > > > > Now you have an 'helper' list which can be glued to the first one > > with zip > > > > λ> zip [1,2,3,7,8,10,11,12] it > > [(1,0),(2,0),(3,0),(7,3),(8,3),(10,4),(11,4),(12,4)] > > > > and now grouped by using `groupBy` in Data.List. > > > > Does that help? > > _______________________________________________ > > Beginners mailing list > > Beginners at haskell.org > > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > > > -- > Beauty of style and harmony and grace and good rhythm depend on simplicity. > - Plato > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: attachments/20170113/35931560/attachment-0001.html> > > ------------------------------ > > Message: 4 > Date: Fri, 13 Jan 2017 13:14:56 -0600 > From: Joel Neely > To: The Haskell-Beginners Mailing List - Discussion of primarily > beginner-level topics related to Haskell > Subject: Re: [Haskell-beginners] Better Code > Message-ID: > fhE_Q at mail.gmail.com> > Content-Type: text/plain; charset="utf-8" > > Had a chance to chat with ghci, so earlier conjecture not confirmed: > > Prelude Data.List> groupBy (\x y -> x == y-1) [1,2,3,7,8,10,11,12] > > [[1,2],[3],[7,8],[10,11],[12]] > > So close but no cigar. > > On Fri, Jan 13, 2017 at 10:05 AM, Saqib Shamsi > wrote: > > > Hi, > > > > The problem that I wish to solve is to divide a (sored) list of integers > > into sublists such that each sublist contains numbers in consecutive > > sequence. > > > > For example, > > *Input:* [1,2,3,7,8,10,11,12] > > *Output:* [[1,2,3],[7,8],[10,11,12]] > > > > I have written the following code and it does the trick. > > > > -- Take a list and divide it at first point of non-consecutive number > > encounter > > divide :: [Int] -> [Int] -> ([Int], [Int]) > > divide first [] = (first, []) > > divide first second = if (last first) /= firstSecond - 1 then (first, > > second) > > else divide (first ++ [firstSecond]) (tail second) > > where firstSecond = head second > > > > > > -- Helper for breaking a list of numbers into consecutive sublists > > breakIntoConsecsHelper :: [Int] -> [[Int]] -> [[Int]] > > breakIntoConsecsHelper [] [[]] = [[]] > > breakIntoConsecsHelper lst ans = if two == [] then ans ++ [one] > > else ans ++ [one] ++ > > breakIntoConsecsHelper two [] > > where > > firstElem = head lst > > remaining = tail lst > > (one, two) = divide [firstElem] > > remaining > > > > > > -- Break the list into sublists of consective numbers > > breakIntoConsecs :: [Int] -> [[Int]] > > breakIntoConsecs lst = breakIntoConsecsHelper lst [[]] > > > > -- Take the tail of the result given by the function above to get the > > required list of lists. > > > > However, I was wondering if there was a better way of doing this. Any > help > > would be highly appreciated. > > > > Thank you. > > Best Regards, > > Saqib Shamsi > > > > _______________________________________________ > > Beginners mailing list > > Beginners at haskell.org > > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > > > > -- > Beauty of style and harmony and grace and good rhythm depend on simplicity. > - Plato > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: attachments/20170113/df78caf6/attachment.html> > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > ------------------------------ > > End of Beginners Digest, Vol 103, Issue 8 > ***************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From magnus at therning.org Mon Jan 16 06:31:14 2017 From: magnus at therning.org (Magnus Therning) Date: Mon, 16 Jan 2017 07:31:14 +0100 Subject: [Haskell-beginners] Feedback needed - CLI app + guide In-Reply-To: References: Message-ID: <87tw8zwm6l.fsf@therning.org> Carlo Matteo Scalzo writes: > Hi all, > > I'm new to the community here, so please do let me know if I'm doing > something wrong :-) > > I've been learning Haskell over the last year or so, reading books etc., > but I couldn't find a simple, real world example, so I decided to to write > a simple command-line application in Haskell. > > The application and the code are free, and I've also written a short guide > that uses the application as a use case to talk about Haskell and its > features. > > Can you guys please download the guide (for free, of course) , and let me > know if you found it useful? > > You can find it here: > > https://fifohaskell.com > > Please let me have your feedback (my personal email is on the website, if > you don't want to reply here) - and thank you very much for your help! Just had a quick look and things that I notice are: 1. Keep your source in a VCS like gitlab/github/etc? 2. It would be nice of you to put a copyright notice in the source so users know what they may do with the source. 3. Please do create a proper package for it so you can publish it to Hackage. /M -- Magnus Therning OpenPGP: 0x927912051716CE39 email: magnus at therning.org jabber: magnus at therning.org twitter: magthe http://therning.org/magnus As someone who's worked at multiple proprietary software companies, having a roadmap doesn't magically make code happen. — Josh Berkus (found in LWN 2016-04-16) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 832 bytes Desc: not available URL: From math.simplex at gmail.com Mon Jan 16 15:59:38 2017 From: math.simplex at gmail.com (Graham Gill) Date: Mon, 16 Jan 2017 10:59:38 -0500 Subject: [Haskell-beginners] safe versions of pred and succ? In-Reply-To: References: Message-ID: Thanks very much for that clear reply Michael. I don't have an application in mind specifically, the example function groupConsecutive just came up in another message and set me wondering: if I have a function to work on types of class A, but types that are instances of both class A and class B are problematic, is there a way to distinguish the cases? As you say, it's probably not class A that I want my function to work over, but instead my own type class. Graham On 15 Jan 2017 14:09, "Michael Orlitzky" > wrote: On 01/14/2017 02:35 AM, Graham Gill wrote: > > Do I need two different versions of f, one for Bounded a and one for > non-Bounded a? Is there a more elegant way to take care of this problem? > I don't know much about all of the type magic available in GHC. > You probably want your own typeclass instead of Enum, even if it means generating a bunch of very boring instances of it for the types you want "f" to work on. The fact that "pred" should throw a runtime error on "minBound" is a documented fact of the Enum typeclass, and you should stay far far away from such things in your own code. Besides that, there's a weird interaction between the semantic meaning of Enum and Bounded. For example, here's a perfectly valid enumeration of boolean values: True, False, True, False, ... In your case it would be fine to have (pred False) == True, but instead you get a runtime error thanks to the Bounded instance. So being Bounded rules out some otherwise valid (and fine for your purposes) Enum instances. Your "f" should also work on a singleton type: ghci> data Foo = Foo deriving (Eq,Show) ghci> instance Enum Foo where toEnum _ = Foo; fromEnum _ = 0; ghci> groupConsecutive [Foo,Foo,Foo,Foo] [[Foo,Foo,Foo,Foo]] But any Bounded instance for Foo would mess that up. Basically, the pre-existing Enum instances aren't exactly what you want. _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmscalzo at gmail.com Mon Jan 16 18:00:23 2017 From: cmscalzo at gmail.com (Carlo Matteo Scalzo) Date: Mon, 16 Jan 2017 18:00:23 +0000 Subject: [Haskell-beginners] Feedback needed - CLI app + guide In-Reply-To: <87tw8zwm6l.fsf@therning.org> References: <87tw8zwm6l.fsf@therning.org> Message-ID: Hi Magnus, thank you very much for your feedback! I'm trying to keep things simple for now, but I'll think about your suggestions (and thank you for pointing those out). Did you have the chance to look at guide? I'd love to get your feedback on the content, if you have time. Thanks again! Carlo On 16 Jan 2017 06:32, "Magnus Therning" wrote: Carlo Matteo Scalzo writes: > Hi all, > > I'm new to the community here, so please do let me know if I'm doing > something wrong :-) > > I've been learning Haskell over the last year or so, reading books etc., > but I couldn't find a simple, real world example, so I decided to to write > a simple command-line application in Haskell. > > The application and the code are free, and I've also written a short guide > that uses the application as a use case to talk about Haskell and its > features. > > Can you guys please download the guide (for free, of course) , and let me > know if you found it useful? > > You can find it here: > > https://fifohaskell.com > > Please let me have your feedback (my personal email is on the website, if > you don't want to reply here) - and thank you very much for your help! Just had a quick look and things that I notice are: 1. Keep your source in a VCS like gitlab/github/etc? 2. It would be nice of you to put a copyright notice in the source so users know what they may do with the source. 3. Please do create a proper package for it so you can publish it to Hackage. /M -- Magnus Therning OpenPGP: 0x927912051716CE39 email: magnus at therning.org jabber: magnus at therning.org twitter: magthe http://therning.org/magnus As someone who's worked at multiple proprietary software companies, having a roadmap doesn't magically make code happen. — Josh Berkus (found in LWN 2016-04-16) _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From frederic-emmanuel.picca at synchrotron-soleil.fr Tue Jan 17 10:15:24 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Tue, 17 Jan 2017 10:15:24 +0000 Subject: [Haskell-beginners] =?utf-8?q?=28no_subject=29?= Message-ID: Hello, Here a reduction of my problem values :: IO [IO (Maybe Int)] values = do let v = [Just 1, Just 2, Just 3, Nothing, Just 5, Nothing, Just 7] :: [Maybe Int] return $ map return v main :: IO () main = do vs <- values nvs <- mapM_ go vs print nvs where go :: IO (Maybe Int) -> IO Int go v' = do Just v <- v' return v when I run this script, I get a runtime error picca at diffabs6:~/tmp$ runhaskell test.hs test.hs: user error (Pattern match failure in do expression at test.hs:13:10-15) What I want is a go method which skip silently the (IO Nothing) values. so when used in the mapM_ it return only the values which are returned by the IO (Maybe Int) (stored in the values) Thanks for your help Frédéric Indeed From frederic-emmanuel.picca at synchrotron-soleil.fr Tue Jan 17 14:03:02 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Tue, 17 Jan 2017 14:03:02 +0000 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ Message-ID: Sorry I forgot to put a subject ________________________________________ De : Beginners [beginners-bounces at haskell.org] de la part de PICCA Frederic-Emmanuel Envoyé : mardi 17 janvier 2017 11:15 À : The Haskell-Beginners Mailing List - Discussion of primarily beginner-level topics related to Haskell Objet : [Haskell-beginners] (no subject) Hello, Here a reduction of my problem values :: IO [IO (Maybe Int)] values = do let v = [Just 1, Just 2, Just 3, Nothing, Just 5, Nothing, Just 7] :: [Maybe Int] return $ map return v main :: IO () main = do vs <- values nvs <- mapM_ go vs print nvs where go :: IO (Maybe Int) -> IO Int go v' = do Just v <- v' return v when I run this script, I get a runtime error picca at diffabs6:~/tmp$ runhaskell test.hs test.hs: user error (Pattern match failure in do expression at test.hs:13:10-15) What I want is a go method which skip silently the (IO Nothing) values. so when used in the mapM_ it return only the values which are returned by the IO (Maybe Int) (stored in the values) Thanks for your help Frédéric Indeed _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From fa-ml at ariis.it Tue Jan 17 14:19:46 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Tue, 17 Jan 2017 15:19:46 +0100 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: References: Message-ID: <20170117141946.GA6864@casa.casa> On Tue, Jan 17, 2017 at 02:03:02PM +0000, PICCA Frederic-Emmanuel wrote: > Hello, > > Here a reduction of my problem > > values :: IO [IO (Maybe Int)] > values = do > let v = [Just 1, Just 2, Just 3, Nothing, Just 5, Nothing, Just 7] :: [Maybe Int] > return $ map return v > > main :: IO () > main = do > vs <- values > nvs <- mapM_ go vs > print nvs > where > go :: IO (Maybe Int) -> IO Int > go v' = do > Just v <- v' > return v Hello Frédéric, `Just v <- v'` doesn't silently skip Nothing values, but it's a full fledged pattern match (and one reason why I dislike `do notation` as a syntactic sugar). A way to solve the problem is to take advantage of `sequence` and `catMaybes` (from `Data.Maybe`). λ> :t sequence sequence :: (Monad m) => [m a] -> m [a] -- I cheated a bit on the signature, but the gist -- of it is: from a list of monadic actions, to -- one monadic action returning a list of results. λ> :t catMaybes catMaybes :: [Maybe a] -> [a] With that your main gets simpler: main :: IO () main = do vs <- values -- vs :: [IO (Maybe Int)] sv <- sequence vs -- sequence vs :: IO [Maybe Int] -- sv :: [Maybe Int] print (M.catMaybes sv) Does this help? From frederic-emmanuel.picca at synchrotron-soleil.fr Tue Jan 17 14:49:11 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Tue, 17 Jan 2017 14:49:11 +0000 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: <20170117141946.GA6864@casa.casa> References: , <20170117141946.GA6864@casa.casa> Message-ID: Hello In fact I realize that my real problem is during the 'values' generation of my example. I have a class like this class Frame t where len :: t -> IO (Maybe Int) row :: t -> Int -> IO (Maybe (DifTomoFrame DIM1)) And I create an instance for my dataframe comming from an hdf5 file. some time there is Nan values returned by the get_position method. I decided to return a Maybe Double and Nan -> Nothing instance Frame DataFrameH5 where len d = lenH5Dataspace (h5delta d) row d idx = do Just n <- len d let eof = n - 1 == idx let nxs' = h5nxs d let mu = 0.0 let komega = 0.0 let kappa = 0.0 let kphi = 0.0 Just gamma <- get_position' (h5gamma d) 0 Just delta <- get_position' (h5delta d) idx Just wavelength <- get_position' (h5wavelength d) 0 let source = Source (head wavelength *~ nano meter) let positions = concat [mu, komega, kappa, kphi, gamma, delta] -- print positions let geometry = Geometry K6c source positions Nothing let detector = ZeroD m <- geometryDetectorRotationGet geometry detector poniext <- ponigen d (MyMatrix HklB m) idx return $ Just DifTomoFrame { difTomoFrameNxs = nxs' , difTomoFrameIdx = idx , difTomoFrameEOF = eof , difTomoFrameGeometry = geometry , difTomoFramePoniExt = poniext } where get_position' a b = do v <- get_position a b return $ if any isNaN v then Nothing else Just v I iterate for each idx of my dataframe So I would like row to return Nothing as soon as the get_position' return Nothing but when I use this code, I get the error and it stop my program instead of skipping the point. ________________________________________ De : Beginners [beginners-bounces at haskell.org] de la part de Francesco Ariis [fa-ml at ariis.it] Envoyé : mardi 17 janvier 2017 15:19 À : The Haskell-Beginners Mailing List - Discussion of primarily beginner-level topics related to Haskell Objet : Re: [Haskell-beginners] how to skip pattern match error when applying a mapM_ On Tue, Jan 17, 2017 at 02:03:02PM +0000, PICCA Frederic-Emmanuel wrote: > Hello, > > Here a reduction of my problem > > values :: IO [IO (Maybe Int)] > values = do > let v = [Just 1, Just 2, Just 3, Nothing, Just 5, Nothing, Just 7] :: [Maybe Int] > return $ map return v > > main :: IO () > main = do > vs <- values > nvs <- mapM_ go vs > print nvs > where > go :: IO (Maybe Int) -> IO Int > go v' = do > Just v <- v' > return v Hello Frédéric, `Just v <- v'` doesn't silently skip Nothing values, but it's a full fledged pattern match (and one reason why I dislike `do notation` as a syntactic sugar). A way to solve the problem is to take advantage of `sequence` and `catMaybes` (from `Data.Maybe`). λ> :t sequence sequence :: (Monad m) => [m a] -> m [a] -- I cheated a bit on the signature, but the gist -- of it is: from a list of monadic actions, to -- one monadic action returning a list of results. λ> :t catMaybes catMaybes :: [Maybe a] -> [a] With that your main gets simpler: main :: IO () main = do vs <- values -- vs :: [IO (Maybe Int)] sv <- sequence vs -- sequence vs :: IO [Maybe Int] -- sv :: [Maybe Int] print (M.catMaybes sv) Does this help? _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From fa-ml at ariis.it Tue Jan 17 15:26:03 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Tue, 17 Jan 2017 16:26:03 +0100 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: References: <20170117141946.GA6864@casa.casa> Message-ID: <20170117152603.GA8760@casa.casa> On Tue, Jan 17, 2017 at 02:49:11PM +0000, PICCA Frederic-Emmanuel wrote: > Hello > > In fact I realize that my real problem is during the 'values' generation of my example. > > I have a class like this > > [...] A repository would help! In any case writing: Just gamma <- get_position' (h5gamma d) 0 Just delta <- get_position' (h5delta d) idx Just wavelength <- get_position' (h5wavelength d) 0 is asking for a trouble down the road. Use a case to pattern match on nothing, (or `maybe`, or LambdaCase if you are into extensions). From frederic-emmanuel.picca at synchrotron-soleil.fr Tue Jan 17 17:34:05 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Tue, 17 Jan 2017 17:34:05 +0000 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: <20170117152603.GA8760@casa.casa> References: <20170117141946.GA6864@casa.casa> , <20170117152603.GA8760@casa.casa> Message-ID: > Just gamma <- get_position' (h5gamma d) 0 > Just delta <- get_position' (h5delta d) idx > Just wavelength <- get_position' (h5wavelength d) 0 > is asking for a trouble down the road. Use a case to pattern match > on nothing, (or `maybe`, or LambdaCase if you are into extensions). I tought that was the purpose of the Monad to avoid writting these boillerplate ? What I am missing ? Cheers Frederic From daniel.trstenjak at gmail.com Tue Jan 17 18:06:11 2017 From: daniel.trstenjak at gmail.com (Daniel Trstenjak) Date: Tue, 17 Jan 2017 19:06:11 +0100 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: References: <20170117141946.GA6864@casa.casa> <20170117152603.GA8760@casa.casa> Message-ID: <20170117180611.GA16815@octa> Hi Frederic, On Tue, Jan 17, 2017 at 05:34:05PM +0000, PICCA Frederic-Emmanuel wrote: > I tought that was the purpose of the Monad to avoid writting these boillerplate ? > > What I am missing ? You don't pattern match on 'Just' but just write: gamma <- get_position' (h5gamma d) 0 delta <- get_position' (h5delta d) idx wavelength <- get_position' (h5wavelength d) 0 If e.g. 'gamma' is 'Nothing', then the following expressions aren't evaluated and the whole "do-block" returns 'Nothing'. Greetings, Daniel From verdier.jean at gmail.com Tue Jan 17 18:17:10 2017 From: verdier.jean at gmail.com (jean verdier) Date: Tue, 17 Jan 2017 19:17:10 +0100 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: References: <20170117141946.GA6864@casa.casa> , <20170117152603.GA8760@casa.casa> Message-ID: <1484677030.3065.8.camel@gmail.com> Just x <- y  is a construction similar to  let Just x = y which is the same as x = case y of       Just z -> z       Nothing -> error "pattern match failed" Some matches are mapped to errors but not explicitly. Just x = y  avoid some boilerplate at the cost of hiding the non exhaustive matches that may raise unexpected errors. Just x <- y is the same as  z <- y let x = case z of ... On Tue, 2017-01-17 at 17:34 +0000, PICCA Frederic-Emmanuel wrote: > > > >     Just gamma <- get_position' (h5gamma d) 0 > >     Just delta <- get_position' (h5delta d) idx > >     Just wavelength <- get_position' (h5wavelength d) 0 > > > > > is asking for a trouble down the road. Use a case to pattern match > > on nothing, (or `maybe`, or LambdaCase if you are into extensions). > > I tought that was the purpose of the Monad to avoid writting these > boillerplate ? > > What I am missing ? > > Cheers > > Frederic > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From daniel.trstenjak at gmail.com Tue Jan 17 18:21:38 2017 From: daniel.trstenjak at gmail.com (Daniel Trstenjak) Date: Tue, 17 Jan 2017 19:21:38 +0100 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: <20170117180611.GA16815@octa> References: <20170117141946.GA6864@casa.casa> <20170117152603.GA8760@casa.casa> <20170117180611.GA16815@octa> Message-ID: <20170117182138.GB16815@octa> > If e.g. 'gamma' is 'Nothing', then the following expressions aren't evaluated > and the whole "do-block" returns 'Nothing'. I just saw that 'row' isn't operating in the 'Maybe' monad but in the 'IO' monad, so this wont work. I don't know if 'row' contains any side effects that should also be executed if the returned 'Maybe' is 'Nothing', if this isn't the case, then you might be able to switch the return type of 'row' from 'IO (Maybe ...)' to 'Maybe (IO ...)' and then you could get the described behaviour for 'Maybe'. Greetings, Daniel From frederic-emmanuel.picca at synchrotron-soleil.fr Tue Jan 17 19:44:31 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Tue, 17 Jan 2017 19:44:31 +0000 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: <20170117182138.GB16815@octa> References: <20170117141946.GA6864@casa.casa> <20170117152603.GA8760@casa.casa> <20170117180611.GA16815@octa>,<20170117182138.GB16815@octa> Message-ID: > I don't know if 'row' contains any side effects that should also be > executed if the returned 'Maybe' is 'Nothing', if this isn't the case, > then you might be able to switch the return type of 'row' from > 'IO (Maybe ...)' to 'Maybe (IO ...)' and then you could get the > described behaviour for 'Maybe'. As soon as one side effect return Nothing, it should stop the IO monad. so I should definitiely switch to Maybe IO now how can I know the behaviour in between the line of a Monad. I aimagine that this is the purpose of the bind method (>>=). Where is this defined for Maybe and IO ? Thanks Frederic From daniel.trstenjak at gmail.com Tue Jan 17 20:36:37 2017 From: daniel.trstenjak at gmail.com (Daniel Trstenjak) Date: Tue, 17 Jan 2017 21:36:37 +0100 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: References: <20170117141946.GA6864@casa.casa> <20170117152603.GA8760@casa.casa> <20170117180611.GA16815@octa> <20170117182138.GB16815@octa> Message-ID: <53A63195-75D3-4B94-87DD-3C7EF094AEE7@gmail.com> > now how can I know the behaviour in between the line of a Monad. > I aimagine that this is the purpose of the bind method (>>=). Yes, that's the case. > Where is this defined for Maybe and IO ? You just look at the Monad instance for the type. IO is a bit special, but here is the one for Maybe[1]. Greetings, Daniel [1] http://hackage.haskell.org/package/base-4.9.1.0/docs/src/GHC.Base.html#line-665 -------------- next part -------------- An HTML attachment was scrubbed... URL: From frederic-emmanuel.picca at synchrotron-soleil.fr Tue Jan 17 20:46:32 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Tue, 17 Jan 2017 20:46:32 +0000 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: <53A63195-75D3-4B94-87DD-3C7EF094AEE7@gmail.com> References: <20170117141946.GA6864@casa.casa> <20170117152603.GA8760@casa.casa> <20170117180611.GA16815@octa> <20170117182138.GB16815@octa> , <53A63195-75D3-4B94-87DD-3C7EF094AEE7@gmail.com> Message-ID: > You just look at the Monad instance for the type. IO is a bit special, but > here is the one for Maybe[1]. thanks and what is the purpose of fail _ = nothing Cheers Fred From daniel.trstenjak at gmail.com Tue Jan 17 21:28:47 2017 From: daniel.trstenjak at gmail.com (Daniel Trstenjak) Date: Tue, 17 Jan 2017 22:28:47 +0100 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: References: <20170117141946.GA6864@casa.casa> <20170117152603.GA8760@casa.casa> <20170117180611.GA16815@octa> <20170117182138.GB16815@octa> <53A63195-75D3-4B94-87DD-3C7EF094AEE7@gmail.com> Message-ID: > thanks and what is the purpose of > > fail _ = nothing ’fail’ is called for pattern match errors, pretty much the error you’ve got from ’Just x <- ...’. The IO Monad instance raises the exception you've seen. For the Maybe Monad instance just 'Nothing' is returned. Greetings, Daniel From mva.led at gmail.com Tue Jan 17 23:31:55 2017 From: mva.led at gmail.com (Manuel =?utf-8?Q?V=C3=A1zquez?= Acosta) Date: Tue, 17 Jan 2017 18:31:55 -0500 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: (PICCA Frederic-Emmanuel's message of "Tue, 17 Jan 2017 20:46:32 +0000") References: <20170117141946.GA6864@casa.casa> <20170117152603.GA8760@casa.casa> <20170117180611.GA16815@octa> <20170117182138.GB16815@octa> <53A63195-75D3-4B94-87DD-3C7EF094AEE7@gmail.com> Message-ID: <87eg016z6c.fsf@pavla.com> >From [1]: -- | Fail with a message. This operation is not part of the -- mathematical definition of a monad, but is invoked on pattern-match -- failure in a @do@ expression. -- -- As part of the MonadFail proposal (MFP), this function is moved -- to its own class 'MonadFail' (see "Control.Monad.Fail" for more -- details). The definition here will be removed in a future -- release. fail :: String -> m a fail s = errorWithoutStackTrace s Best regards, Manuel (also a newbie) [1] http://hackage.haskell.org/package/base-4.9.1.0/docs/src/GHC.Base.html#Monad > thanks and what is the purpose of > > fail _ = nothing > > Cheers > > Fred > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From frederic-emmanuel.picca at synchrotron-soleil.fr Wed Jan 18 10:28:30 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Wed, 18 Jan 2017 10:28:30 +0000 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: <87eg016z6c.fsf@pavla.com> References: <20170117141946.GA6864@casa.casa> <20170117152603.GA8760@casa.casa> <20170117180611.GA16815@octa> <20170117182138.GB16815@octa> <53A63195-75D3-4B94-87DD-3C7EF094AEE7@gmail.com> , <87eg016z6c.fsf@pavla.com> Message-ID: Hello, thanks for the informations after investigating, I could not switch the IO and the Maybe I need to process the IO in order to know if I have a Just or a Nothing So this is a IO (Maybe ...) I just would like to know if there is a better way to write this knowing len :: IO (Maybe Int) get_position' :: a -> b -> IO (Maybe Double) instance Frame DataFrameH5 where len d = lenH5Dataspace (h5delta d) row d idx = do n' <- len d case n' of (Just n) -> do let eof = n - 1 == idx let nxs' = h5nxs d let mu = 0.0 let komega = 0.0 let kappa = 0.0 let kphi = 0.0 gamma' <- get_position' (h5gamma d) 0 case gamma' of (Just gamma) -> do delta' <- get_position' (h5delta d) idx case delta' of (Just delta) -> do wavelength' <- get_position' (h5wavelength d) 0 case wavelength' of (Just wavelength) -> do let source = Source (head wavelength *~ nano meter) let positions = concat [mu, komega, kappa, kphi, gamma, delta] -- print positions let geometry = Geometry K6c source positions Nothing let detector = ZeroD m <- geometryDetectorRotationGet geometry detector poniext <- ponigen d (MyMatrix HklB m) idx return $ Just DifTomoFrame { difTomoFrameNxs = nxs' , difTomoFrameIdx = idx , difTomoFrameEOF = eof , difTomoFrameGeometry = geometry , difTomoFramePoniExt = poniext } Nothing -> return Nothing Nothing -> return Nothing Nothing -> return Nothing Nothing -> return Nothing where get_position' a b = do v <- get_position a b return $ if any isNaN v then Nothing else Just v Thanks for your help Frederic From daniel.trstenjak at gmail.com Wed Jan 18 11:53:26 2017 From: daniel.trstenjak at gmail.com (Daniel Trstenjak) Date: Wed, 18 Jan 2017 12:53:26 +0100 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: References: <20170117152603.GA8760@casa.casa> <20170117180611.GA16815@octa> <20170117182138.GB16815@octa> <53A63195-75D3-4B94-87DD-3C7EF094AEE7@gmail.com> <87eg016z6c.fsf@pavla.com> Message-ID: <20170118115326.GA7930@octa> Hi Frederic, > after investigating, I could not switch the IO and the Maybe > I need to process the IO in order to know if I have a Just or a Nothing > So this is a IO (Maybe ...) > > I just would like to know if there is a better way to write this > knowing There's the MaybeT[1] monad transformer for this use case. Instead of having: row :: t -> Int -> IO (Maybe (DifTomoFrame DIM1)) you would have: row :: t -> Int -> MaybeT IO (DifTomoFrame DIM1) So 'row' might look like: row d idx = do n <- len d let eof = n - 1 == idx let nxs' = h5nxs d let mu = 0.0 let komega = 0.0 let kappa = 0.0 let kphi = 0.0 gamma <- get_position' (h5gamma d) 0 delta <- get_position' (h5delta d) idx wavelength <- get_position' (h5wavelength d) 0 let source = Source (head wavelength *~ nano meter) let positions = concat [mu, komega, kappa, kphi, gamma, delta] -- print positions let geometry = Geometry K6c source positions Nothing let detector = ZeroD m <- lift $ geometryDetectorRotationGet geometry detector poniext <- lift $ ponigen d (MyMatrix HklB m) idx return $ DifTomoFrame { difTomoFrameNxs = nxs' , difTomoFrameIdx = idx , difTomoFrameEOF = eof , difTomoFrameGeometry = geometry , difTomoFramePoniExt = poniext } This assumes that the functions 'len', 'get_position' also return a 'MaybeT IO (...)'. Functions in the IO monad - like 'geometryDetectorRotationGet' and 'ponigen' - have to be "lifted" into the IO monad by 'lift'. To get at the 'Maybe' result of 'row' you're using the 'runMaybeT' function in the IO monad: main :: IO () main = do ... result <- runMaybeT (row t int) ... Greetings, Daniel [1] https://hackage.haskell.org/package/transformers-0.5.2.0/docs/Control-Monad-Trans-Maybe.html From frederic-emmanuel.picca at synchrotron-soleil.fr Wed Jan 18 12:24:23 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Wed, 18 Jan 2017 12:24:23 +0000 Subject: [Haskell-beginners] how to skip pattern match error when applying a mapM_ In-Reply-To: <20170118115326.GA7930@octa> References: <20170117152603.GA8760@casa.casa> <20170117180611.GA16815@octa> <20170117182138.GB16815@octa> <53A63195-75D3-4B94-87DD-3C7EF094AEE7@gmail.com> <87eg016z6c.fsf@pavla.com> , <20170118115326.GA7930@octa> Message-ID: fantastic I like this a lot :)) Thanks Frederic There is plenty of nice Monad transformer like that :)) I just need to learn when to use them. Cheers Frederic From frederic-emmanuel.picca at synchrotron-soleil.fr Mon Jan 23 08:48:26 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Mon, 23 Jan 2017 08:48:26 +0000 Subject: [Haskell-beginners] What is wrong with my types signatures. Message-ID: Hello here a snipset code class Shape sh => FrameND t sh where shapeND :: t -> MaybeT IO sh rowND :: t -> sh -> MaybeT IO (XrdMeshFrame sh) I have an instance of FrameND then I created a function which use this class framesND :: (Shape sh, FrameND a sh) => Pipe a (XrdMeshFrame sh) IO () framesND = do d <- await sh' <- lift $ runMaybeT $ shapeND d let n = size sh' forM_ [0..n-1] (\i' -> do f <- lift $ runMaybeT $ rowND d (fromIndex sh' i') when (isJust f) (yield (fromJust f))) But when I compile it; I get this error message src/Hkl/XRD.hs:613:55: Could not deduce (sh ~ Maybe a0) from the context (Shape sh, FrameND a sh) bound by the type signature for framesND :: (Shape sh, FrameND a sh) => Pipe a (XrdMeshFrame sh) IO () at src/Hkl/XRD.hs:606:13-70 `sh' is a rigid type variable bound by the type signature for framesND :: (Shape sh, FrameND a sh) => Pipe a (XrdMeshFrame sh) IO () at src/Hkl/XRD.hs:606:13 Expected type: Maybe (XrdMeshFrame sh) Actual type: Maybe (XrdMeshFrame (Maybe a0)) In the first argument of `fromJust', namely `f' In the first argument of `yield', namely `(fromJust f)' In the second argument of `when', namely `(yield (fromJust f))' So I do not undestand why the typse system guess Maybe a0 instead of sh in f If I read this f <- lift $ runMaybeT $ rowND d (fromIndex sh' i') runMaybeT return a (Maybe (XrdMeshFrame sh)) and then I lift it into the Pipe. So What is wrong ? thanks Frederic From toad3k at gmail.com Mon Jan 23 13:25:14 2017 From: toad3k at gmail.com (David McBride) Date: Mon, 23 Jan 2017 08:25:14 -0500 Subject: [Haskell-beginners] What is wrong with my types signatures. In-Reply-To: References: Message-ID: Here's my guess. I can't be sure without class instances and some function types that are not in code. sh' <- lift $ runMaybeT $ shapeND d :: Pipe a (XrdMeshFrame sh) IO (Maybe sh?) ... f <- lift $ runMaybeT $ rowND d (fromIndex sh' i') -- <- sh' is (Maybe sh), guessing that fromIndex does not take a Maybe. On Mon, Jan 23, 2017 at 3:48 AM, PICCA Frederic-Emmanuel wrote: > Hello here a snipset code > > class Shape sh => FrameND t sh where > shapeND :: t -> MaybeT IO sh > rowND :: t -> sh -> MaybeT IO (XrdMeshFrame sh) > > I have an instance of FrameND > > then I created a function which use this class > > framesND :: (Shape sh, FrameND a sh) => Pipe a (XrdMeshFrame sh) IO () > framesND = do > d <- await > sh' <- lift $ runMaybeT $ shapeND d > let n = size sh' > forM_ [0..n-1] (\i' -> do > f <- lift $ runMaybeT $ rowND d (fromIndex sh' i') > when (isJust f) (yield (fromJust f))) > > But when I compile it; I get this error message > > > src/Hkl/XRD.hs:613:55: > Could not deduce (sh ~ Maybe a0) > from the context (Shape sh, FrameND a sh) > bound by the type signature for > framesND :: (Shape sh, FrameND a sh) => > Pipe a (XrdMeshFrame sh) IO () > at src/Hkl/XRD.hs:606:13-70 > `sh' is a rigid type variable bound by > the type signature for > framesND :: (Shape sh, FrameND a sh) => > Pipe a (XrdMeshFrame sh) IO () > at src/Hkl/XRD.hs:606:13 > Expected type: Maybe (XrdMeshFrame sh) > Actual type: Maybe (XrdMeshFrame (Maybe a0)) > In the first argument of `fromJust', namely `f' > In the first argument of `yield', namely `(fromJust f)' > In the second argument of `when', namely `(yield (fromJust f))' > > > So I do not undestand why the typse system guess Maybe a0 instead of sh in f > > If I read this > > f <- lift $ runMaybeT $ rowND d (fromIndex sh' i') > > runMaybeT return a (Maybe (XrdMeshFrame sh)) and then I lift it into the Pipe. > > So > > What is wrong ? > > thanks > > > Frederic > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From frederic-emmanuel.picca at synchrotron-soleil.fr Mon Jan 23 13:37:59 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Mon, 23 Jan 2017 13:37:59 +0000 Subject: [Haskell-beginners] What is wrong with my types signatures. In-Reply-To: References: , Message-ID: Thanks a lot. > Here's my guess. I can't be sure without class instances and some > function types that are not in code. > sh' <- lift $ runMaybeT $ shapeND d :: Pipe a (XrdMeshFrame sh) IO (Maybe sh?) ... > f <- lift $ runMaybeT $ rowND d (fromIndex sh' i') -- <- sh' is (Maybe > sh), guessing that fromIndex does not take a Maybe. This was the problem. Thanks. PS: The error message was right (as usual :), but I do not know why I was not able to found the cuprite. From magnus at therning.org Tue Jan 24 08:58:44 2017 From: magnus at therning.org (Magnus Therning) Date: Tue, 24 Jan 2017 09:58:44 +0100 Subject: [Haskell-beginners] (no subject) In-Reply-To: References: Message-ID: <87mvegltq3.fsf@therning.org> PICCA Frederic-Emmanuel writes: > Hello, > > Here a reduction of my problem > > values :: IO [IO (Maybe Int)] > values = do > let v = [Just 1, Just 2, Just 3, Nothing, Just 5, Nothing, Just 7] :: [Maybe Int] I would let the compiler deal with the type, i.e. skip the ` :: [Maybe Int]`. > return $ map return v Wrapping the list *and* its items in `IO` seems excessive. Would it not be easier to have `values :: IO [Maybe Int]`? > main :: IO () > main = do > vs <- values > nvs <- mapM_ go vs > print nvs > where > go :: IO (Maybe Int) -> IO Int > go v' = do > Just v <- v' > return v > > when I run this script, I get a runtime error > > picca at diffabs6:~/tmp$ runhaskell test.hs > test.hs: user error (Pattern match failure in do expression at test.hs:13:10-15) > > What I want is a go method which skip silently the (IO Nothing) values. > so when used in the mapM_ it return only the values which are returned > by the IO (Maybe Int) (stored in the values) You can't, not with the route you've taken here. It would be the equivalent of skipping the `else` clause of an `if` statement. I suggest you rethink your approach of how to remove (filter out) the `Nothing` items in the list. /M -- Magnus Therning OpenPGP: 0x927912051716CE39 email: magnus at therning.org jabber: magnus at therning.org twitter: magthe http://therning.org/magnus Increasingly, people seem to misinterpret complexity as sophistication, which is baffling—the incomprehensible should cause suspicion rather than admiration. — Niklaus Wirth -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 832 bytes Desc: not available URL: From frederic-emmanuel.picca at synchrotron-soleil.fr Tue Jan 24 09:09:58 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Tue, 24 Jan 2017 09:09:58 +0000 Subject: [Haskell-beginners] (no subject) In-Reply-To: <87mvegltq3.fsf@therning.org> References: , <87mvegltq3.fsf@therning.org> Message-ID: Hello thanks for your time. > I would let the compiler deal with the type, i.e. skip the ` :: [Maybe Int]`. It was just a reduced example of my real problem. And I wanted to express the type for th ehuman of the mailing list :) > Wrapping the list *and* its items in `IO` seems excessive. Would it not > be easier to have `values :: IO [Maybe Int]`? No because the Maybe Int comes from an IO. But we solved the problem using the MaybeT MaybeT IO MyDataType So as you said, I rethink this with the help of the mailing list guyes. Thansk a lot Frederic From gilbertomelfe at gmail.com Tue Jan 24 11:29:00 2017 From: gilbertomelfe at gmail.com (Gilberto Melfe) Date: Tue, 24 Jan 2017 11:29:00 +0000 Subject: [Haskell-beginners] Memory Profiling Graph Explanation! Message-ID: Hello all! I'm trying to understand the memory allocation charts produced by the Haskell GHC profiler. My doubt at this moment is this: the graph shown at [1], is what is called an Area Graph; but I can't find information on what sort of area graph it is, is it an overlapped area graph or a stacked area graph? or put another way, is the higher point (more or less horizontally centered) value read from the x (seconds) axis (from 0K) or from the top "line" for the lesser area plots (namely from around 4k) So, is the highest value an absolute value taken from the y axis, or that value minus the higher value for the 2nd greatest area plot in the graph? Thank You Very Much in advance for any help! Gilberto Melfe [1] https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/profiling.html#profiling-memory-usage -------------- next part -------------- An HTML attachment was scrubbed... URL: From frederic-emmanuel.picca at synchrotron-soleil.fr Thu Jan 26 09:50:47 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Thu, 26 Jan 2017 09:50:47 +0000 Subject: [Haskell-beginners] system and FilePath with space Message-ID: Hello I try to execute a command using system. my code is like this system (unwords ["python", p]) where p :: FilePath p = "/my super/script.py" has you can see this path contain a space. When I try to run it I get an error python: can't open file '/my': So the system command is wrong. I understand that I need to escape the space in the command, like this p = "/my\ super/script.py" now is there a function in haskell for this. a sort of sanitizer for FilePath when used by system. Thanks Frederic From raabe at froglogic.com Thu Jan 26 10:03:42 2017 From: raabe at froglogic.com (Frerich Raabe) Date: Thu, 26 Jan 2017 11:03:42 +0100 Subject: [Haskell-beginners] system and FilePath with space In-Reply-To: References: Message-ID: <1c681ea7e9acb4a0b4038a946ec5045d@froglogic.com> On 2017-01-26 10:50, PICCA Frederic-Emmanuel wrote: > Hello > > I try to execute a command using system. > > my code is like this > > > system (unwords ["python", p]) An easier way to execute programs is to use the functions defined in System.Process, e.g.: import System.Process main :: IO () main = callProcess "/usr/bin/python" ["/my super/script.py"] Note that 'callProcess' takes a list of strings, each element being one argument. The elements may contain spaces. -- Frerich Raabe - raabe at froglogic.com www.froglogic.com - Multi-Platform GUI Testing From frederic-emmanuel.picca at synchrotron-soleil.fr Thu Jan 26 10:19:37 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Thu, 26 Jan 2017 10:19:37 +0000 Subject: [Haskell-beginners] system and FilePath with space In-Reply-To: <1c681ea7e9acb4a0b4038a946ec5045d@froglogic.com> References: , <1c681ea7e9acb4a0b4038a946ec5045d@froglogic.com> Message-ID: thanks but I do not have a recent enough ghc in order to use this method (debian jessie) maybe I can use proc in order to prepare my command line ? From michael at snoyman.com Thu Jan 26 10:21:56 2017 From: michael at snoyman.com (Michael Snoyman) Date: Thu, 26 Jan 2017 12:21:56 +0200 Subject: [Haskell-beginners] system and FilePath with space In-Reply-To: References: <1c681ea7e9acb4a0b4038a946ec5045d@froglogic.com> Message-ID: You can use the rawSystem function on older versions of the process package. On Thu, Jan 26, 2017 at 12:19 PM, PICCA Frederic-Emmanuel < frederic-emmanuel.picca at synchrotron-soleil.fr> wrote: > thanks but I do not have a recent enough ghc in order to use this method > (debian jessie) > > > maybe I can use proc in order to prepare my command line ? > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From frederic-emmanuel.picca at synchrotron-soleil.fr Thu Jan 26 10:33:27 2017 From: frederic-emmanuel.picca at synchrotron-soleil.fr (PICCA Frederic-Emmanuel) Date: Thu, 26 Jan 2017 10:33:27 +0000 Subject: [Haskell-beginners] system and FilePath with space In-Reply-To: References: <1c681ea7e9acb4a0b4038a946ec5045d@froglogic.com> , Message-ID: >You can use the rawSystem function on older versions of the process package. thanks , it is exactly what I wanted. Cheers From 50295 at web.de Thu Jan 26 15:41:35 2017 From: 50295 at web.de (Olumide) Date: Thu, 26 Jan 2017 15:41:35 +0000 Subject: [Haskell-beginners] Question about example in 'using do notation with Writer' section of LYH Message-ID: <41fadc2e-e456-b4fb-3943-ed896812c648@web.de> Hello List, Chapter 14 of LYH ( http://learnyouahaskell.com/for-a-few-monads-more#reader ) has the following bit of code: import Control.Monad.Writer logNumber :: Int -> Writer [String] Int logNumber x = Writer (x, ["Got number: " ++ show x]) multWithLog :: Writer [String] Int multWithLog = do a <- logNumber 3 b <- logNumber 5 return (a*b) I have a fair grasp of what's going bu the last line return(a*b) eludes me. Specifically its the a*b part that baffles me. I think 3 is bound to 'a' and 5 to 'b', then return(a*b) would put the value 15 in a context ... So what becomes of the string parts of the Writer monads created by logNumber 3 and logNumber 5 respectively. Regards, - Olumide From toad3k at gmail.com Thu Jan 26 16:02:44 2017 From: toad3k at gmail.com (David McBride) Date: Thu, 26 Jan 2017 11:02:44 -0500 Subject: [Haskell-beginners] Question about example in 'using do notation with Writer' section of LYH In-Reply-To: <41fadc2e-e456-b4fb-3943-ed896812c648@web.de> References: <41fadc2e-e456-b4fb-3943-ed896812c648@web.de> Message-ID: Nothing happens to them. They are still in there. Whereas logNumber always returns the number you give it, multiWithLog always returns 15 and appends two strings into its state ("got number 3 and 5"). You can return whatever value you want from a Monad. In this case he's doing a * b, but you could do 2 * b, Just (a + b) or anything else. As an example, here I return a tuple instead. multWithLogTuple :: Writer [String] (Int,Int,Int) multWithLogTuple = do a <- logNumber 3 b <- logNumber 5 return (a,b,2*b) >runWriter multWithLogTuple ((3,5,10),["Got number: 3","Got number: 5"]) On Thu, Jan 26, 2017 at 10:41 AM, Olumide <50295 at web.de> wrote: > Hello List, > > Chapter 14 of LYH ( http://learnyouahaskell.com/for-a-few-monads-more#reader > ) has the following bit of code: > > > import Control.Monad.Writer > > logNumber :: Int -> Writer [String] Int > logNumber x = Writer (x, ["Got number: " ++ show x]) > > multWithLog :: Writer [String] Int > multWithLog = do > a <- logNumber 3 > b <- logNumber 5 > return (a*b) > > I have a fair grasp of what's going bu the last line return(a*b) eludes me. > Specifically its the a*b part that baffles me. I think 3 is bound to 'a' and > 5 to 'b', then return(a*b) would put the value 15 in a context ... So what > becomes of the string parts of the Writer monads created by logNumber 3 and > logNumber 5 respectively. > > Regards, > > - Olumide > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From imantc at gmail.com Thu Jan 26 16:10:55 2017 From: imantc at gmail.com (Imants Cekusins) Date: Thu, 26 Jan 2017 17:10:55 +0100 Subject: [Haskell-beginners] Question about example in 'using do notation with Writer' section of LYH In-Reply-To: <41fadc2e-e456-b4fb-3943-ed896812c648@web.de> References: <41fadc2e-e456-b4fb-3943-ed896812c648@web.de> Message-ID: > what becomes of the string parts of the Writer monads multWithLog keeps [String] and outputs Int to fully benefit from Writer [String] Int, you'd call e.g. runWriter or execWriter similar to other *State state out* monads, *m state out* lets you get/set/keep state as needed without passing it as an arg. *state* is there if you need it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From 50295 at web.de Thu Jan 26 18:00:08 2017 From: 50295 at web.de (Olumide) Date: Thu, 26 Jan 2017 18:00:08 +0000 Subject: [Haskell-beginners] Question about example in 'using do notation with Writer' section of LYH In-Reply-To: References: <41fadc2e-e456-b4fb-3943-ed896812c648@web.de> Message-ID: <23309531-2d21-c413-d3c3-dcd266ec23a4@web.de> On 26/01/2017 16:02, David McBride wrote: > Nothing happens to them. They are still in there. Whereas logNumber > always returns the number you give it, multiWithLog always returns 15 > and appends two strings into its state ("got number 3 and 5"). > > You can return whatever value you want from a Monad. In this case > he's doing a * b, but you could do 2 * b, Just (a + b) or anything > else. As an example, here I return a tuple instead. > > multWithLogTuple :: Writer [String] (Int,Int,Int) > multWithLogTuple = do > a <- logNumber 3 > b <- logNumber 5 > return (a,b,2*b) > So return (a*b) still creates Writer [String] Int? I thought the [String] parts of 'a' and 'b' ought to be in the result but I see it needn't. - Olumide From 50295 at web.de Thu Jan 26 21:34:42 2017 From: 50295 at web.de (Olumide) Date: Thu, 26 Jan 2017 21:34:42 +0000 Subject: [Haskell-beginners] Question about example in 'using do notation with Writer' section of LYH In-Reply-To: References: <41fadc2e-e456-b4fb-3943-ed896812c648@web.de> Message-ID: On 26/01/17 16:02, David McBride wrote: >> runWriter multWithLogTuple > ((3,5,10),["Got number: 3","Got number: 5"]) On second thoughts I don't think I understand how the logs are concatenated. I was expecting (15,["Got number: 15") in the original example. - Olumide From atrudyjane at protonmail.com Thu Jan 26 21:55:12 2017 From: atrudyjane at protonmail.com (Atrudyjane) Date: Thu, 26 Jan 2017 16:55:12 -0500 Subject: [Haskell-beginners] Semigroup Instances Message-ID: <82H33KLF09rxs-mmILyQ-aBsaKQFCiANhJ4FMZwOCjQ7AYiPtd3noxIcauSDVqrGs1xNbVMYNM_Vc5lrNgJPsN-mEe24my553xoFockn2kM=@protonmail.com> I'm currently studying semigroups and trying to figure out how to determine which type variables need a semigroup instance. Here are a couple of examples from Evan Cameron's github (https://github.com/leshow/haskell-programming-book/blob/master/src/Ch15ex.hs): (1) data Validation a b = Failure a | Success b deriving (Eq, Show) instance Semigroup a => Semigroup (Validation a b) where Success a <> Success b = Success a Failure a <> Success b = Success b Success a <> Failure b = Success a Failure a <> Failure b = Failure (a <> b) * Why doesn't 'b' need an instance of semigroup? (2) newtype AccumulateRight a b = AccumulateRight (Validation a b) deriving (Eq, Show) instance Semigroup b => Semigroup (AccumulateRight a b) where AccumulateRight (Success a) <>AccumulateRight (Failure b) =AccumulateRight (Success a) AccumulateRight (Failure a) <>AccumulateRight (Success b) =AccumulateRight (Success b) AccumulateRight (Failure a) <>AccumulateRight (Failure b) =AccumulateRight (Failure a) AccumulateRight (Success a) <> AccumulateRight (Success b) = AccumulateRight (Success (a <> b)) * Why doesn't 'a' need an instance of semigroup? Thank you, Andrea Sent with [ProtonMail](https://protonmail.com) Secure Email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tanuki at gmail.com Fri Jan 27 08:34:29 2017 From: tanuki at gmail.com (Theodore Lief Gannon) Date: Fri, 27 Jan 2017 00:34:29 -0800 Subject: [Haskell-beginners] Question about example in 'using do notation with Writer' section of LYH In-Reply-To: References: <41fadc2e-e456-b4fb-3943-ed896812c648@web.de> Message-ID: Fully expanding your program might help. One of the great things about Haskell is equational reasoning: if two things have been declared equal, you can substitute one for the other. First, let's desugar that do notation to the equivalent bind chain: multWithLog = logNumber 3 >>= \a -> logNumber 5 >>= \b -> return (a*b) Evaluate the logNumber and return calls to normal form from their definitions, also considering the monoid definitions of (++) and mempty for lists: multWithLog = Writer (3, ["Got number: 3"]) >>= \a -> Writer (5, ["Got number: 5"]) >>= \b -> Writer (a*b, []) Now, refer to the definition of (>>=) for Writer (as shown in LYAH): (Writer (x, v)) >>= f = let (Writer (y, v')) = f x in Writer (y, v `mappend` v') Rewritten as a lamba (and replacing `mappend` with (++) for brevity), this becomes: \(Writer (x, v)) f -> let (Writer (y, v')) = f x in Writer (y, v++v') It's no longer an infix function, so we'll have to shift things around a little. Here's what it expands to: multWithLog = (\(Writer (x, v)) f -> -- \ let (Writer (y, v')) = f x -- | bind in Writer (y, v++v')) -- / (Writer (3, ["Got number: 3"])) -- Writer (x, v) (\a -> -- f (\(Writer (x2, v2)) f2 -> -- \ let (Writer (y2, v2')) = f2 x2 -- | bind in Writer (y2, v2++v2')) -- / (Writer (5, ["Got number: 5"])) -- Writer (x2, v2) (\b -> Writer (a*b, [])) -- f2 ) -- (end f) Now it's just a matter of simplification. Let's start by eliminating the first argument of each bind, i.e. (Writer (x,v)), by substituting with concrete values. multWithLog = (\f -> -- \ partially let (Writer (y, v')) = f 3 -- | applied in Writer (y, ["Got number: 3"]++v')) -- / bind (\a -> -- f (\f2 -> -- \ partially let (Writer (y2, v2')) = f2 5 -- | applied in Writer (y2, ["Got number: 5"]++v2')) -- / bind (\b -> Writer (a*b, [])) -- f2 ) -- (end f) Substitute f2, and eliminate both \f2 and \b in the same way: multWithLog = (\f -> let (Writer (y, v')) = f 3 in Writer (y, ["Got number: 3"]++v')) (\a -> let (Writer (y2, v2')) = Writer (a*5, []) -- applied f2 in Writer (y2, ["Got number: 5"]++v2') ) With a full match on the inner let block, that can also be eliminated: multWithLog = (\f -> let (Writer (y, v')) = f 3 in Writer (y, ["Got number: 3"]++v')) (\a -> Writer (a*5, ["Got number: 5"]++[])) I'll forego the last few substitutions. If it's still not clear how you get to the final output, you should run through them yourself. You'll eventually reach a static definition of the result -- which shouldn't really be surprising, since there were no arguments to this "function" and its type doesn't contain -> anywhere. :) On Thu, Jan 26, 2017 at 1:34 PM, Olumide <50295 at web.de> wrote: > On 26/01/17 16:02, David McBride wrote: > >> runWriter multWithLogTuple >>> >> ((3,5,10),["Got number: 3","Got number: 5"]) >> > > On second thoughts I don't think I understand how the logs are > concatenated. I was expecting (15,["Got number: 15") in the original > example. > > > - Olumide > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at mostrom.pp.se Fri Jan 27 11:23:56 2017 From: lists at mostrom.pp.se (Jan Erik =?utf-8?q?Mostr=C3=B6m?=) Date: Fri, 27 Jan 2017 12:23:56 +0100 Subject: [Haskell-beginners] Change in type that I don't understand Message-ID: <38EF2A30-6EA4-4844-A802-11BF7BC261F5@mostrom.pp.se> Hi, Here is something that I don't understand, why does the named value have a different type than just the value itself? Prelude> let f x = x * x Prelude> :t f f :: Num a => a -> a Prelude> :t [f] [f] :: Num a => [a -> a] Prelude> let g = [f] Prelude> :t g g :: [Integer -> Integer] = jem From daniel.trstenjak at gmail.com Fri Jan 27 12:08:35 2017 From: daniel.trstenjak at gmail.com (Daniel Trstenjak) Date: Fri, 27 Jan 2017 13:08:35 +0100 Subject: [Haskell-beginners] Change in type that I don't understand In-Reply-To: <38EF2A30-6EA4-4844-A802-11BF7BC261F5@mostrom.pp.se> References: <38EF2A30-6EA4-4844-A802-11BF7BC261F5@mostrom.pp.se> Message-ID: <20170127120835.GA3233@octa> Hi Jan, > Here is something that I don't understand, why does the named value have a > different type than just the value itself? Looks like a bug in your ghci version. With version 7.10.2 I'm getting: > :t g g :: Num a => [a -> a] Grettings, Daniel From toad3k at gmail.com Fri Jan 27 13:35:08 2017 From: toad3k at gmail.com (David McBride) Date: Fri, 27 Jan 2017 08:35:08 -0500 Subject: [Haskell-beginners] Change in type that I don't understand In-Reply-To: <38EF2A30-6EA4-4844-A802-11BF7BC261F5@mostrom.pp.se> References: <38EF2A30-6EA4-4844-A802-11BF7BC261F5@mostrom.pp.se> Message-ID: If you have the Monomorphism restriction set, it will choose types based on the type defaulting rules (Num changes to Integer). This is because polymorphic code is slower than code that has concrete types. Try :set -XNoMonomorphismRestriction, then test it again. It may be that different versions of ghci have a different default for that pragma. On Fri, Jan 27, 2017 at 6:23 AM, Jan Erik Moström wrote: > Hi, > > Here is something that I don't understand, why does the named value have a > different type than just the value itself? > > Prelude> let f x = x * x > Prelude> :t f > f :: Num a => a -> a > Prelude> :t [f] > [f] :: Num a => [a -> a] > Prelude> let g = [f] > Prelude> :t g > g :: [Integer -> Integer] > > = jem > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From daniel.trstenjak at gmail.com Fri Jan 27 15:17:48 2017 From: daniel.trstenjak at gmail.com (Daniel Trstenjak) Date: Fri, 27 Jan 2017 16:17:48 +0100 Subject: [Haskell-beginners] Change in type that I don't understand In-Reply-To: References: <38EF2A30-6EA4-4844-A802-11BF7BC261F5@mostrom.pp.se> Message-ID: <20170127151748.GA9028@octa> On Fri, Jan 27, 2017 at 08:35:08AM -0500, David McBride wrote: > If you have the Monomorphism restriction set, it will choose types > based on the type defaulting rules (Num changes to Integer). This is > because polymorphic code is slower than code that has concrete types. But why didn't the defaulting rules have been applied for both: 'f' and 'g'? Greetings, Daniel From toad3k at gmail.com Fri Jan 27 15:43:28 2017 From: toad3k at gmail.com (David McBride) Date: Fri, 27 Jan 2017 10:43:28 -0500 Subject: [Haskell-beginners] Change in type that I don't understand In-Reply-To: <20170127151748.GA9028@octa> References: <38EF2A30-6EA4-4844-A802-11BF7BC261F5@mostrom.pp.se> <20170127151748.GA9028@octa> Message-ID: Because f has an argument x, and g doesn't. On Fri, Jan 27, 2017 at 10:17 AM, Daniel Trstenjak wrote: > > On Fri, Jan 27, 2017 at 08:35:08AM -0500, David McBride wrote: >> If you have the Monomorphism restriction set, it will choose types >> based on the type defaulting rules (Num changes to Integer). This is >> because polymorphic code is slower than code that has concrete types. > > But why didn't the defaulting rules have been applied for both: 'f' and 'g'? > > Greetings, > Daniel > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From toad3k at gmail.com Fri Jan 27 15:53:47 2017 From: toad3k at gmail.com (David McBride) Date: Fri, 27 Jan 2017 10:53:47 -0500 Subject: [Haskell-beginners] Change in type that I don't understand In-Reply-To: <20170127151748.GA9028@octa> References: <38EF2A30-6EA4-4844-A802-11BF7BC261F5@mostrom.pp.se> <20170127151748.GA9028@octa> Message-ID: Sorry let me elaborate. The type of f depends on its argument. The argument could be anything that the caller passes in so long as it is an instance of Num. If the user passes in Int or Integer or Float, it has to handle all those cases. It can't just type restrict the argument to Int, that is likely not what the user wanted. If he had he would have type restricted it himself. g on the other hand has complete control over its own type. If mm restriction is enabled and there is no type declaration then it is reasonable for it to default to a concrete type so that it only has to generate only one possible code path. If it isn't enabled then it will try to be as polymorphic as possible, at the cost of being flexible enough to return any type that is an instance of Num. On Fri, Jan 27, 2017 at 10:17 AM, Daniel Trstenjak wrote: > > On Fri, Jan 27, 2017 at 08:35:08AM -0500, David McBride wrote: >> If you have the Monomorphism restriction set, it will choose types >> based on the type defaulting rules (Num changes to Integer). This is >> because polymorphic code is slower than code that has concrete types. > > But why didn't the defaulting rules have been applied for both: 'f' and 'g'? > > Greetings, > Daniel > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From daniel.trstenjak at gmail.com Fri Jan 27 16:29:09 2017 From: daniel.trstenjak at gmail.com (Daniel Trstenjak) Date: Fri, 27 Jan 2017 17:29:09 +0100 Subject: [Haskell-beginners] Change in type that I don't understand In-Reply-To: References: <38EF2A30-6EA4-4844-A802-11BF7BC261F5@mostrom.pp.se> <20170127151748.GA9028@octa> Message-ID: <20170127162909.GB11209@octa> Thank you for the nice explanation! Greetings, Daniel From brutallesale at gmail.com Fri Jan 27 22:09:07 2017 From: brutallesale at gmail.com (sasa bogicevic) Date: Fri, 27 Jan 2017 23:09:07 +0100 Subject: [Haskell-beginners] applicative instance Message-ID: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> What is wrong with my applicative instance for custom List type ? http://lpaste.net/351723 data List a = Nil | Cons a (List a) deriving (Eq, Show) instance Applicative List where pure x = Cons x Nil Nil <*> _ = Nil _ <*> Nil = Nil (Cons x xy) <*> (Cons z dy) = Cons (x z) (xy <*> dy) Prelude> let functions = Cons (+1) (Cons (*2) Nil) Prelude> let values = Cons 1 (Cons 2 Nil) Prelude> functions <*> values Cons 2 (Cons 3 (Cons 2 (Cons 4 Nil))) -- I get Cons 2 (Cons 4 Nil) what is wrong with my Applicative instance ? { name: Bogicevic Sasa phone: +381606006200 } From edwards.benj at gmail.com Fri Jan 27 22:17:35 2017 From: edwards.benj at gmail.com (Benjamin Edwards) Date: Fri, 27 Jan 2017 22:17:35 +0000 Subject: [Haskell-beginners] applicative instance In-Reply-To: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> References: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> Message-ID: You are zipping rather than taking the cross product. Ben On Fri, 27 Jan 2017, 22:09 sasa bogicevic, wrote: > What is wrong with my applicative instance for custom List type ? > > http://lpaste.net/351723 > > data List a = Nil | Cons a (List a) deriving (Eq, Show) > > > > instance Applicative List where > pure x = Cons x Nil > Nil <*> _ = Nil > _ <*> Nil = Nil > (Cons x xy) <*> (Cons z dy) = Cons (x z) (xy <*> dy) > > Prelude> let functions = Cons (+1) (Cons (*2) Nil) > Prelude> let values = Cons 1 (Cons 2 Nil) > Prelude> functions <*> values > Cons 2 (Cons 3 (Cons 2 (Cons 4 Nil))) -- I get Cons 2 (Cons 4 Nil) what > is wrong with my Applicative instance ? > > > { > name: Bogicevic Sasa > phone: +381606006200 > } > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fa-ml at ariis.it Fri Jan 27 22:21:35 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Fri, 27 Jan 2017 23:21:35 +0100 Subject: [Haskell-beginners] applicative instance In-Reply-To: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> References: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> Message-ID: <20170127222135.GA5233@casa.casa> On Fri, Jan 27, 2017 at 11:09:07PM +0100, sasa bogicevic wrote: > What is wrong with my applicative instance for custom List type ? > > http://lpaste.net/351723 > > [..] You have implemented <*> on a list in one of the many possible (and sensible) ways. In regular Haskell it's a ZipList λ> :m Control.Applicative λ> ZipList [(+1), (*2)] <*> ZipList [1,2] ZipList {getZipList = [2,4]} (and there's nothing wrong with that) From brutallesale at gmail.com Sat Jan 28 09:09:10 2017 From: brutallesale at gmail.com (sasa bogicevic) Date: Sat, 28 Jan 2017 10:09:10 +0100 Subject: [Haskell-beginners] applicative instance In-Reply-To: <20170127222135.GA5233@casa.casa> References: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> <20170127222135.GA5233@casa.casa> Message-ID: Ok so how would the implementation look to get the correct result ? I can't seem to write something that will compile except ZipList version. Thanks, Sasa > On Jan 27, 2017, at 23:21, Francesco Ariis wrote: > > On Fri, Jan 27, 2017 at 11:09:07PM +0100, sasa bogicevic wrote: >> What is wrong with my applicative instance for custom List type ? >> >> http://lpaste.net/351723 >> >> [..] > > You have implemented <*> on a list in one of the many possible > (and sensible) ways. In regular Haskell it's a ZipList > > λ> :m Control.Applicative > λ> ZipList [(+1), (*2)] <*> ZipList [1,2] > ZipList {getZipList = [2,4]} > > (and there's nothing wrong with that) > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From fa-ml at ariis.it Sat Jan 28 09:43:45 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Sat, 28 Jan 2017 10:43:45 +0100 Subject: [Haskell-beginners] applicative instance In-Reply-To: References: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> <20170127222135.GA5233@casa.casa> Message-ID: <20170128094345.GA2593@casa.casa> On Sat, Jan 28, 2017 at 10:09:10AM +0100, sasa bogicevic wrote: > Ok so how would the implementation look to get the correct result ? > I can't seem to write something that will compile except ZipList version. One way is by implementing your own (++): data List a = Nil | Cons a (List a) deriving (Eq, Show) plusPlus :: List a -> List a -> List a plusPlus Nil bs = bs plusPlus (Cons a as) bs = Cons a (as `plusPlus` bs) instance Functor List where fmap f Nil = Nil fmap f (Cons a b) = Cons (f a) (fmap f b) instance Applicative List where pure x = Cons x Nil Nil <*> _ = Nil _ <*> Nil = Nil (Cons x xy) <*> ys = (fmap x ys) `plusPlus` (xy <*> ys) From brutallesale at gmail.com Sat Jan 28 09:53:07 2017 From: brutallesale at gmail.com (sasa bogicevic) Date: Sat, 28 Jan 2017 10:53:07 +0100 Subject: [Haskell-beginners] applicative instance In-Reply-To: <20170128094345.GA2593@casa.casa> References: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> <20170127222135.GA5233@casa.casa> <20170128094345.GA2593@casa.casa> Message-ID: <432542C4-01E7-4E22-A563-7068906C4335@gmail.com> Yep that worked, thanks. Is there a way to do it without defining a separate function like plusPlus ? > On Jan 28, 2017, at 10:43, Francesco Ariis wrote: > > On Sat, Jan 28, 2017 at 10:09:10AM +0100, sasa bogicevic wrote: >> Ok so how would the implementation look to get the correct result ? >> I can't seem to write something that will compile except ZipList version. > > One way is by implementing your own (++): > > data List a = Nil | Cons a (List a) deriving (Eq, Show) > > plusPlus :: List a -> List a -> List a > plusPlus Nil bs = bs > plusPlus (Cons a as) bs = Cons a (as `plusPlus` bs) > > instance Functor List where > fmap f Nil = Nil > fmap f (Cons a b) = Cons (f a) (fmap f b) > > instance Applicative List where > pure x = Cons x Nil > Nil <*> _ = Nil > _ <*> Nil = Nil > (Cons x xy) <*> ys = (fmap x ys) `plusPlus` (xy <*> ys) > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From ivan.v.kush at yandex.ru Sat Jan 28 20:09:09 2017 From: ivan.v.kush at yandex.ru (Ivan Kush) Date: Sat, 28 Jan 2017 23:09:09 +0300 Subject: [Haskell-beginners] Ambiguous type variable prevents the constraint `(Ord t0)' from being solved. Message-ID: <5152611485634149@web34j.yandex.ru> I get this error (full message at the end of the mail). How could I correct my code? =================== Code: =================== module Intro where import Data.Bits -- for xor, .&. data Func a b = Empty | Leaf Int [(a, b)] | Branch Int Int (Func a b) (Func a b) applyd = let apply_listd l d x = case l of [] -> d x (a, b) : t -> let c = compare x a in if c == EQ then b else if c == GT then apply_listd t d x else d x in \f d x -> let k = 5 -- hash x - todo in let look t = case t of Leaf h l | h == k -> apply_listd l d x Branch p b l r | (k `xor` p) .&. (b - 1) == 0 -> -- (Branch p b l r) | ((k xor p) .&. (b - 1)) == 0 -> look (if k .&. b == 0 then l else r) _ -> d x in look f =================== Error: =================== Intro.hs:37:25: error: * Ambiguous type variable `t0' arising from a use of `apply_listd' prevents the constraint `(Ord t0)' from being solved. Relevant bindings include l :: [(t0, t)] (bound at Intro.hs:36:28) t :: Func t0 t (bound at Intro.hs:34:21) look :: Func t0 t -> t (bound at Intro.hs:34:16) x :: t0 (bound at Intro.hs:32:15) d :: t0 -> t (bound at Intro.hs:32:13) f :: Func t0 t (bound at Intro.hs:32:11) (Some bindings suppressed; use -fmax-relevant-binds=N or -fno-max-relevant-binds) Probable fix: use a type annotation to specify what `t0' should be. These potential instances exist: instance Ord Ordering -- Defined in `GHC.Classes' instance Ord Integer -- Defined in `integer-gmp-1.0.0.1:GHC.Integer.Type' instance Ord a => Ord (Maybe a) -- Defined in `GHC.Base' ...plus 22 others ...plus five instances involving out-of-scope types (use -fprint-potential-instances to see them all) * In the expression: apply_listd l d x In a case alternative: Leaf h l | h == k -> apply_listd l d x In the expression: case t of { Leaf h l | h == k -> apply_listd l d x Branch p b l r | (k `xor` p) .&. (b - 1) == 0 -> look (if k .&. b == 0 then l else r) _ -> d x } --  Best wishes, Ivan Kush From math.simplex at gmail.com Mon Jan 30 05:57:26 2017 From: math.simplex at gmail.com (Graham Gill) Date: Mon, 30 Jan 2017 00:57:26 -0500 Subject: [Haskell-beginners] applicative instance In-Reply-To: <432542C4-01E7-4E22-A563-7068906C4335@gmail.com> References: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> <20170127222135.GA5233@casa.casa> <20170128094345.GA2593@casa.casa> <432542C4-01E7-4E22-A563-7068906C4335@gmail.com> Message-ID: <989594d3-c665-3840-7b49-9e0a0368d505@gmail.com> On 28-Jan-2017 4:53 AM, sasa bogicevic wrote: > Is there a way to do it without defining a separate function like > plusPlus ? My guess is there isn't. I'm unsure what you mean by your question though. Your List is a reimplementation of Haskell []. So, List with the "Cartesian product" Applicative instance will, like Haskell [], extend to a Monad instance. In the Monad instance for [], join = concat, and the work of concat is done using ++. For List, we can implement join using concatList: concatList :: List (List a) -> List a concatList Nil = Nil concatList (Cons xs xss) = xs `plusPlus` (concatList xss) and then we can add a Monad instance for List: instance Monad List where return = pure xs >>= f = concatList (pure f <*> xs) or equivalently, bind isgiven by xs >>= f = concatList (fmap f xs) To ask whether you can define the Cartesian product Applicative instance for List without plusPlus, is, I think, like asking whether there is a Cartesian product Applicative instance for List (or []) which doesn't extend to a Monad instance. Because if it does extend to a Monad (that obeys the Monad laws), then there will exist an implementation of join :: List (List a) -> List a, and join will need to collapse a List of Lists into a List. A function like plusPlus is used to accomplish the collapse. That's "proof by hand waving." The Ziplist Applicative instance for List on the other hand can't be extended to a Monad instance without additional restrictions on the lengths of the lists. Your question led me to some interesting reading with a google search on "list monad vs ziplist". Thanks. On 28-Jan-2017 4:53 AM, sasa bogicevic wrote: > Yep that worked, thanks. > Is there a way to do it without defining a separate function like plusPlus ? > > > > > >> On Jan 28, 2017, at 10:43, Francesco Ariis wrote: >> >> On Sat, Jan 28, 2017 at 10:09:10AM +0100, sasa bogicevic wrote: >>> Ok so how would the implementation look to get the correct result ? >>> I can't seem to write something that will compile except ZipList version. >> One way is by implementing your own (++): >> >> data List a = Nil | Cons a (List a) deriving (Eq, Show) >> >> plusPlus :: List a -> List a -> List a >> plusPlus Nil bs = bs >> plusPlus (Cons a as) bs = Cons a (as `plusPlus` bs) >> >> instance Functor List where >> fmap f Nil = Nil >> fmap f (Cons a b) = Cons (f a) (fmap f b) >> >> instance Applicative List where >> pure x = Cons x Nil >> Nil <*> _ = Nil >> _ <*> Nil = Nil >> (Cons x xy) <*> ys = (fmap x ys) `plusPlus` (xy <*> ys) >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From traqueofziche at gmail.com Mon Jan 30 08:38:44 2017 From: traqueofziche at gmail.com (=?UTF-8?B?6bKN5Yev5paH?=) Date: Mon, 30 Jan 2017 00:38:44 -0800 Subject: [Haskell-beginners] Ambiguous type variable prevents the constraint `(Ord t0)' from being solved. Message-ID: Hi, I refactored it as such: apply_listd [] d x = d x apply_listd ((a,b):t) d x = case compare x a of EQ -> a GT -> b _ -> d x applyd f d x = look f where k = 5 look (Leaf h l) | h == k = apply_listd l d x look (Branch p b l r) | (k `xor` p) .&. (b - 1) == 0 = look (if k .&. b == 0 then l else r) look _ = d x ...and it compiled so i'm not sure what happened there. Simpler though: adding the type signature applyd :: Ord a => Func a b -> (a -> b) -> a -> b also made it compile. I'm not sure why ghc thinks there's multiple instances to choose from (somebody please explain), but in any case adding type signatures will give you better error messages/help ghc. Hope that helps a bit. On Sun, Jan 29, 2017 at 4:00 AM, wrote: > Send Beginners mailing list submissions to > beginners at haskell.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > or, via email, send a message with subject or body 'help' to > beginners-request at haskell.org > > You can reach the person managing the list at > beginners-owner at haskell.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Beginners digest..." > > > Today's Topics: > > 1. Ambiguous type variable prevents the constraint `(Ord t0)' > from being solved. (Ivan Kush) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 28 Jan 2017 23:09:09 +0300 > From: Ivan Kush > To: beginners at haskell.org > Subject: [Haskell-beginners] Ambiguous type variable prevents the > constraint `(Ord t0)' from being solved. > Message-ID: <5152611485634149 at web34j.yandex.ru> > Content-Type: text/plain; charset=utf-8 > > I get this error (full message at the end of the mail). How could I > correct my code? > > > =================== > Code: > =================== > > module Intro where > > import Data.Bits -- for xor, .&. > > data Func a b > = Empty > | Leaf Int [(a, b)] > | Branch Int Int (Func a b) (Func a b) > > applyd = > let apply_listd l d x = > case l of > [] -> d x > (a, b) : t -> > let c = compare x a > in if c == EQ then b > else if c == GT then apply_listd t d x > else d x > > in \f d x -> > let k = 5 -- hash x - todo > in let look t = > case t of > Leaf h l | h == k -> > apply_listd l d x > Branch p b l r | (k `xor` p) .&. (b - 1) == 0 -> -- > (Branch p b l r) | ((k xor p) .&. (b - 1)) == 0 -> > look (if k .&. b == 0 then l else r) > _ -> d x > in look f > > > > =================== > Error: > =================== > > Intro.hs:37:25: error: > * Ambiguous type variable `t0' arising from a use of `apply_listd' > prevents the constraint `(Ord t0)' from being solved. > Relevant bindings include > l :: [(t0, t)] (bound at Intro.hs:36:28) > t :: Func t0 t (bound at Intro.hs:34:21) > look :: Func t0 t -> t (bound at Intro.hs:34:16) > x :: t0 (bound at Intro.hs:32:15) > d :: t0 -> t (bound at Intro.hs:32:13) > f :: Func t0 t (bound at Intro.hs:32:11) > (Some bindings suppressed; use -fmax-relevant-binds=N or > -fno-max-relevant-binds) > Probable fix: use a type annotation to specify what `t0' should be. > These potential instances exist: > instance Ord Ordering -- Defined in `GHC.Classes' > instance Ord Integer > -- Defined in `integer-gmp-1.0.0.1:GHC.Integer.Type' > instance Ord a => Ord (Maybe a) -- Defined in `GHC.Base' > ...plus 22 others > ...plus five instances involving out-of-scope types > (use -fprint-potential-instances to see them all) > * In the expression: apply_listd l d x > In a case alternative: Leaf h l | h == k -> apply_listd l d x > In the expression: > case t of { > Leaf h l | h == k -> apply_listd l d x > Branch p b l r > | (k `xor` p) .&. (b - 1) == 0 > -> look (if k .&. b == 0 then l else r) > _ -> d x } > > > -- > Best wishes, > Ivan Kush > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > ------------------------------ > > End of Beginners Digest, Vol 103, Issue 25 > ****************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From brutallesale at gmail.com Mon Jan 30 08:48:38 2017 From: brutallesale at gmail.com (sasa bogicevic) Date: Mon, 30 Jan 2017 09:48:38 +0100 Subject: [Haskell-beginners] applicative instance In-Reply-To: <989594d3-c665-3840-7b49-9e0a0368d505@gmail.com> References: <7BEA3C9A-BA94-40A9-9514-E17F4C1F88A6@gmail.com> <20170127222135.GA5233@casa.casa> <20170128094345.GA2593@casa.casa> <432542C4-01E7-4E22-A563-7068906C4335@gmail.com> <989594d3-c665-3840-7b49-9e0a0368d505@gmail.com> Message-ID: <18D14B30-0DE4-4CB0-818E-226865C9D6A1@gmail.com> Wow thanks for the indepth explanation. I am glad that this got you reading some stuff but the fact is I was just doing an exercise in writing Applicative instances for some types and it was not stated that we should use separate 'helper' functions to achieve this. So I banged my head trying to write the correct implementation but I could only come up with the zipList solution. Thanks again! Sasa > On Jan 30, 2017, at 06:57, Graham Gill wrote: > > > On 28-Jan-2017 4:53 AM, sasa bogicevic wrote: >> Is there a way to do it without defining a separate function like plusPlus ? > > My guess is there isn't. I'm unsure what you mean by your question though. > > Your List is a reimplementation of Haskell []. So, List with the "Cartesian product" Applicative instance will, like Haskell [], extend to a Monad instance. In the Monad instance for [], join = concat, and the work of concat is done using ++. > > For List, we can implement join using concatList: > > concatList :: List (List a) -> List a > concatList Nil = Nil > concatList (Cons xs xss) = xs `plusPlus` (concatList xss) > > and then we can add a Monad instance for List: > > instance Monad List where > return = pure > xs >>= f = concatList (pure f <*> xs) > > or equivalently, bind is given by > xs >>= f = concatList (fmap f xs) > > To ask whether you can define the Cartesian product Applicative instance for List without plusPlus, is, I think, like asking whether there is a Cartesian product Applicative instance for List (or []) which doesn't extend to a Monad instance. Because if it does extend to a Monad (that obeys the Monad laws), then there will exist an implementation of join :: List (List a) -> List a, and join will need to collapse a List of Lists into a List. A function like plusPlus is used to accomplish the collapse. > > That's "proof by hand waving." > > The Ziplist Applicative instance for List on the other hand can't be extended to a Monad instance without additional restrictions on the lengths of the lists. Your question led me to some interesting reading with a google search on "list monad vs ziplist". Thanks. > > > On 28-Jan-2017 4:53 AM, sasa bogicevic wrote: >> Yep that worked, thanks. >> Is there a way to do it without defining a separate function like plusPlus ? >> >> >> >> >> >> >>> On Jan 28, 2017, at 10:43, Francesco Ariis >>> wrote: >>> >>> On Sat, Jan 28, 2017 at 10:09:10AM +0100, sasa bogicevic wrote: >>> >>>> Ok so how would the implementation look to get the correct result ? >>>> I can't seem to write something that will compile except ZipList version. >>>> >>> One way is by implementing your own (++): >>> >>> data List a = Nil | Cons a (List a) deriving (Eq, Show) >>> >>> plusPlus :: List a -> List a -> List a >>> plusPlus Nil bs = bs >>> plusPlus (Cons a as) bs = Cons a (as `plusPlus` bs) >>> >>> instance Functor List where >>> fmap f Nil = Nil >>> fmap f (Cons a b) = Cons (f a) (fmap f b) >>> >>> instance Applicative List where >>> pure x = Cons x Nil >>> Nil <*> _ = Nil >>> _ <*> Nil = Nil >>> (Cons x xy) <*> ys = (fmap x ys) `plusPlus` (xy <*> ys) >>> >>> _______________________________________________ >>> Beginners mailing list >>> >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> _______________________________________________ >> Beginners mailing list >> >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners