From aquagnu at gmail.com Fri Sep 1 14:18:02 2017 From: aquagnu at gmail.com (Baa) Date: Fri, 1 Sep 2017 17:18:02 +0300 Subject: [Haskell-beginners] Restrict type in phantom data-type Message-ID: <20170901171802.2819db2e@Pavel> Hello, List! For example, I have specialized (right nameis phantom?) type: data Day a = Day { ... no `a` here } data Sunny data Rainy joyToday :: Day Sunny -> IO () joyToday day = ... melancholyToday :: Day Rainy -> IO () melancholyToday day = ... And I can create (in spite of that it's phantom) some day: let day1 = Day {...} :: Day Sunny joyToday day1 but no problem to create `Day Int`, `Day Char`, etc which is pointless actually (sure "creator"-function can be exported from the module only, but I'm talking about type-level solution). I know that constraints (`... =>`) on data types are redundant/removed from the language. And I'm not sure how it's possible to restrict that parameter `a` (I know that it's possible to Java/C++/Perl6 (not sure), some other languages but how to add such restriction in Haskell? IMHO type families can help but I'm not sure how it will look (Sunny, Rainy are "nullary" type, so...). Is it possible for Haskell too? === Best regards, Paul From toad3k at gmail.com Fri Sep 1 14:50:09 2017 From: toad3k at gmail.com (David McBride) Date: Fri, 1 Sep 2017 10:50:09 -0400 Subject: [Haskell-beginners] Restrict type in phantom data-type In-Reply-To: <20170901171802.2819db2e@Pavel> References: <20170901171802.2819db2e@Pavel> Message-ID: This is maybe edging toward haskell-cafe territory, but you can definitely do this in haskell. {-# LANGUAGE DataKinds, KindSignatures #-} data DayType = Sunny | Rainy data Day (a :: DayType) = Day sunnyDay :: Day Sunny sunnyDay = Day rainyDay :: Day Rainy rainyDay = Day -- impossibleDay :: Day () -- impossibleDay = Day On Fri, Sep 1, 2017 at 10:18 AM, Baa wrote: > Hello, List! > > For example, I have specialized (right nameis phantom?) type: > > data Day a = Day { ... no `a` here } > data Sunny > data Rainy > > joyToday :: Day Sunny -> IO () > joyToday day = ... > > melancholyToday :: Day Rainy -> IO () > melancholyToday day = ... > > And I can create (in spite of that it's phantom) some day: > > let day1 = Day {...} :: Day Sunny > joyToday day1 > > but no problem to create `Day Int`, `Day Char`, etc which is > pointless actually (sure "creator"-function can be exported from the > module only, but I'm talking about type-level solution). > > I know that constraints (`... =>`) on data types are redundant/removed > from the language. And I'm not sure how it's possible to restrict that > parameter `a` (I know that it's possible to Java/C++/Perl6 (not sure), > some other languages but how to add such restriction in Haskell? IMHO > type families can help but I'm not sure how it will look (Sunny, Rainy > are "nullary" type, so...). > > Is it possible for Haskell too? > > === > Best regards, Paul > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From fa-ml at ariis.it Fri Sep 1 14:55:32 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Fri, 1 Sep 2017 16:55:32 +0200 Subject: [Haskell-beginners] Restrict type in phantom data-type In-Reply-To: <20170901171802.2819db2e@Pavel> References: <20170901171802.2819db2e@Pavel> Message-ID: <20170901145532.74p6tullydckofuy@x60s.casa> On Fri, Sep 01, 2017 at 05:18:02PM +0300, Baa wrote: > Hello, List! > > For example, I have specialized (right nameis phantom?) type: > > data Day a = Day { ... no `a` here } > data Sunny > data Rainy > > joyToday :: Day Sunny -> IO () > joyToday day = ... > > melancholyToday :: Day Rainy -> IO () > melancholyToday day = ... > > And I can create (in spite of that it's phantom) some day: > > let day1 = Day {...} :: Day Sunny > joyToday day1 Hello Paul, the usual way is create a module and export `smart` constructors: module MyType (rainy, Day, Sunny) -- *not* Day rainy :: Day Rainy rainy = undefined -- something here That way you can use Day for time signatures but *not* `Day` the constructor. Does this solve your problem? From fa-ml at ariis.it Fri Sep 1 14:57:58 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Fri, 1 Sep 2017 16:57:58 +0200 Subject: [Haskell-beginners] Restrict type in phantom data-type In-Reply-To: <20170901145532.74p6tullydckofuy@x60s.casa> References: <20170901171802.2819db2e@Pavel> <20170901145532.74p6tullydckofuy@x60s.casa> Message-ID: <20170901145758.6cyarxv6l6sl5gbw@x60s.casa> On Fri, Sep 01, 2017 at 04:55:32PM +0200, Francesco Ariis wrote: > module MyType (rainy, Day, Sunny) -- *not* Day I meant to write: -- not `Day(..)` From aquagnu at gmail.com Fri Sep 1 15:06:19 2017 From: aquagnu at gmail.com (Baa) Date: Fri, 1 Sep 2017 18:06:19 +0300 Subject: [Haskell-beginners] Restrict type in phantom data-type In-Reply-To: <20170901145758.6cyarxv6l6sl5gbw@x60s.casa> References: <20170901171802.2819db2e@Pavel> <20170901145532.74p6tullydckofuy@x60s.casa> <20170901145758.6cyarxv6l6sl5gbw@x60s.casa> Message-ID: <20170901180619.598c255c@Pavel> @Francesco: yes, it's a solution. But more interesting here is to make it on type level, like we do it in D, Java, etc where you can say: "class derived from...", "class before...", "class after...". > On Fri, Sep 01, 2017 at 04:55:32PM +0200, Francesco Ariis wrote: > > module MyType (rainy, Day, Sunny) -- *not* Day > > I meant to write: -- not `Day(..)` > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From aquagnu at gmail.com Fri Sep 1 15:23:27 2017 From: aquagnu at gmail.com (Baa) Date: Fri, 1 Sep 2017 18:23:27 +0300 Subject: [Haskell-beginners] Restrict type in phantom data-type Message-ID: <20170901182327.1d673162@Pavel> I pereputal emails. --- David, hello! 1. Is it the same/different as: data family Day a data Sunny data Rainy data instance Day Sunny = SunnyDay deriving Show data instance Day Rainy = RainyDay deriving Show ..and here you can not create `Day Int` object because no `Day Int` constructor (but you can create such constructor) ? Or in case with type families there is possibility to extend it to `Day Int` and in case with DayaKinds it's totally impossible? 2. I read somewhere (on forums) that restrictions on data types... I don't remember exactly, but something like they are not real restrictions or are related to old extension which is/will be deprecated. I'm not sure. Also, I'm not sure is it - in your example - restriction (constraint) or something else. Am I wrong? > This is maybe edging toward haskell-cafe territory, but you can > definitely do this in haskell. > > {-# LANGUAGE DataKinds, KindSignatures #-} > > data DayType = Sunny | Rainy > > data Day (a :: DayType) = Day > > > sunnyDay :: Day Sunny > sunnyDay = Day > > rainyDay :: Day Rainy > rainyDay = Day > > -- impossibleDay :: Day () > -- impossibleDay = Day > > On Fri, Sep 1, 2017 at 10:18 AM, Baa wrote: > > Hello, List! > > > > For example, I have specialized (right nameis phantom?) type: > > > > data Day a = Day { ... no `a` here } > > data Sunny > > data Rainy > > > > joyToday :: Day Sunny -> IO () > > joyToday day = ... > > > > melancholyToday :: Day Rainy -> IO () > > melancholyToday day = ... > > > > And I can create (in spite of that it's phantom) some day: > > > > let day1 = Day {...} :: Day Sunny > > joyToday day1 > > > > but no problem to create `Day Int`, `Day Char`, etc which is > > pointless actually (sure "creator"-function can be exported from the > > module only, but I'm talking about type-level solution). > > > > I know that constraints (`... =>`) on data types are > > redundant/removed from the language. And I'm not sure how it's > > possible to restrict that parameter `a` (I know that it's possible > > to Java/C++/Perl6 (not sure), some other languages but how to add > > such restriction in Haskell? IMHO type families can help but I'm > > not sure how it will look (Sunny, Rainy are "nullary" type, so...). > > > > Is it possible for Haskell too? > > > > === > > Best regards, Paul > > _______________________________________________ > > 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 toad3k at gmail.com Fri Sep 1 16:19:13 2017 From: toad3k at gmail.com (David McBride) Date: Fri, 1 Sep 2017 12:19:13 -0400 Subject: [Haskell-beginners] Restrict type in phantom data-type In-Reply-To: <20170901182327.1d673162@Pavel> References: <20170901182327.1d673162@Pavel> Message-ID: The terminology for what you are looking for was phantom type. That is any type that looks like this, where the a is not mentioned on the right hand side. data Foo a = Foo What happens with datakinds is when you write data SomeType = Foo | Bar By default there is a type SomeType and two values Foo and Bar, which are of kind *, which is the default. With datakinds enabled, it creates two new types 'Foo, and 'Bar, which have a kind SomeType (instead of *). You can replace Rainy with 'Rainy in the other code I gave. It compiles either way because there is no other type Rainy, so it assumes you must have meant 'Rainy. As for type families, what you have there are called open type families. There is also a closed type families variant that prevents more instances of the type family from being declared by the library user. It would look like this: data Sunny data Rainy type family Night a where Night Sunny = SunnyNight Night Rainy = RainyNight You could still write the following, which would not work in datakinds, but at least there is no constructor that you could use that would satisfy it other than the ones listed in the type family. impossibleDay2 :: Day () impossibleDay2 = undefined There may be more to this than I know, but I think that about covers it. On Fri, Sep 1, 2017 at 11:23 AM, Baa wrote: > I pereputal emails. > --- > > David, hello! > > 1. Is it the same/different as: > > data family Day a > data Sunny > data Rainy > data instance Day Sunny = SunnyDay deriving Show > data instance Day Rainy = RainyDay deriving Show > > ..and here you can not create `Day Int` object because no `Day Int` > constructor (but you can create such constructor) > > ? Or in case with type families there is possibility to extend it to > `Day Int` and in case with DayaKinds it's totally impossible? > > 2. I read somewhere (on forums) that restrictions on data types... I > don't remember exactly, but something like they are not real > restrictions or are related to old extension which is/will be > deprecated. I'm not sure. Also, I'm not sure is it - in your example - > restriction (constraint) or something else. Am I wrong? > >> This is maybe edging toward haskell-cafe territory, but you can >> definitely do this in haskell. >> >> {-# LANGUAGE DataKinds, KindSignatures #-} >> >> data DayType = Sunny | Rainy >> >> data Day (a :: DayType) = Day >> >> >> sunnyDay :: Day Sunny >> sunnyDay = Day >> >> rainyDay :: Day Rainy >> rainyDay = Day >> >> -- impossibleDay :: Day () >> -- impossibleDay = Day >> >> On Fri, Sep 1, 2017 at 10:18 AM, Baa wrote: >> > Hello, List! >> > >> > For example, I have specialized (right nameis phantom?) type: >> > >> > data Day a = Day { ... no `a` here } >> > data Sunny >> > data Rainy >> > >> > joyToday :: Day Sunny -> IO () >> > joyToday day = ... >> > >> > melancholyToday :: Day Rainy -> IO () >> > melancholyToday day = ... >> > >> > And I can create (in spite of that it's phantom) some day: >> > >> > let day1 = Day {...} :: Day Sunny >> > joyToday day1 >> > >> > but no problem to create `Day Int`, `Day Char`, etc which is >> > pointless actually (sure "creator"-function can be exported from the >> > module only, but I'm talking about type-level solution). >> > >> > I know that constraints (`... =>`) on data types are >> > redundant/removed from the language. And I'm not sure how it's >> > possible to restrict that parameter `a` (I know that it's possible >> > to Java/C++/Perl6 (not sure), some other languages but how to add >> > such restriction in Haskell? IMHO type families can help but I'm >> > not sure how it will look (Sunny, Rainy are "nullary" type, so...). >> > >> > Is it possible for Haskell too? >> > >> > === >> > Best regards, Paul >> > _______________________________________________ >> > 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 aquagnu at gmail.com Fri Sep 1 18:19:40 2017 From: aquagnu at gmail.com (baa dg) Date: Fri, 1 Sep 2017 21:19:40 +0300 Subject: [Haskell-beginners] Restrict type in phantom data-type In-Reply-To: References: <20170901182327.1d673162@Pavel> Message-ID: Thank you, David. It is a good seed, I'll read more about it, I used already GADTs and type families but I don't understand them so deep. By the way, yes, I got warning about tick and when I added it (s/Rainy/'Rainy/) it fixed warning :) 2017-09-01 19:19 GMT+03:00 David McBride : > The terminology for what you are looking for was phantom type. That > is any type that looks like this, where the a is not mentioned on the > right hand side. > > data Foo a = Foo > > What happens with datakinds is when you write > > data SomeType = Foo | Bar > > By default there is a type SomeType and two values Foo and Bar, which > are of kind *, which is the default. With datakinds enabled, it > creates two new types 'Foo, and 'Bar, which have a kind SomeType > (instead of *). You can replace Rainy with 'Rainy in the other code I > gave. It compiles either way because there is no other type Rainy, so > it assumes you must have meant 'Rainy. > > As for type families, what you have there are called open type > families. There is also a closed type families variant that prevents > more instances of the type family from being declared by the library > user. It would look like this: > > data Sunny > data Rainy > > type family Night a where > Night Sunny = SunnyNight > Night Rainy = RainyNight > > You could still write the following, which would not work in > datakinds, but at least there is no constructor that you could use > that would satisfy it other than the ones listed in the type family. > > impossibleDay2 :: Day () > impossibleDay2 = undefined > > There may be more to this than I know, but I think that about covers it. > > On Fri, Sep 1, 2017 at 11:23 AM, Baa wrote: > > I pereputal emails. > > --- > > > > David, hello! > > > > 1. Is it the same/different as: > > > > data family Day a > > data Sunny > > data Rainy > > data instance Day Sunny = SunnyDay deriving Show > > data instance Day Rainy = RainyDay deriving Show > > > > ..and here you can not create `Day Int` object because no `Day Int` > > constructor (but you can create such constructor) > > > > ? Or in case with type families there is possibility to extend it to > > `Day Int` and in case with DayaKinds it's totally impossible? > > > > 2. I read somewhere (on forums) that restrictions on data types... I > > don't remember exactly, but something like they are not real > > restrictions or are related to old extension which is/will be > > deprecated. I'm not sure. Also, I'm not sure is it - in your example - > > restriction (constraint) or something else. Am I wrong? > > > >> This is maybe edging toward haskell-cafe territory, but you can > >> definitely do this in haskell. > >> > >> {-# LANGUAGE DataKinds, KindSignatures #-} > >> > >> data DayType = Sunny | Rainy > >> > >> data Day (a :: DayType) = Day > >> > >> > >> sunnyDay :: Day Sunny > >> sunnyDay = Day > >> > >> rainyDay :: Day Rainy > >> rainyDay = Day > >> > >> -- impossibleDay :: Day () > >> -- impossibleDay = Day > >> > >> On Fri, Sep 1, 2017 at 10:18 AM, Baa wrote: > >> > Hello, List! > >> > > >> > For example, I have specialized (right nameis phantom?) type: > >> > > >> > data Day a = Day { ... no `a` here } > >> > data Sunny > >> > data Rainy > >> > > >> > joyToday :: Day Sunny -> IO () > >> > joyToday day = ... > >> > > >> > melancholyToday :: Day Rainy -> IO () > >> > melancholyToday day = ... > >> > > >> > And I can create (in spite of that it's phantom) some day: > >> > > >> > let day1 = Day {...} :: Day Sunny > >> > joyToday day1 > >> > > >> > but no problem to create `Day Int`, `Day Char`, etc which is > >> > pointless actually (sure "creator"-function can be exported from the > >> > module only, but I'm talking about type-level solution). > >> > > >> > I know that constraints (`... =>`) on data types are > >> > redundant/removed from the language. And I'm not sure how it's > >> > possible to restrict that parameter `a` (I know that it's possible > >> > to Java/C++/Perl6 (not sure), some other languages but how to add > >> > such restriction in Haskell? IMHO type families can help but I'm > >> > not sure how it will look (Sunny, Rainy are "nullary" type, so...). > >> > > >> > Is it possible for Haskell too? > >> > > >> > === > >> > Best regards, Paul > >> > _______________________________________________ > >> > 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 > _______________________________________________ > 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 Sep 3 08:22:59 2017 From: mike_k_houghton at yahoo.co.uk (mike h) Date: Sun, 3 Sep 2017 09:22:59 +0100 Subject: [Haskell-beginners] Square root algorithm Message-ID: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Hi, To help me in learning Haskell I started blogging about some of the things I’ve looked at. One such topic was calculating square roots ‘by hand’ and then deriving a Haskell algorithm. I wrote about the well known technique here http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ and it it is really quite a simple method. The second part of the post will be an implementation in Haskell. I then tried implementing it and got something that works but really its not very pleasant to look at! And its something I don’t want to post! Some parts are fine but I think I locked myself into the notion that it had to be using State and really the end result is pretty poor. I know this i perhaps a ‘big ask’ but I’d really appreciate any suggestions, solutions, hints etc. I will of course give full attribution. I’ve created a gist of the code here https://gist.github.com/banditpig Many Thanks Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From aquagnu at gmail.com Mon Sep 4 12:06:34 2017 From: aquagnu at gmail.com (Baa) Date: Mon, 4 Sep 2017 15:06:34 +0300 Subject: [Haskell-beginners] I have a -> f a. How to get m a -> f m a ? Message-ID: <20170904150634.230dd5ff@Pavel> Hello List! I have function a -> IO a. How to get function: Maybe a -> IO (Maybe a) ? I found in Haskell mails archive such thing: class IFunctor f where imap :: Idiom i => (s -> i t) -> f s -> i (f t) which looks similar, but I didn't find any helpfull instances of `IFunctor` class in its package (and unfortunately I don't know what are the indexed types: IMonad, IFunctor, etc). Sure, there is the primitive solution like: myfunc :: a -> IO a ... f x = case x of Nothing -> return Nothing Just x' -> Just <$> myfunc x' but more interesting is to know more standard and Haskelish solution (like lift's, etc). May be I miss something very obvious.. === Best regards, Paul From imantc at gmail.com Mon Sep 4 12:14:42 2017 From: imantc at gmail.com (Imants Cekusins) Date: Mon, 4 Sep 2017 15:14:42 +0300 Subject: [Haskell-beginners] I have a -> f a. How to get m a -> f m a ? In-Reply-To: <20170904150634.230dd5ff@Pavel> References: <20170904150634.230dd5ff@Pavel> Message-ID: > I have function a -> IO a. How to get function: > Maybe a -> IO (Maybe a) ? Will mapM work: http://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Traversable.html#v:mapM ? On 4 September 2017 at 15:06, Baa wrote: > Hello List! > > I have function a -> IO a. How to get function: > > Maybe a -> IO (Maybe a) ? > > I found in Haskell mails archive such thing: > > class IFunctor f where > imap :: Idiom i => (s -> i t) -> f s -> i (f t) > > which looks similar, but I didn't find any helpfull instances of > `IFunctor` class in its package (and unfortunately I don't know what are > the indexed types: IMonad, IFunctor, etc). Sure, there is the primitive > solution like: > > myfunc :: a -> IO a > ... > f x = case x of Nothing -> return Nothing > Just x' -> Just <$> myfunc x' > > but more interesting is to know more standard and Haskelish solution > (like lift's, etc). May be I miss something very obvious.. > > === > Best regards, Paul > _______________________________________________ > 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 aquagnu at gmail.com Mon Sep 4 12:36:42 2017 From: aquagnu at gmail.com (Baa) Date: Mon, 4 Sep 2017 15:36:42 +0300 Subject: [Haskell-beginners] I have a -> f a. How to get m a -> f m a ? In-Reply-To: References: <20170904150634.230dd5ff@Pavel> Message-ID: <20170904153642.7e839b91@Pavel> Hello, Imants! Exactly :) Thanks! > > I have function a -> IO a. How to get function: > > Maybe a -> IO (Maybe a) ? > > Will mapM work: > > http://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Traversable.html#v:mapM > > ? > > > > On 4 September 2017 at 15:06, Baa wrote: > > > Hello List! > > > > I have function a -> IO a. How to get function: > > > > Maybe a -> IO (Maybe a) ? > > > > I found in Haskell mails archive such thing: > > > > class IFunctor f where > > imap :: Idiom i => (s -> i t) -> f s -> i (f t) > > > > which looks similar, but I didn't find any helpfull instances of > > `IFunctor` class in its package (and unfortunately I don't know > > what are the indexed types: IMonad, IFunctor, etc). Sure, there is > > the primitive solution like: > > > > myfunc :: a -> IO a > > ... > > f x = case x of Nothing -> return Nothing > > Just x' -> Just <$> myfunc x' > > > > but more interesting is to know more standard and Haskelish solution > > (like lift's, etc). May be I miss something very obvious.. > > > > === > > Best regards, Paul > > _______________________________________________ > > Beginners mailing list > > Beginners at haskell.org > > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > From info at maximka.de Mon Sep 4 16:04:42 2017 From: info at maximka.de (info at maximka.de) Date: Mon, 4 Sep 2017 18:04:42 +0200 (CEST) Subject: [Haskell-beginners] get rid of IO in [IO XXX] Message-ID: <1953337571.1245148.1504541082396@communicator.strato.de> What is the way to transform a list of [IO XXX] type to [XXX]? Thanks, Alexei From mihai.maruseac at gmail.com Mon Sep 4 16:09:07 2017 From: mihai.maruseac at gmail.com (Mihai Maruseac) Date: Mon, 4 Sep 2017 09:09:07 -0700 Subject: [Haskell-beginners] get rid of IO in [IO XXX] In-Reply-To: <1953337571.1245148.1504541082396@communicator.strato.de> References: <1953337571.1245148.1504541082396@communicator.strato.de> Message-ID: Hi, Use sequence. It has type t (m a) -> m (t a) where m is a Monad (like IO) and t is a Traversable (like the list). Documentation: http://hackage.haskell.org/package/base-4.10.0.0/docs/Prelude.html#v:sequence I got to it using Hoogle: https://www.haskell.org/hoogle/?hoogle=%5BIO+a%5D+-%3E+IO+%5Ba%5D On Mon, Sep 4, 2017 at 9:04 AM, wrote: > What is the way to transform a list of [IO XXX] type to [XXX]? > > Thanks, > Alexei > _______________________________________________ > 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 i.caught.air at gmail.com Mon Sep 4 16:38:25 2017 From: i.caught.air at gmail.com (Alex Belanger) Date: Mon, 4 Sep 2017 12:38:25 -0400 Subject: [Haskell-beginners] get rid of IO in [IO XXX] In-Reply-To: <1953337571.1245148.1504541082396@communicator.strato.de> References: <1953337571.1245148.1504541082396@communicator.strato.de> Message-ID: You can turn `[IO a]` into `IO [a]` by traversing the Traversable and sequencing the actions using `sequence`. Note that what it creates is a slightly different IO computation that re-organizes the results, you'll still need to run that IO in the end. Typically, it's passed all the way down to your closest use of IO (often main for beginners) where you'll be able to finally get rid of it by performing the effects and doing something with the results. The flavor of choice depends on the situation but I find the IO monad very readable. main :: IO () main = do listOfA <- sequence ioListOfA -- Use listOfA from here Alex On Sep 4, 2017 12:05 PM, wrote: > What is the way to transform a list of [IO XXX] type to [XXX]? > > Thanks, > Alexei > _______________________________________________ > 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 jackbrandt11 at gmail.com Mon Sep 4 17:33:30 2017 From: jackbrandt11 at gmail.com (Jack Brandt) Date: Mon, 4 Sep 2017 12:33:30 -0500 Subject: [Haskell-beginners] Beginners Digest, Vol 111, Issue 4 In-Reply-To: References: Message-ID: Would a specialization of return work, as in f = return :: Maybe a -> IO (Maybe a)? On Mon, Sep 4, 2017 at 7: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. I have a -> f a. How to get m a -> f m a ? (Baa) > 2. Re: I have a -> f a. How to get m a -> f m a ? (Imants Cekusins) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 4 Sep 2017 15:06:34 +0300 > From: Baa > To: beginners at haskell.org > Subject: [Haskell-beginners] I have a -> f a. How to get m a -> f m a > ? > Message-ID: <20170904150634.230dd5ff at Pavel> > Content-Type: text/plain; charset=US-ASCII > > Hello List! > > I have function a -> IO a. How to get function: > > Maybe a -> IO (Maybe a) ? > > I found in Haskell mails archive such thing: > > class IFunctor f where > imap :: Idiom i => (s -> i t) -> f s -> i (f t) > > which looks similar, but I didn't find any helpfull instances of > `IFunctor` class in its package (and unfortunately I don't know what are > the indexed types: IMonad, IFunctor, etc). Sure, there is the primitive > solution like: > > myfunc :: a -> IO a > ... > f x = case x of Nothing -> return Nothing > Just x' -> Just <$> myfunc x' > > but more interesting is to know more standard and Haskelish solution > (like lift's, etc). May be I miss something very obvious.. > > === > Best regards, Paul > > > ------------------------------ > > Message: 2 > Date: Mon, 4 Sep 2017 15:14:42 +0300 > From: Imants Cekusins > To: The Haskell-Beginners Mailing List - Discussion of primarily > beginner-level topics related to Haskell > Subject: Re: [Haskell-beginners] I have a -> f a. How to get m a -> f > m a ? > Message-ID: > yhapZZtg at mail.gmail.com> > Content-Type: text/plain; charset="utf-8" > > > I have function a -> IO a. How to get function: > > Maybe a -> IO (Maybe a) ? > > Will mapM work: > > http://hackage.haskell.org/package/base-4.10.0.0/docs/ > Data-Traversable.html#v:mapM > > ? > > > > On 4 September 2017 at 15:06, Baa wrote: > > > Hello List! > > > > I have function a -> IO a. How to get function: > > > > Maybe a -> IO (Maybe a) ? > > > > I found in Haskell mails archive such thing: > > > > class IFunctor f where > > imap :: Idiom i => (s -> i t) -> f s -> i (f t) > > > > which looks similar, but I didn't find any helpfull instances of > > `IFunctor` class in its package (and unfortunately I don't know what are > > the indexed types: IMonad, IFunctor, etc). Sure, there is the primitive > > solution like: > > > > myfunc :: a -> IO a > > ... > > f x = case x of Nothing -> return Nothing > > Just x' -> Just <$> myfunc x' > > > > but more interesting is to know more standard and Haskelish solution > > (like lift's, etc). May be I miss something very obvious.. > > > > === > > Best regards, Paul > > _______________________________________________ > > Beginners mailing list > > Beginners at haskell.org > > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: attachments/20170904/f82f05da/attachment-0001.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 111, Issue 4 > ***************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zhiwudazhanjiangshi at gmail.com Fri Sep 8 22:40:09 2017 From: zhiwudazhanjiangshi at gmail.com (yi lu) Date: Sat, 9 Sep 2017 06:40:09 +0800 Subject: [Haskell-beginners] Square root algorithm In-Reply-To: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> References: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Message-ID: I don't know why this email was marked as spam, but it could be worth discussing. On Sun, Sep 3, 2017 at 4:22 PM, mike h wrote: > Hi, > > To help me in learning Haskell I started blogging about some of the things > I’ve looked at. > One such topic was calculating square roots ‘by hand’ and then deriving a > Haskell algorithm. > I wrote about the well known technique here > http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ > > and it it is really quite a simple method. > > The second part of the post will be an implementation in Haskell. > > I then tried implementing it and got something that works but really its > not very pleasant to look at! And its something I don’t want to post! Some > parts are fine but I think I locked myself into the notion that it had to > be using State and really the end result is pretty poor. > > I know this i perhaps a ‘big ask’ but I’d really appreciate any > suggestions, solutions, hints etc. I will of course give full attribution. > > I’ve created a gist of the code here > https://gist.github.com/banditpig > > Many Thanks > > Mike > > _______________________________________________ > 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 kc1956 at gmail.com Sat Sep 9 04:49:58 2017 From: kc1956 at gmail.com (KC) Date: Fri, 8 Sep 2017 21:49:58 -0700 Subject: [Haskell-beginners] Square root algorithm In-Reply-To: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> References: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Message-ID: One approach One function to compute the next iterate Another function to call the computation function until results are within some tolerance It's usually presented as separation of control and computation 😎 -- Sent from an expensive device which will be obsolete in a few months Casey On Sep 3, 2017 1:23 AM, "mike h" wrote: > Hi, > > To help me in learning Haskell I started blogging about some of the things > I’ve looked at. > One such topic was calculating square roots ‘by hand’ and then deriving a > Haskell algorithm. > I wrote about the well known technique here > http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ > > and it it is really quite a simple method. > > The second part of the post will be an implementation in Haskell. > > I then tried implementing it and got something that works but really its > not very pleasant to look at! And its something I don’t want to post! Some > parts are fine but I think I locked myself into the notion that it had to > be using State and really the end result is pretty poor. > > I know this i perhaps a ‘big ask’ but I’d really appreciate any > suggestions, solutions, hints etc. I will of course give full attribution. > > I’ve created a gist of the code here > https://gist.github.com/banditpig > > Many Thanks > > Mike > > _______________________________________________ > 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 Sat Sep 9 07:03:11 2017 From: mike_k_houghton at yahoo.co.uk (mike h) Date: Sat, 9 Sep 2017 08:03:11 +0100 Subject: [Haskell-beginners] Square root algorithm In-Reply-To: References: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Message-ID: Thanks I’ll look into that. To recap I have an unattractive but working implementation here https://gist.github.com/banditpig and the algorithm is described here http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ Thanks Mike > On 9 Sep 2017, at 05:49, KC wrote: > > One approach > > One function to compute the next iterate > > Another function to call the computation function until results are within some tolerance > > It's usually presented as separation of control and computation 😎 > > -- > Sent from an expensive device which will be obsolete in a few months > Casey > > On Sep 3, 2017 1:23 AM, "mike h" > wrote: > Hi, > > To help me in learning Haskell I started blogging about some of the things I’ve looked at. > One such topic was calculating square roots ‘by hand’ and then deriving a Haskell algorithm. > I wrote about the well known technique here > http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ > > and it it is really quite a simple method. > > The second part of the post will be an implementation in Haskell. > > I then tried implementing it and got something that works but really its not very pleasant to look at! And its something I don’t want to post! Some parts are fine but I think I locked myself into the notion that it had to be using State and really the end result is pretty poor. > > I know this i perhaps a ‘big ask’ but I’d really appreciate any suggestions, solutions, hints etc. I will of course give full attribution. > > I’ve created a gist of the code here > https://gist.github.com/banditpig > > Many Thanks > > Mike > > _______________________________________________ > 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 Sat Sep 9 07:44:57 2017 From: mike_k_houghton at yahoo.co.uk (mike h) Date: Sat, 9 Sep 2017 08:44:57 +0100 Subject: [Haskell-beginners] Square root algorithm In-Reply-To: References: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Message-ID: I’m sort of seeing this as a foldr over a list of digit pairs with the seed value of the fold being the first step of the algorithm (which is different from the other steps). The list of pairs will be of indeterminate length as ’00’ is used until the required number of digits in the result is achieved. A minor wrinkle with this is if the input number is a perfect square then a lot of ‘0’s would be in the result. Then, after the fold, apply some simple function to determine where the decimal point should go. M > On 9 Sep 2017, at 05:49, KC wrote: > > One approach > > One function to compute the next iterate > > Another function to call the computation function until results are within some tolerance > > It's usually presented as separation of control and computation 😎 > > -- > Sent from an expensive device which will be obsolete in a few months > Casey > > On Sep 3, 2017 1:23 AM, "mike h" > wrote: > Hi, > > To help me in learning Haskell I started blogging about some of the things I’ve looked at. > One such topic was calculating square roots ‘by hand’ and then deriving a Haskell algorithm. > I wrote about the well known technique here > http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ > > and it it is really quite a simple method. > > The second part of the post will be an implementation in Haskell. > > I then tried implementing it and got something that works but really its not very pleasant to look at! And its something I don’t want to post! Some parts are fine but I think I locked myself into the notion that it had to be using State and really the end result is pretty poor. > > I know this i perhaps a ‘big ask’ but I’d really appreciate any suggestions, solutions, hints etc. I will of course give full attribution. > > I’ve created a gist of the code here > https://gist.github.com/banditpig > > Many Thanks > > Mike > > _______________________________________________ > 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 patrick.browne at dit.ie Mon Sep 11 12:44:51 2017 From: patrick.browne at dit.ie (PATRICK BROWNE) Date: Mon, 11 Sep 2017 13:44:51 +0100 Subject: [Haskell-beginners] Square root algorithm In-Reply-To: References: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Message-ID: Why is it the sqrt0 function is so much slower than sqrt1. Does the where clause allow intermediate values to be stored? Regards, Pat sqrt0 :: Int -> Int sqrt0 0 = 0 sqrt0 1 = 1 sqrt0 n = ((sqrt0 (n - 1)) + (n `quot` sqrt0 (n-1))) `quot` 2 -- sqrt0 25 several minutes sqrt1 :: Int -> Int sqrt1 n | n == 0 = 0 | n == 1 = 1 | otherwise = div (k + ( div n k)) 2 where k = sqrt1(n-1) -- sqrt1 25 instant On 9 September 2017 at 05:49, KC wrote: > One approach > > One function to compute the next iterate > > Another function to call the computation function until results are within > some tolerance > > It's usually presented as separation of control and computation 😎 > > -- > Sent from an expensive device which will be obsolete in a few months > Casey > > On Sep 3, 2017 1:23 AM, "mike h" wrote: > >> Hi, >> >> To help me in learning Haskell I started blogging about some of the >> things I’ve looked at. >> One such topic was calculating square roots ‘by hand’ and then deriving a >> Haskell algorithm. >> I wrote about the well known technique here >> http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ >> >> and it it is really quite a simple method. >> >> The second part of the post will be an implementation in Haskell. >> >> I then tried implementing it and got something that works but really its >> not very pleasant to look at! And its something I don’t want to post! Some >> parts are fine but I think I locked myself into the notion that it had to >> be using State and really the end result is pretty poor. >> >> I know this i perhaps a ‘big ask’ but I’d really appreciate any >> suggestions, solutions, hints etc. I will of course give full attribution. >> >> I’ve created a gist of the code here >> https://gist.github.com/banditpig >> >> Many Thanks >> >> Mike >> >> _______________________________________________ >> 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 > > -- This email originated from DIT. If you received this email in error, please delete it from your system. Please note that if you are not the named addressee, disclosing, copying, distributing or taking any action based on the contents of this email or attachments is prohibited. www.dit.ie Is ó ITBÁC a tháinig an ríomhphost seo. Má fuair tú an ríomhphost seo trí earráid, scrios de do chóras é le do thoil. Tabhair ar aird, mura tú an seolaí ainmnithe, go bhfuil dianchosc ar aon nochtadh, aon chóipeáil, aon dáileadh nó ar aon ghníomh a dhéanfar bunaithe ar an ábhar atá sa ríomhphost nó sna hiatáin seo. www.dit.ie Tá ITBÁC ag aistriú go Gráinseach Ghormáin – DIT is on the move to Grangegorman -------------- next part -------------- An HTML attachment was scrubbed... URL: From mukeshtiwari.iiitm at gmail.com Tue Sep 12 00:36:58 2017 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Tue, 12 Sep 2017 10:36:58 +1000 Subject: [Haskell-beginners] Square root algorithm In-Reply-To: References: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Message-ID: Hi Patrick, On Mon, Sep 11, 2017 at 10:44 PM, PATRICK BROWNE wrote: > Why is it the sqrt0 function is so much slower than sqrt1. Does the where > clause allow intermediate values to be stored? > Regards, > Pat > sqrt0 :: Int -> Int > sqrt0 0 = 0 > sqrt0 1 = 1 > sqrt0 n = ((sqrt0 (n - 1)) + (n `quot` sqrt0 (n-1))) `quot` 2 > -- sqrt0 25 several minutes > In sqrt0, each function call with n > 1 creates two more function call, and this creates exponential blow up (factor of 2). You can make your code it faster by storing the intermediate result sqrt0 :: Int -> Int sqrt0 0 = 0 sqrt0 1 = 1 sqrt0 n = let k = sqrt0 (n - 1) in (k + (n `quot` k)) `quot` 2 This code is not blowing exponentially because of you storing intermediate result leading to faster computation. sqrt1 :: Int -> Int > sqrt1 n > | n == 0 = 0 > | n == 1 = 1 > | otherwise = div (k + ( div n k)) 2 > where k = sqrt1(n-1) > -- sqrt1 25 instant > > > On 9 September 2017 at 05:49, KC wrote: > >> One approach >> >> One function to compute the next iterate >> >> Another function to call the computation function until results are >> within some tolerance >> >> It's usually presented as separation of control and computation 😎 >> >> -- >> Sent from an expensive device which will be obsolete in a few months >> Casey >> >> On Sep 3, 2017 1:23 AM, "mike h" wrote: >> >>> Hi, >>> >>> To help me in learning Haskell I started blogging about some of the >>> things I’ve looked at. >>> One such topic was calculating square roots ‘by hand’ and then deriving >>> a Haskell algorithm. >>> I wrote about the well known technique here >>> http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ >>> >>> and it it is really quite a simple method. >>> >>> The second part of the post will be an implementation in Haskell. >>> >>> I then tried implementing it and got something that works but really >>> its not very pleasant to look at! And its something I don’t want to post! >>> Some parts are fine but I think I locked myself into the notion that it had >>> to be using State and really the end result is pretty poor. >>> >>> I know this i perhaps a ‘big ask’ but I’d really appreciate any >>> suggestions, solutions, hints etc. I will of course give full attribution. >>> >>> I’ve created a gist of the code here >>> https://gist.github.com/banditpig >>> >>> Many Thanks >>> >>> Mike >>> >>> _______________________________________________ >>> 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 >> >> > > This email originated from DIT. If you received this email in error, > please delete it from your system. Please note that if you are not the > named addressee, disclosing, copying, distributing or taking any action > based on the contents of this email or attachments is prohibited. > www.dit.ie > > Is ó ITBÁC a tháinig an ríomhphost seo. Má fuair tú an ríomhphost seo trí > earráid, scrios de do chóras é le do thoil. Tabhair ar aird, mura tú an > seolaí ainmnithe, go bhfuil dianchosc ar aon nochtadh, aon chóipeáil, aon > dáileadh nó ar aon ghníomh a dhéanfar bunaithe ar an ábhar atá sa > ríomhphost nó sna hiatáin seo. www.dit.ie > > Tá ITBÁC ag aistriú go Gráinseach Ghormáin – DIT is on the move to > Grangegorman > > _______________________________________________ > 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 aquagnu at gmail.com Tue Sep 12 08:06:55 2017 From: aquagnu at gmail.com (Baa) Date: Tue, 12 Sep 2017 11:06:55 +0300 Subject: [Haskell-beginners] HSpec output option Message-ID: <20170912110655.1cea1a86@Pavel> Hello, Dear List! I have tests: I'm using HSpec (and QuickCheck too). And I have tests like this: describe "Something" $ do it "something is correct" $ do ...blah-blah... it "any string is correct" $ property $ \s -> all (=='*') (Something s) -- it's for example only!!! so something like unit-test and property checks in one SomethingSpec.hs. I'm running them with this Makefile: .PHONY: test fast-test fast-test: stack exec runhaskell -- -isrc -itest test/Spec.hs test: stack test and in Spec.hs I have: {-# OPTIONS_GHC -F -pgmF hspec-discover #-} That's all. So, when I find failed test, I get a trace like this: ... Failures: test/SomethingSpec.hs:172: 1) BlahBlah.superFunc any string is correct: result Gave up after 48 tests ...etc... So, my question is: when QuichCheck runs my property test, it passes argument to property's lambda. And on 48th test attempt with some concreate argument value my check fails. How can I get detailed output from such test environment, to see what concreate arguments lead to failure? To see something (or similar/or more detailed even): Failed with arguments: s = "" Is it possible (I run them with stack and with runhaskell too) ? === Best regards, Paul From patrick.browne at dit.ie Tue Sep 12 09:21:48 2017 From: patrick.browne at dit.ie (PATRICK BROWNE) Date: Tue, 12 Sep 2017 10:21:48 +0100 Subject: [Haskell-beginners] Square root algorithm In-Reply-To: References: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Message-ID: Mukesh, Thanks for your reply. Does the mean that my original sqrt0 makes (2^25=33554432) function calls? How many function calls does the let/where versions make? Thanks, Pat On 12 September 2017 at 01:36, mukesh tiwari wrote: > Hi Patrick, > > On Mon, Sep 11, 2017 at 10:44 PM, PATRICK BROWNE > wrote: > >> Why is it the sqrt0 function is so much slower than sqrt1. Does the where >> clause allow intermediate values to be stored? >> Regards, >> Pat >> sqrt0 :: Int -> Int >> sqrt0 0 = 0 >> sqrt0 1 = 1 >> sqrt0 n = ((sqrt0 (n - 1)) + (n `quot` sqrt0 (n-1))) `quot` 2 >> -- sqrt0 25 several minutes >> > > In sqrt0, each function call with n > 1 creates two more function call, > and this creates exponential blow up (factor of 2). You can make your code > it faster by storing the intermediate result > > sqrt0 :: Int -> Int > sqrt0 0 = 0 > sqrt0 1 = 1 > sqrt0 n = let k = sqrt0 (n - 1) in (k + (n `quot` k)) `quot` 2 > > This code is not blowing exponentially because of you storing intermediate > result leading to faster computation. > > sqrt1 :: Int -> Int >> sqrt1 n >> | n == 0 = 0 >> | n == 1 = 1 >> | otherwise = div (k + ( div n k)) 2 >> where k = sqrt1(n-1) >> -- sqrt1 25 instant >> >> >> On 9 September 2017 at 05:49, KC wrote: >> >>> One approach >>> >>> One function to compute the next iterate >>> >>> Another function to call the computation function until results are >>> within some tolerance >>> >>> It's usually presented as separation of control and computation 😎 >>> >>> -- >>> Sent from an expensive device which will be obsolete in a few months >>> Casey >>> >>> On Sep 3, 2017 1:23 AM, "mike h" wrote: >>> >>>> Hi, >>>> >>>> To help me in learning Haskell I started blogging about some of the >>>> things I’ve looked at. >>>> One such topic was calculating square roots ‘by hand’ and then deriving >>>> a Haskell algorithm. >>>> I wrote about the well known technique here >>>> http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ >>>> >>>> and it it is really quite a simple method. >>>> >>>> The second part of the post will be an implementation in Haskell. >>>> >>>> I then tried implementing it and got something that works but really >>>> its not very pleasant to look at! And its something I don’t want to post! >>>> Some parts are fine but I think I locked myself into the notion that it had >>>> to be using State and really the end result is pretty poor. >>>> >>>> I know this i perhaps a ‘big ask’ but I’d really appreciate any >>>> suggestions, solutions, hints etc. I will of course give full attribution. >>>> >>>> I’ve created a gist of the code here >>>> https://gist.github.com/banditpig >>>> >>>> Many Thanks >>>> >>>> Mike >>>> >>>> _______________________________________________ >>>> 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 >>> >>> >> >> This email originated from DIT. If you received this email in error, >> please delete it from your system. Please note that if you are not the >> named addressee, disclosing, copying, distributing or taking any action >> based on the contents of this email or attachments is prohibited. >> www.dit.ie >> >> Is ó ITBÁC a tháinig an ríomhphost seo. Má fuair tú an ríomhphost seo trí >> earráid, scrios de do chóras é le do thoil. Tabhair ar aird, mura tú an >> seolaí ainmnithe, go bhfuil dianchosc ar aon nochtadh, aon chóipeáil, aon >> dáileadh nó ar aon ghníomh a dhéanfar bunaithe ar an ábhar atá sa >> ríomhphost nó sna hiatáin seo. www.dit.ie >> >> Tá ITBÁC ag aistriú go Gráinseach Ghormáin – DIT is on the move to >> Grangegorman >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > -- This email originated from DIT. If you received this email in error, please delete it from your system. Please note that if you are not the named addressee, disclosing, copying, distributing or taking any action based on the contents of this email or attachments is prohibited. www.dit.ie Is ó ITBÁC a tháinig an ríomhphost seo. Má fuair tú an ríomhphost seo trí earráid, scrios de do chóras é le do thoil. Tabhair ar aird, mura tú an seolaí ainmnithe, go bhfuil dianchosc ar aon nochtadh, aon chóipeáil, aon dáileadh nó ar aon ghníomh a dhéanfar bunaithe ar an ábhar atá sa ríomhphost nó sna hiatáin seo. www.dit.ie Tá ITBÁC ag aistriú go Gráinseach Ghormáin – DIT is on the move to Grangegorman -------------- next part -------------- An HTML attachment was scrubbed... URL: From mukeshtiwari.iiitm at gmail.com Wed Sep 13 01:37:32 2017 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Wed, 13 Sep 2017 11:37:32 +1000 Subject: [Haskell-beginners] Square root algorithm In-Reply-To: References: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Message-ID: Hi Patrick, On Tue, Sep 12, 2017 at 7:21 PM, PATRICK BROWNE wrote: > Mukesh, > Thanks for your reply. > Does the mean that my original sqrt0 makes (2^25=33554432) function calls? > Technically Yes, and more accurately for any given number n, you have 2 ^ (n - 1) call because your base case is 1. > How many function calls does the let/where versions make? > With let/where version you store the value of function call in in variable, so no more second call and total functional in this scenario is linear in number n. For you case with n = 25 the number of function calls is just 24. Best, Mukesh Tiwari > Thanks, > Pat > > On 12 September 2017 at 01:36, mukesh tiwari > wrote: > >> Hi Patrick, >> >> On Mon, Sep 11, 2017 at 10:44 PM, PATRICK BROWNE >> wrote: >> >>> Why is it the sqrt0 function is so much slower than sqrt1. Does the >>> where clause allow intermediate values to be stored? >>> Regards, >>> Pat >>> sqrt0 :: Int -> Int >>> sqrt0 0 = 0 >>> sqrt0 1 = 1 >>> sqrt0 n = ((sqrt0 (n - 1)) + (n `quot` sqrt0 (n-1))) `quot` 2 >>> -- sqrt0 25 several minutes >>> >> >> In sqrt0, each function call with n > 1 creates two more function call, >> and this creates exponential blow up (factor of 2). You can make your code >> it faster by storing the intermediate result >> >> sqrt0 :: Int -> Int >> sqrt0 0 = 0 >> sqrt0 1 = 1 >> sqrt0 n = let k = sqrt0 (n - 1) in (k + (n `quot` k)) `quot` 2 >> >> This code is not blowing exponentially because of you storing >> intermediate result leading to faster computation. >> >> sqrt1 :: Int -> Int >>> sqrt1 n >>> | n == 0 = 0 >>> | n == 1 = 1 >>> | otherwise = div (k + ( div n k)) 2 >>> where k = sqrt1(n-1) >>> -- sqrt1 25 instant >>> >>> >>> On 9 September 2017 at 05:49, KC wrote: >>> >>>> One approach >>>> >>>> One function to compute the next iterate >>>> >>>> Another function to call the computation function until results are >>>> within some tolerance >>>> >>>> It's usually presented as separation of control and computation 😎 >>>> >>>> -- >>>> Sent from an expensive device which will be obsolete in a few months >>>> Casey >>>> >>>> On Sep 3, 2017 1:23 AM, "mike h" wrote: >>>> >>>>> Hi, >>>>> >>>>> To help me in learning Haskell I started blogging about some of the >>>>> things I’ve looked at. >>>>> One such topic was calculating square roots ‘by hand’ and then >>>>> deriving a Haskell algorithm. >>>>> I wrote about the well known technique here >>>>> http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ >>>>> >>>>> and it it is really quite a simple method. >>>>> >>>>> The second part of the post will be an implementation in Haskell. >>>>> >>>>> I then tried implementing it and got something that works but really >>>>> its not very pleasant to look at! And its something I don’t want to post! >>>>> Some parts are fine but I think I locked myself into the notion that it had >>>>> to be using State and really the end result is pretty poor. >>>>> >>>>> I know this i perhaps a ‘big ask’ but I’d really appreciate any >>>>> suggestions, solutions, hints etc. I will of course give full attribution. >>>>> >>>>> I’ve created a gist of the code here >>>>> https://gist.github.com/banditpig >>>>> >>>>> Many Thanks >>>>> >>>>> Mike >>>>> >>>>> _______________________________________________ >>>>> 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 >>>> >>>> >>> >>> This email originated from DIT. If you received this email in error, >>> please delete it from your system. Please note that if you are not the >>> named addressee, disclosing, copying, distributing or taking any action >>> based on the contents of this email or attachments is prohibited. >>> www.dit.ie >>> >>> Is ó ITBÁC a tháinig an ríomhphost seo. Má fuair tú an ríomhphost seo >>> trí earráid, scrios de do chóras é le do thoil. Tabhair ar aird, mura tú an >>> seolaí ainmnithe, go bhfuil dianchosc ar aon nochtadh, aon chóipeáil, aon >>> dáileadh nó ar aon ghníomh a dhéanfar bunaithe ar an ábhar atá sa >>> ríomhphost nó sna hiatáin seo. www.dit.ie >>> >>> Tá ITBÁC ag aistriú go Gráinseach Ghormáin – DIT is on the move to >>> Grangegorman >>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >>> >> > > This email originated from DIT. If you received this email in error, > please delete it from your system. Please note that if you are not the > named addressee, disclosing, copying, distributing or taking any action > based on the contents of this email or attachments is prohibited. > www.dit.ie > > Is ó ITBÁC a tháinig an ríomhphost seo. Má fuair tú an ríomhphost seo trí > earráid, scrios de do chóras é le do thoil. Tabhair ar aird, mura tú an > seolaí ainmnithe, go bhfuil dianchosc ar aon nochtadh, aon chóipeáil, aon > dáileadh nó ar aon ghníomh a dhéanfar bunaithe ar an ábhar atá sa > ríomhphost nó sna hiatáin seo. www.dit.ie > > Tá ITBÁC ag aistriú go Gráinseach Ghormáin – DIT is on the move to > Grangegorman > -------------- next part -------------- An HTML attachment was scrubbed... URL: From aquagnu at gmail.com Wed Sep 13 08:22:55 2017 From: aquagnu at gmail.com (Baa) Date: Wed, 13 Sep 2017 11:22:55 +0300 Subject: [Haskell-beginners] HSpec output option In-Reply-To: <20170912110655.1cea1a86@Pavel> References: <20170912110655.1cea1a86@Pavel> Message-ID: <20170913112255.4f981309@Pavel> I will answer myself, because it is possible that someone will need this answer. Reason of the problem was with one "test operator" only: `==>` - it's something like imlication but has one difference. I implemented own (standard) implication as: (-->) :: Bool -> Bool -> Bool True --> True = True True --> False = False False --> True = True False --> False = True infixr 0 --> and use it instead of `==>`. And with this operator (used in QuickCheck properties testing) I get output of case's values which leads to fail in my tests. So, test looks like: ... describe "Some func test" $ do prop "negative input becomes positive" $ do \n -> n < 0 --> someFunc n >= 0 ... To see all QuickCheck generated values, I can use alternative (verbose) `property` and `prop` funcs: verbproperty :: Testable prop => prop -> Expectation verbproperty p = verboseCheckResult p >>= (`shouldBe` True) . isSuccess verbprop :: (HasCallStack, Testable prop) => String -> prop -> Spec verbprop s = it s . vproperty All is for HSpec tests (with QuickCheck properties)... === Best regards, Paul > Hello, Dear List! > > I have tests: I'm using HSpec (and QuickCheck too). And I have tests > like this: > > describe "Something" $ do > it "something is correct" $ do > ...blah-blah... > it "any string is correct" $ property $ > \s -> all (=='*') (Something s) -- it's for example only!!! > > so something like unit-test and property checks in one > SomethingSpec.hs. > > I'm running them with this Makefile: > > .PHONY: test fast-test > > fast-test: > stack exec runhaskell -- -isrc -itest test/Spec.hs > > test: > stack test > > and in Spec.hs I have: > > {-# OPTIONS_GHC -F -pgmF hspec-discover #-} > > That's all. So, when I find failed test, I get a trace like this: > > ... > Failures: > > test/SomethingSpec.hs:172: > 1) BlahBlah.superFunc any string is correct: > result Gave up after 48 tests > ...etc... > > So, my question is: when QuichCheck runs my property test, it passes > argument to property's lambda. And on 48th test attempt with some > concreate argument value my check fails. How can I get detailed output > from such test environment, to see what concreate arguments lead to > failure? To see something (or similar/or more detailed even): > > Failed with arguments: s = "" > > Is it possible (I run them with stack and with runhaskell too) ? > > === > Best regards, Paul From anwar.ludin at gmail.com Thu Sep 14 04:04:26 2017 From: anwar.ludin at gmail.com (Anwar Ludin) Date: Thu, 14 Sep 2017 06:04:26 +0200 Subject: [Haskell-beginners] understanding type constructors and value constructors Message-ID: Hello everyone, I have just started studying Haskell and I am having a hard time understanding type and value constructors. So to create a new type, you write something like: data FinancialInstrument = Financial String Double deriving (Eq, Show) and then you can write: ibm = Financial "ibm" 150 OK all good. This initializes a FinancialInstrument. What I don't quite grasp is what is the purpose of Financial (the data/value constructor)? And from what I have read, you could have also written: data FinancialInstrument = FinancialInstrument String Double deriving (Eq, Show) To me the second expression is a lot closer to the typical OOP way of doing things (where the type name and constructor(s) have the same name). Why would someone prefer the first notation? Once a value has been constructed, how can I access its fields? Is there a way to create values using named parameters? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.caught.air at gmail.com Thu Sep 14 04:56:59 2017 From: i.caught.air at gmail.com (Alex Belanger) Date: Thu, 14 Sep 2017 00:56:59 -0400 Subject: [Haskell-beginners] understanding type constructors and value constructors In-Reply-To: References: Message-ID: I'm on my phone which makes replying painful, but consider: data Weekday = Monday | Tuesday | Wednesday | Thursday | Friday data Shape = Circle Int | Rectangle Int Int Int Int | Triangle Int Int data Either a b = Left a | Right b Cheers, Alex On Sep 14, 2017 12:05 AM, "Anwar Ludin" wrote: > Hello everyone, > > I have just started studying Haskell and I am having a hard time > understanding type and value constructors. > > So to create a new type, you write something like: > > data FinancialInstrument = Financial String Double > deriving (Eq, Show) > > and then you can write: > > ibm = Financial "ibm" 150 > > OK all good. This initializes a FinancialInstrument. What I don't quite > grasp is what is the purpose of Financial (the data/value constructor)? And > from what I have read, you could have also written: > > data FinancialInstrument = FinancialInstrument String Double > deriving (Eq, Show) > > To me the second expression is a lot closer to the typical OOP way of > doing things (where the type name and constructor(s) have the same name). > Why would someone prefer the first notation? > > Once a value has been constructed, how can I access its fields? > > Is there a way to create values using named parameters? > > Thanks! > > _______________________________________________ > 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 imantc at gmail.com Thu Sep 14 05:18:07 2017 From: imantc at gmail.com (Imants Cekusins) Date: Thu, 14 Sep 2017 08:18:07 +0300 Subject: [Haskell-beginners] understanding type constructors and value constructors In-Reply-To: References: Message-ID: This chapter details it: http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html More questions are welcome, of course. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anwar.ludin at gmail.com Thu Sep 14 07:19:24 2017 From: anwar.ludin at gmail.com (Anwar Ludin) Date: Thu, 14 Sep 2017 07:19:24 +0000 Subject: [Haskell-beginners] understanding type constructors and value constructors In-Reply-To: References: Message-ID: An HTML attachment was scrubbed... URL: From aquagnu at gmail.com Fri Sep 15 09:40:46 2017 From: aquagnu at gmail.com (Baa) Date: Fri, 15 Sep 2017 12:40:46 +0300 Subject: [Haskell-beginners] "Phantom" function? Message-ID: <20170915124046.286a8049@Pavel> Hello, List. I'm trying to write function like this: type VerifyJson a = IO Bool isRight :: FromJSON a => FilePath -> VerifyJson a isRight testbed = do js <- readFile testbed return $ isJust (decode js) <<<<< ERROR IS HERE ! So I get error: 60 23 error error: • Could not deduce (FromJSON a0) arising from a use of ‘decode’ from the context: FromJSON a bound by the type signature for: isRight :: FromJSON a => FilePath -> VerifyJson a at /home/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/.stack-work/intero/intero7476qP4.hs:57:1-46 The type variable ‘a0’ is ambiguous These potential instances exist: instance FromJSON DotNetTime -- Defined in ‘aeson-1.0.2.1:Data.Aeson.Types.FromJSON’ instance FromJSON Value -- Defined in ‘aeson-1.0.2.1:Data.Aeson.Types.FromJSON’ instance (FromJSON a, FromJSON b) => FromJSON (Either a b) -- Defined in ‘aeson-1.0.2.1:Data.Aeson.Types.FromJSON’ ...plus 25 others ...plus 52 instances involving out-of-scope types (use -fprint-potential-instances to see them all) • In the first argument of ‘MB.isJust’, namely ‘(decode js)’ In the second argument of ‘($)’, namely ‘MB.isJust (decode js)’ In a stmt of a 'do' block: return $ MB.isJust (decode js) (intero) Is it possible to write such (phantom?;)) function? Sure, I can make workaround like: class FromJSON a => VerifyJson a where isRight :: FilePath -> IO Bool isRight testbed = do js <- readFile testbed return $ MB.isJust (decode js::Maybe a) but in this case I must declare instances for all verificating types (right?), like: instance VerifyJson MyType But idea was to minimize `isRight` users code... === Best regards, Paul From aquagnu at gmail.com Fri Sep 15 09:53:46 2017 From: aquagnu at gmail.com (Baa) Date: Fri, 15 Sep 2017 12:53:46 +0300 Subject: [Haskell-beginners] "Phantom" function? In-Reply-To: <20170915124046.286a8049@Pavel> References: <20170915124046.286a8049@Pavel> Message-ID: <20170915125346.212bffc6@Pavel> Seems that this works: {-# LANGUAGE ExistentialQuantification #-} ... type VerifyJson a = IO Bool isRight :: forall a. FromJSON a => FilePath -> VerifyJson a isRight testbed = do js <- readFile testbed return $ MB.isJust (decode js::Maybe a) but what is the difference?!? > Hello, List. I'm trying to write function like this: > > type VerifyJson a = IO Bool > > isRight :: FromJSON a => FilePath -> VerifyJson a > isRight testbed = do > js <- readFile testbed > return $ isJust (decode js) <<<<< ERROR IS HERE ! > > So I get error: > > 60 23 error error: > • Could not deduce (FromJSON a0) arising from a use of ‘decode’ > from the context: FromJSON a > bound by the type signature for: > isRight :: FromJSON a => FilePath -> VerifyJson a > at /home/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/.stack-work/intero/intero7476qP4.hs:57:1-46 > The type variable ‘a0’ is ambiguous > These potential instances exist: > instance FromJSON DotNetTime > -- Defined in ‘aeson-1.0.2.1:Data.Aeson.Types.FromJSON’ > instance FromJSON Value > -- Defined in ‘aeson-1.0.2.1:Data.Aeson.Types.FromJSON’ > instance (FromJSON a, FromJSON b) => FromJSON (Either a b) > -- Defined in ‘aeson-1.0.2.1:Data.Aeson.Types.FromJSON’ > ...plus 25 others > ...plus 52 instances involving out-of-scope types > (use -fprint-potential-instances to see them all) > • In the first argument of ‘MB.isJust’, namely ‘(decode js)’ > In the second argument of ‘($)’, namely ‘MB.isJust (decode js)’ > In a stmt of a 'do' block: return $ MB.isJust (decode js) > (intero) > > Is it possible to write such (phantom?;)) function? Sure, I can make > workaround like: > > class FromJSON a => VerifyJson a where > isRight :: FilePath -> IO Bool > isRight testbed = do > js <- readFile testbed > return $ MB.isJust (decode js::Maybe a) > > but in this case I must declare instances for all verificating types > (right?), like: > > instance VerifyJson MyType > > But idea was to minimize `isRight` users code... > > === > Best regards, Paul > From aquagnu at gmail.com Fri Sep 15 10:05:52 2017 From: aquagnu at gmail.com (Baa) Date: Fri, 15 Sep 2017 13:05:52 +0300 Subject: [Haskell-beginners] "Phantom" function? In-Reply-To: <20170915125346.212bffc6@Pavel> References: <20170915124046.286a8049@Pavel> <20170915125346.212bffc6@Pavel> Message-ID: <20170915130552.391143f6@Pavel> unfortunately call of new version: .. (isRight "data/a.json" :: VerifyJson RESTResp) `shouldReturn` True .. leads to new errors: • Ambiguous type variable ‘a0’ arising from a use of ‘isRight’ prevents the constraint ‘(aeson-1.0.2.1:Data.Aeson.Types.FromJSON.FromJSON a0)’ from being solved. Probable fix: use a type annotation to specify what ‘a0’ should be. These potential instances exist: ..... • In the first argument of ‘shouldReturn’, namely ‘(isRight "data/a.json" :: VerifyJson RESTResp)’ In a stmt of a 'do' block: (isRight "data/a.json" :: VerifyJson RESTResp) `shouldReturn` True In the second argument of ‘($)’, namely ‘do { (isRight "data/a.json" :: VerifyJson RESTResp) `shouldReturn` True }’ I will be grateful for any help. === Best regards, Paul > Seems that this works: > > {-# LANGUAGE ExistentialQuantification #-} > ... > > type VerifyJson a = IO Bool > > isRight :: forall a. FromJSON a => FilePath -> VerifyJson a > isRight testbed = do > js <- readFile testbed > return $ MB.isJust (decode js::Maybe a) > > but what is the difference?!? > > > > Hello, List. I'm trying to write function like this: > > > > type VerifyJson a = IO Bool > > > > isRight :: FromJSON a => FilePath -> VerifyJson a > > isRight testbed = do > > js <- readFile testbed > > return $ isJust (decode js) <<<<< ERROR IS HERE ! > > > > So I get error: > > > > 60 23 error error: > > • Could not deduce (FromJSON a0) arising from a use of ‘decode’ > > from the context: FromJSON a > > bound by the type signature for: > > isRight :: FromJSON a => FilePath -> VerifyJson > > a > > at /home/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/.stack-work/intero/intero7476qP4.hs:57:1-46 > > The type variable ‘a0’ is ambiguous These potential instances exist: > > instance FromJSON DotNetTime > > -- Defined in ‘aeson-1.0.2.1:Data.Aeson.Types.FromJSON’ > > instance FromJSON Value > > -- Defined in ‘aeson-1.0.2.1:Data.Aeson.Types.FromJSON’ > > instance (FromJSON a, FromJSON b) => FromJSON (Either a b) > > -- Defined in ‘aeson-1.0.2.1:Data.Aeson.Types.FromJSON’ > > ...plus 25 others > > ...plus 52 instances involving out-of-scope types > > (use -fprint-potential-instances to see them all) > > • In the first argument of ‘MB.isJust’, namely ‘(decode js)’ > > In the second argument of ‘($)’, namely ‘MB.isJust (decode > > js)’ In a stmt of a 'do' block: return $ MB.isJust (decode js) > > (intero) > > > > Is it possible to write such (phantom?;)) function? Sure, I can make > > workaround like: > > > > class FromJSON a => VerifyJson a where > > isRight :: FilePath -> IO Bool > > isRight testbed = do > > js <- readFile testbed > > return $ MB.isJust (decode js::Maybe a) > > > > but in this case I must declare instances for all verificating types > > (right?), like: > > > > instance VerifyJson MyType > > > > But idea was to minimize `isRight` users code... > > > > === > > Best regards, Paul > > > From mike_k_houghton at yahoo.co.uk Fri Sep 15 15:49:10 2017 From: mike_k_houghton at yahoo.co.uk (mike h) Date: Fri, 15 Sep 2017 16:49:10 +0100 Subject: [Haskell-beginners] Square root algorithm In-Reply-To: References: <79F5B2AD-59ED-47AD-A531-90CC3CE83E59@yahoo.co.uk> Message-ID: <70509FEE-22EB-40F2-BDB7-CEE4FEBF642B@yahoo.co.uk> On the original ‘using pairs’ algorithm I’ve now coded something slightly cleaner than the original State based one. There’s still a lot of code for a seemingly simple problem but I s’pose a lot of the functions are helpers for various things and the core of the solution is contained in the fold. An easier to read copy of the code is at http://gitcommit.co.uk/2017/09/15/the-root-of-the-problem-part-2/ and the raw code is below. Thanks Mike ——————— import Data.List.Split import Data.Char import Numeric -- The entry point. root :: Float -> Float root n = f where ((f, _):_) = readFloat (lhs ++ "." ++ rhs) (_, rootDigits) = rootFold n (lhs, rhs) = splitAt (dpLocation n) rootDigits -- -- fold with the initial value based on intSquareRoot function -- and subsequent calculations based on doubling and the biggestN function. rootFold :: Float -> (Integer, String) rootFold n = foldr calculate (makeStartVal p1 p2) pairs where (p1:p2:pairs) = digitList n makeStartVal :: Integer -> Integer -> (Integer, String) makeStartVal p1 p2 = res where rt = intSquareRoot p1 res = (p2 + (p1 - rt * rt) * 100 , show rt) calculate :: Integer -> (Integer, String) -> (Integer, String) calculate p (n, res) = next where (toAppend, remain) = biggestN (2 * read res) n -- bring down the next pair and accumulate the result next = (remain * 100 + p, res ++ show toAppend) -- Where should decimal point be? dpLocation :: Float -> Int dpLocation n = if (even len) then len `div` 2 else (len + 1) `div` 2 where [left, _] = splitOn "." . show $ n len = length left -- helper for formatting formatFloatN numOfDecimals floatNum = showFFloat (Just numOfDecimals) floatNum "" showFlt = formatFloatN 16 -- Takes float and makes list of 'paired' integers digitList :: Float -> [Integer] digitList n = res where [l, r] = splitOn "." . showFlt $ n res = map read $ (pairs . pad $ l) ++ (pairs . pad $ r) where pairs [] = [] pairs xs = let (ys, zs) = splitAt 2 xs in ys : pairs zs pad xs | odd . length $ xs = "0" ++ xs | otherwise = xs -- eg largest number N such that 4N x N <= 161 -- and biggestN 4 161 = (3, 32) -- biggestN :: Integer -> Integer -> (Integer, Integer) biggestN = get 0 where get n x y | (x*10 + n) * n > y = (n-1, y - (x*10 + n - 1)*(n - 1)) | (x*10 + n) * n == y = (n , y - (x*10 + n) * n ) | otherwise = get (n + 1) x y -- gives the largest int whose square is <= n intSquareRoot :: Integer -> Integer intSquareRoot n = root 0 where root i | i*i <= n = root (i + 1) | otherwise = i - 1 ——————— > On 13 Sep 2017, at 02:37, mukesh tiwari wrote: > > Hi Patrick, > > On Tue, Sep 12, 2017 at 7:21 PM, PATRICK BROWNE > wrote: > Mukesh, > Thanks for your reply. > Does the mean that my original sqrt0 makes (2^25=33554432) function calls? > > Technically Yes, and more accurately for any given number n, you have 2 ^ (n - 1) call because your base case is 1. > > How many function calls does the let/where versions make? > > With let/where version you store the value of function call in in variable, so no more second call and total functional in this scenario is linear in number n. For you case with n = 25 the number of function calls is just 24. > > Best, > Mukesh Tiwari > > Thanks, > Pat > > On 12 September 2017 at 01:36, mukesh tiwari > wrote: > Hi Patrick, > > On Mon, Sep 11, 2017 at 10:44 PM, PATRICK BROWNE > wrote: > Why is it the sqrt0 function is so much slower than sqrt1. Does the where clause allow intermediate values to be stored? > Regards, > Pat > sqrt0 :: Int -> Int > sqrt0 0 = 0 > sqrt0 1 = 1 > sqrt0 n = ((sqrt0 (n - 1)) + (n `quot` sqrt0 (n-1))) `quot` 2 > -- sqrt0 25 several minutes > > In sqrt0, each function call with n > 1 creates two more function call, and this creates exponential blow up (factor of 2). You can make your code it faster by storing the intermediate result > > sqrt0 :: Int -> Int > sqrt0 0 = 0 > sqrt0 1 = 1 > sqrt0 n = let k = sqrt0 (n - 1) in (k + (n `quot` k)) `quot` 2 > > This code is not blowing exponentially because of you storing intermediate result leading to faster computation. > > sqrt1 :: Int -> Int > sqrt1 n > | n == 0 = 0 > | n == 1 = 1 > | otherwise = div (k + ( div n k)) 2 > where k = sqrt1(n-1) > -- sqrt1 25 instant > > > On 9 September 2017 at 05:49, KC > wrote: > One approach > > One function to compute the next iterate > > Another function to call the computation function until results are within some tolerance > > It's usually presented as separation of control and computation 😎 > > -- > Sent from an expensive device which will be obsolete in a few months > Casey > > On Sep 3, 2017 1:23 AM, "mike h" > wrote: > Hi, > > To help me in learning Haskell I started blogging about some of the things I’ve looked at. > One such topic was calculating square roots ‘by hand’ and then deriving a Haskell algorithm. > I wrote about the well known technique here > http://gitcommit.co.uk/2017/08/25/the-root-of-the-problem-part-1/ > > and it it is really quite a simple method. > > The second part of the post will be an implementation in Haskell. > > I then tried implementing it and got something that works but really its not very pleasant to look at! And its something I don’t want to post! Some parts are fine but I think I locked myself into the notion that it had to be using State and really the end result is pretty poor. > > I know this i perhaps a ‘big ask’ but I’d really appreciate any suggestions, solutions, hints etc. I will of course give full attribution. > > I’ve created a gist of the code here > https://gist.github.com/banditpig > > Many Thanks > > Mike > > _______________________________________________ > 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 > > > > This email originated from DIT. If you received this email in error, please delete it from your system. Please note that if you are not the named addressee, disclosing, copying, distributing or taking any action based on the contents of this email or attachments is prohibited. www.dit.ie > Is ó ITBÁC a tháinig an ríomhphost seo. Má fuair tú an ríomhphost seo trí earráid, scrios de do chóras é le do thoil. Tabhair ar aird, mura tú an seolaí ainmnithe, go bhfuil dianchosc ar aon nochtadh, aon chóipeáil, aon dáileadh nó ar aon ghníomh a dhéanfar bunaithe ar an ábhar atá sa ríomhphost nó sna hiatáin seo. www.dit.ie > Tá ITBÁC ag aistriú go Gráinseach Ghormáin – DIT is on the move to Grangegorman > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > > This email originated from DIT. If you received this email in error, please delete it from your system. Please note that if you are not the named addressee, disclosing, copying, distributing or taking any action based on the contents of this email or attachments is prohibited. www.dit.ie > Is ó ITBÁC a tháinig an ríomhphost seo. Má fuair tú an ríomhphost seo trí earráid, scrios de do chóras é le do thoil. Tabhair ar aird, mura tú an seolaí ainmnithe, go bhfuil dianchosc ar aon nochtadh, aon chóipeáil, aon dáileadh nó ar aon ghníomh a dhéanfar bunaithe ar an ábhar atá sa ríomhphost nó sna hiatáin seo. www.dit.ie > Tá ITBÁC ag aistriú go Gráinseach Ghormáin – DIT is on the move to Grangegorman > _______________________________________________ > 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 Fri Sep 15 22:53:54 2017 From: mva.led at gmail.com (=?utf-8?Q?Manuel_V=C3=A1zquez_Acosta?=) Date: Fri, 15 Sep 2017 18:53:54 -0400 Subject: [Haskell-beginners] Syntax error using where with guards. Message-ID: <87r2v74lq5.fsf@pavla.com> I was trying to implement a functional version of numerator/denominator simplifications of symbols. I came up with: simplify :: (Eq o, Ord o) => [o] -> [o] -> ([o], [o]) simplify [] bs = ([], bs) simplify ts [] = (ts, []) simplify (x:xs) (y:ys) | x == y = simplify xs ys | x < y = ([x] ++ (fst $ simplify xs (y:ys)), snd $ simplify xs (y:ys)) | otherwise = (fst r, [y] ++ snd r) where r = simplify (x:xs) ys simplify2 :: (Eq o, Ord o) => [o] -> [o] -> ([o], [o]) simplify2 a b = simplify (sort a) (sort b) -- sort not shown here In the second guard of the simplify function the expression 'simplify xs (y:ys)' is repeated. I would like to write instead: simplify (x:xs) (y:ys) | x == y = simplify xs ys | x < y = ([x] ++ fst r, snd r) where r = simplify xs (y:ys) | otherwise = (fst r, [y] ++ snd r) where r = simplify (x:xs) ys But doing so is parse error: $ ghc xoutil/dim/meta.hs [1 of 1] Compiling Meta ( xoutil/dim/meta.hs, xoutil/dim/meta.o ) xoutil/dim/meta.hs:19:3: parse error on input ‘|’ I'm using: ghc 7.10.3. Any ideas of why this is a syntax error? Best regards, Manuel. From fa-ml at ariis.it Fri Sep 15 23:49:00 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Sat, 16 Sep 2017 01:49:00 +0200 Subject: [Haskell-beginners] Syntax error using where with guards. In-Reply-To: <87r2v74lq5.fsf@pavla.com> References: <87r2v74lq5.fsf@pavla.com> Message-ID: <20170915234900.4iaz6q2umv7dxxmu@x60s.casa> On Fri, Sep 15, 2017 at 06:53:54PM -0400, Manuel Vázquez Acosta wrote: > $ ghc xoutil/dim/meta.hs > [1 of 1] Compiling Meta ( xoutil/dim/meta.hs, xoutil/dim/meta.o ) > > xoutil/dim/meta.hs:19:3: parse error on input ‘|’ Hello Manuel, `where` scopes over several guarded equations (and this is the main difference with `let`). This should do the trick: | a == 1 = let x = 10 in x + a | a == 2 = let x = 3 in x + a From mva.led at gmail.com Sat Sep 16 01:37:58 2017 From: mva.led at gmail.com (mva.led at gmail.com) Date: Fri, 15 Sep 2017 21:37:58 -0400 Subject: [Haskell-beginners] Syntax error using where with guards. In-Reply-To: <20170915234900.4iaz6q2umv7dxxmu@x60s.casa> (Francesco Ariis's message of "Sat, 16 Sep 2017 01:49:00 +0200") References: <87r2v74lq5.fsf@pavla.com> <20170915234900.4iaz6q2umv7dxxmu@x60s.casa> Message-ID: <87lglf4e4p.fsf@pavla.com> Thanks, that solves it. I really like `where`, though. Francesco Ariis writes: > On Fri, Sep 15, 2017 at 06:53:54PM -0400, Manuel Vázquez Acosta wrote: >> $ ghc xoutil/dim/meta.hs >> [1 of 1] Compiling Meta ( xoutil/dim/meta.hs, xoutil/dim/meta.o ) >> >> xoutil/dim/meta.hs:19:3: parse error on input ‘|’ > > Hello Manuel, > `where` scopes over several guarded equations (and this is the main > difference with `let`). This should do the trick: > > | a == 1 = let x = 10 > in x + a > | a == 2 = let x = 3 > in x + a > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From matt.williams45.mw at gmail.com Fri Sep 22 19:53:55 2017 From: matt.williams45.mw at gmail.com (Matt Williams) Date: Fri, 22 Sep 2017 20:53:55 +0100 Subject: [Haskell-beginners] Writing a polymorphic function in Haskell Message-ID: Dear All, I am having problems writing a polymorphic function. I have a type that has two constructors: data Arg = IndArg {evi::Evi, t1::Treatment, t2::Treatment, out::Outcome, dir::Direction} | MetaArg {target::EviType} deriving (Show) I have a function checks for conflict: checkConflict :: Arg -> Arg -> Bool checkConflict a b = if t1 a == t1 b && t2 a == t2 b && dir a /= dir b then True else False However, I can't make this work with both types of Argument - if I pass it MetaArg, it raises an error. In another language, I would write something like: checkConflict(ArgA,ArgB): -------------- next part -------------- An HTML attachment was scrubbed... URL: From matt.williams45.mw at gmail.com Fri Sep 22 19:55:43 2017 From: matt.williams45.mw at gmail.com (Matt Williams) Date: Fri, 22 Sep 2017 20:55:43 +0100 Subject: [Haskell-beginners] Writing a polymorphic function in Haskell In-Reply-To: References: Message-ID: Apologies - sent too soon - code edited below Dear All, > > I am having problems writing a polymorphic function. > > I have a type that has two constructors: > > data Arg = IndArg {evi::Evi, t1::Treatment, t2::Treatment, out::Outcome, > dir::Direction} > | MetaArg {target::EviType} > deriving (Show) > > I have a function checks for conflict: > > checkConflict :: Arg -> Arg -> Bool > checkConflict a b = if t1 a == t1 b && t2 a == t2 b && dir a /= dir b then > True > else False > > However, I can't make this work with both types of Argument - if I pass it > MetaArg, it raises an error. > > In another language, I would write something like: > > checkConflict(ArgA,ArgB): > if type(ArgA) == IndArg: elif type(ArgA) == MetaArg: Any thoughts would be welcomed. BW, Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From aditya.siram at gmail.com Fri Sep 22 20:14:29 2017 From: aditya.siram at gmail.com (aditya siram) Date: Fri, 22 Sep 2017 15:14:29 -0500 Subject: [Haskell-beginners] Writing a polymorphic function in Haskell In-Reply-To: References: Message-ID: Not tested but maybe adding an Eq instance to your datatype would help? So try changing 'deriving (Show)' to 'deriving (Show, Eq)'. On Fri, Sep 22, 2017 at 2:55 PM, Matt Williams wrote: > Apologies - sent too soon - code edited below > > Dear All, >> >> I am having problems writing a polymorphic function. >> >> I have a type that has two constructors: >> >> data Arg = IndArg {evi::Evi, t1::Treatment, t2::Treatment, out::Outcome, >> dir::Direction} >> | MetaArg {target::EviType} >> deriving (Show) >> >> I have a function checks for conflict: >> >> checkConflict :: Arg -> Arg -> Bool >> checkConflict a b = if t1 a == t1 b && t2 a == t2 b && dir a /= dir b >> then True >> else False >> >> However, I can't make this work with both types of Argument - if I pass >> it MetaArg, it raises an error. >> >> In another language, I would write something like: >> >> checkConflict(ArgA,ArgB): >> > if type(ArgA) == IndArg: > > elif type(ArgA) == MetaArg: > > > Any thoughts would be welcomed. > > BW, > Matt > > > > _______________________________________________ > 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 toad3k at gmail.com Fri Sep 22 20:16:55 2017 From: toad3k at gmail.com (David McBride) Date: Fri, 22 Sep 2017 16:16:55 -0400 Subject: [Haskell-beginners] Writing a polymorphic function in Haskell In-Reply-To: References: Message-ID: It is a mistake to use record syntax with data types with multiple constructors. It creates a partial function that dies when you try to use it on a constructor that does not have that field. It is a flaw in the language that many people would like to see removed because it allows programs to compile that will fail at run time, possibly unexpectedly. Arg can have a constructor that does not have an evi. Also what happens if you compare an IndArg to a MetaArg? Or a MetaArg to another MetaArg? You should remove all of these record names, and then write checkConflict as follows (warning untested): checkConflict :: Arg -> Arg -> Bool checkConflict (IndArg _ at1 at2 _ adir) (IndArg _ bt1 bt2 _ bdir) = at1 == bt1 && at2 == bt2 && adir /= bdir -- checkConflict (IndArg ...) (MetaArg) = ??? -- checkConflict a@(MetaArg ...) b@(IndArg ...) = checkConflict b a -- checkConflict (MetaArg _) (MetaArg _) = ??? checkConflict _ _ -> False -- perhaps a catchall? However, you may keep the records as long as you are absolutely sure you are using them only in places where you have the appropriate constructor. On Fri, Sep 22, 2017 at 3:53 PM, Matt Williams wrote: > Dear All, > > I am having problems writing a polymorphic function. > > I have a type that has two constructors: > > data Arg = IndArg {evi::Evi, t1::Treatment, t2::Treatment, out::Outcome, > dir::Direction} > | MetaArg {target::EviType} > deriving (Show) > > I have a function checks for conflict: > > checkConflict :: Arg -> Arg -> Bool > checkConflict a b = if t1 a == t1 b && t2 a == t2 b && dir a /= dir b then > True > else False > > However, I can't make this work with both types of Argument - if I pass it > MetaArg, it raises an error. > > In another language, I would write something like: > > checkConflict(ArgA,ArgB): > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > From matt.williams45.mw at gmail.com Sat Sep 23 15:17:25 2017 From: matt.williams45.mw at gmail.com (Matt Williams) Date: Sat, 23 Sep 2017 16:17:25 +0100 Subject: [Haskell-beginners] Writing a polymorphic function in Haskell In-Reply-To: References: Message-ID: Dear All, Thanks so much for your help. It was largely a syntactic issue around pattern matching - but I also learnt about the @ operator for patter-matching. The correct code is posted below in case it helps anyone else. The only other think would be to rewrite eviCheck as an inline function using where, but I am happy with this for now. Thanks for your speedy help. BW, Matt checkConflict3 :: Arg -> Arg -> Bool checkConflict3 (IndArg _ at1 at2 _ adir) (IndArg _ bt1 bt2 _ bdir) = if at1 == bt1 && at2 == bt2 && adir /= bdir then True else if at1 == bt2 && at2 == bt1 && revDir (adir) /= bdir then True else False checkConflict3 (IndArg e _ _ _ _) (MetaArg a) = eviCheck e a checkConflict3 a@(MetaArg a) b@(IndArg e _ _ _ _) = eviCheck b a checkConflict3 (MetaArg _) (MetaArg _) = False checkConflict3 _ _ = False --A final catchall eviCheck:: Evi -> EviType -> Bool eviCheck (SimpEvi _ _ _ _ type1) type2 = if type1 == type2 then True else False On 22 September 2017 at 21:16, David McBride wrote: > It is a mistake to use record syntax with data types with multiple > constructors. It creates a partial function that dies when you try to > use it on a constructor that does not have that field. It is a flaw > in the language that many people would like to see removed because it > allows programs to compile that will fail at run time, possibly > unexpectedly. > > Arg can have a constructor that does not have an evi. Also what > happens if you compare an IndArg to a MetaArg? Or a MetaArg to > another MetaArg? > > You should remove all of these record names, and then write > checkConflict as follows (warning untested): > > checkConflict :: Arg -> Arg -> Bool > checkConflict (IndArg _ at1 at2 _ adir) (IndArg _ bt1 bt2 _ bdir) = > at1 == bt1 && at2 == bt2 && adir /= bdir > -- checkConflict (IndArg ...) (MetaArg) = ??? > -- checkConflict a@(MetaArg ...) b@(IndArg ...) = checkConflict b a > -- checkConflict (MetaArg _) (MetaArg _) = ??? > checkConflict _ _ -> False -- perhaps a catchall? > > However, you may keep the records as long as you are absolutely sure > you are using them only in places where you have the appropriate > constructor. > > On Fri, Sep 22, 2017 at 3:53 PM, Matt Williams > wrote: > > Dear All, > > > > I am having problems writing a polymorphic function. > > > > I have a type that has two constructors: > > > > data Arg = IndArg {evi::Evi, t1::Treatment, t2::Treatment, out::Outcome, > > dir::Direction} > > | MetaArg {target::EviType} > > deriving (Show) > > > > I have a function checks for conflict: > > > > checkConflict :: Arg -> Arg -> Bool > > checkConflict a b = if t1 a == t1 b && t2 a == t2 b && dir a /= dir b > then > > True > > else False > > > > However, I can't make this work with both types of Argument - if I pass > it > > MetaArg, it raises an error. > > > > In another language, I would write something like: > > > > checkConflict(ArgA,ArgB): > > > > > > > > _______________________________________________ > > 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 Sep 24 19:08:40 2017 From: mike_k_houghton at yahoo.co.uk (mike h) Date: Sun, 24 Sep 2017 20:08:40 +0100 Subject: [Haskell-beginners] take until duplicate Message-ID: <9DB6075E-0A0C-460F-8D9C-F58B2A1E8FAA@yahoo.co.uk> I’m looking at how to take from a list until a duplicate is found. e.g. takeUntilDup [1,2,3,4,3] = [1,2,3,4] I found this implementation takeUntilDup = foldr (\x r -> x : takeWhile (/= x) r) [] It works but I can’t see how!!? The accumulated result is built up in r so with input [1,2,3,4,3] then, at the point when r = [1, 2, 3, 4], the fold is about to use the number 3. i.e. it does takeWhile (/=3) [1,2,3,4] which gives [1,2] Please, how does this work? Thanks Mike . From mike_k_houghton at yahoo.co.uk Sun Sep 24 19:31:46 2017 From: mike_k_houghton at yahoo.co.uk (mike h) Date: Sun, 24 Sep 2017 20:31:46 +0100 Subject: [Haskell-beginners] take until duplicate In-Reply-To: <9DB6075E-0A0C-460F-8D9C-F58B2A1E8FAA@yahoo.co.uk> References: <9DB6075E-0A0C-460F-8D9C-F58B2A1E8FAA@yahoo.co.uk> Message-ID: duh! I tried scanr (\x acc -> x : takeWhile (/= x) acc) [] [1,2,3,4,5,3] which gives [[1,2,3,4,5],[2,3,4,5],[3,4,5],[4,5,3],[5,3],[3],[]] which kind of makes sense. M > On 24 Sep 2017, at 20:08, mike h wrote: > > I’m looking at how to take from a list until a duplicate is found. > e.g. > > takeUntilDup [1,2,3,4,3] = [1,2,3,4] > > I found this implementation > > takeUntilDup = foldr (\x r -> x : takeWhile (/= x) r) [] > > It works but I can’t see how!!? > The accumulated result is built up in r so with input [1,2,3,4,3] then, at the point when r = [1, 2, 3, 4], the fold is about to use the number 3. i.e. it does takeWhile (/=3) [1,2,3,4] which gives [1,2] > > Please, how does this work? > > Thanks > Mike . From fa-ml at ariis.it Sun Sep 24 19:34:10 2017 From: fa-ml at ariis.it (Francesco Ariis) Date: Sun, 24 Sep 2017 21:34:10 +0200 Subject: [Haskell-beginners] take until duplicate In-Reply-To: References: <9DB6075E-0A0C-460F-8D9C-F58B2A1E8FAA@yahoo.co.uk> Message-ID: <20170924193410.tew655ltajkqin2i@x60s.casa> On Sun, Sep 24, 2017 at 08:31:46PM +0100, mike h wrote: > duh! I tried > > scanr (\x acc -> x : takeWhile (/= x) acc) [] [1,2,3,4,5,3] > > which gives > [[1,2,3,4,5],[2,3,4,5],[3,4,5],[4,5,3],[5,3],[3],[]] > > which kind of makes sense. > > M Well done, I find that :step and :show bindings are useful too in these cases. From aquagnu at gmail.com Mon Sep 25 10:06:17 2017 From: aquagnu at gmail.com (Baa) Date: Mon, 25 Sep 2017 13:06:17 +0300 Subject: [Haskell-beginners] Ambogous error in returning value Message-ID: <20170925130617.2c745f7d@Pavel> Hello, everyone. Considering, I have a class: class Flt a where allows :: FltOpts -> [a] denies :: FltOpts -> [a] crit :: a -> [a] -> Bool flt :: FltOpts -> a -> Bool flt opts a = allowed && not denied where allowed = if null $ allows opts then True else a `crit` (allows opts) denied = if null $ denies opts then False else a `crit` (denies opts) I get error here: • Could not deduce (Flt a1) arising from a use of ‘allows’ from the context: Flt a bound by the class declaration for ‘Flt’ at .../.stack-work/intero/intero5319V42.hs:(31,1)-(38,97) The type variable ‘a1’ is ambiguous These potential instance exist: instance Flt MyType -- Defined at ... • In the second argument of ‘($)’, namely ‘allows opts’ .................................................... As I understand, GHC can not deduce type if it's a return's value (contraposition?). OK, but it knows its type: it is `[a]`! What is the problem to keep `flt` method as a generic, i.e. without concreate type, but only `[a]` ? Second, I implemented instance: instance Flt MyType where allows = ... denies = ... flt opts a = allowed && not denied where allowed = if null $ (allows opts::[MyType]) then True else a `crit` (allows opts) denied = if null $ (denies opts::[MyType]) then False else a `crit` (denies opts) and without this explicite type annotation of `allows opts` I get again ambigous error. But why? GHC knows that `allows` returns `[a]` and `a` is `MyType`, so `[a]` is `[MyType]`. Why I need to write it explicitly? May be I need some extension here? === Best regards, Paul From toad3k at gmail.com Tue Sep 26 12:50:57 2017 From: toad3k at gmail.com (David McBride) Date: Tue, 26 Sep 2017 08:50:57 -0400 Subject: [Haskell-beginners] Ambogous error in returning value In-Reply-To: <20170925130617.2c745f7d@Pavel> References: <20170925130617.2c745f7d@Pavel> Message-ID: The problem in the class is that it doesn't necessarily know that (allows opts) and (crit a allows opts) necessarily are working on the exact same Flt instance. (allows opts) could return [Foo], and but crit is constrainted by the argument passed to it which is the a in question. The fact that there is only one possible instance right now does not change the fact that there could be more in the future. denied is already constrained because its return value is used as an argument of crit. To fix it {-# LANGUAGE ScopedTypeVariables #-} class Flt a where .... where allowed = if null $ (allows opts :: [a]) then True else a `crit` (allows opts) denied = if null $ (denies opts :: [a]) then False else (a :: a) `crit` (denies opts) When you see an error Flt a1 does not match Flt a, that's a classic sign that it doesn't know a1 and a are the same type. As for the instance it has the exact same problem. If you were to pull allowed into its own function outside the class you could constrain both functions at the same time, at the cost of some verbosity. {-# LANGUAGE ScopedTypeVariables #-} class Flt a where ... flt opts a = allowed2 opts a && not denied instance Flt MyType where ... flt opts a = allowed2 opts a && not denied allowed2 :: forall a. Flt a => FltOpts -> a -> Bool allowed2 opts a = if null $ (allows opts :: [a]) then True else a `crit` (allows opts) On Mon, Sep 25, 2017 at 6:06 AM, Baa wrote: > Hello, everyone. > > Considering, I have a class: > > class Flt a where > allows :: FltOpts -> [a] > denies :: FltOpts -> [a] > crit :: a -> [a] -> Bool > flt :: FltOpts -> a -> Bool > flt opts a = allowed && not denied > where allowed = if null $ allows opts then True else a `crit` (allows opts) > denied = if null $ denies opts then False else a `crit` (denies opts) > > I get error here: > > • Could not deduce (Flt a1) arising from a use of ‘allows’ > from the context: Flt a > bound by the class declaration for ‘Flt’ > at .../.stack-work/intero/intero5319V42.hs:(31,1)-(38,97) > The type variable ‘a1’ is ambiguous > These potential instance exist: > instance Flt MyType > -- Defined at ... > • In the second argument of ‘($)’, namely ‘allows opts’ > .................................................... > > As I understand, GHC can not deduce type if it's a return's value > (contraposition?). OK, but it knows its type: it is `[a]`! What is the > problem to keep `flt` method as a generic, i.e. without concreate type, > but only `[a]` ? > > Second, I implemented instance: > > instance Flt MyType where > allows = ... > denies = ... > flt opts a = allowed && not denied > where allowed = if null $ (allows opts::[MyType]) then True else a `crit` (allows opts) > denied = if null $ (denies opts::[MyType]) then False else a `crit` (denies opts) > > and without this explicite type annotation of `allows opts` I get again > ambigous error. But why? GHC knows that `allows` returns `[a]` and `a` > is `MyType`, so `[a]` is `[MyType]`. Why I need to write it explicitly? > May be I need some extension here? > > > === > Best regards, Paul > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From aquagnu at gmail.com Tue Sep 26 13:12:35 2017 From: aquagnu at gmail.com (Baa) Date: Tue, 26 Sep 2017 16:12:35 +0300 Subject: [Haskell-beginners] Ambogous error in returning value In-Reply-To: References: <20170925130617.2c745f7d@Pavel> Message-ID: <20170926161235.57109b95@Pavel> Hello, David! Hmm, yes, I got it. Interesting is that I tried to set explicitly types as `[a]` of `allows opts` and `denies opts` in the class too (like in instance) but without this extension: {-# LANGUAGE ScopedTypeVariables #-} and Intero nothing helps about "...do you want to include blah-blah, press C-c C-r..." as usual it does it :) OK, your explanation is absolutely enought. Thank you! Have a nice day, === Best regards, Paul From jimbo4350 at gmail.com Tue Sep 26 16:59:05 2017 From: jimbo4350 at gmail.com (Jimbo) Date: Tue, 26 Sep 2017 12:59:05 -0400 Subject: [Haskell-beginners] Sequence function Message-ID: Hello everyone, Just trying to understand the sequence function as follows: sequence [Just 1] -- evaluates to Just [1] sequence = foldr mcons (return [])     where mcons p q = p >>= \x -> q >>= \y -> return (x:y) -- I'm trying to walk through the code as follows, I understand what is below isn't -- haskell code p >>= \x ->              [] q >>= \y ->        Just 1 return (x:y)    --  [] : Just 1 Am I thinking of sequence correctly here? Best regards, Jim From toad3k at gmail.com Tue Sep 26 17:49:24 2017 From: toad3k at gmail.com (David McBride) Date: Tue, 26 Sep 2017 13:49:24 -0400 Subject: [Haskell-beginners] Sequence function In-Reply-To: References: Message-ID: Remember that foldr has flipped operator order from foldl. >:t foldl foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b >:t foldr foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b That means that you should expand them in the opposite order from how it seems to read. p >>= \x -> -- Just 1 >>= \ 1 q >>= \y -> -- return [] >>= \ [] return (1 : []) -- Just [1] On Tue, Sep 26, 2017 at 12:59 PM, Jimbo wrote: > Hello everyone, > > Just trying to understand the sequence function as follows: > > sequence [Just 1] > > -- evaluates to Just [1] > > sequence = foldr mcons (return []) > where mcons p q = p >>= \x -> q >>= \y -> return (x:y) > > -- I'm trying to walk through the code as follows, I understand what is > below isn't > -- haskell code > > p >>= \x -> [] > q >>= \y -> Just 1 > return (x:y) -- [] : Just 1 > > Am I thinking of sequence correctly here? > > Best regards, > > Jim > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From jimbo4350 at gmail.com Tue Sep 26 18:10:32 2017 From: jimbo4350 at gmail.com (Jimbo) Date: Tue, 26 Sep 2017 14:10:32 -0400 Subject: [Haskell-beginners] Sequence function In-Reply-To: References: Message-ID: Thank you very much. Final question, in the line: return (1 : []) -- Just [1] Does the value ([1] in this case) get wrapped in Just because of the type signature of sequence? I.e sequence :: Monad m => [m a] -> m [a] On 26/09/2017 1:49 PM, David McBride wrote: > Remember that foldr has flipped operator order from foldl. > >> :t foldl > foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b >> :t foldr > foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b > > That means that you should expand them in the opposite order from how > it seems to read. > > p >>= \x -> -- Just 1 >>= \ 1 > q >>= \y -> -- return [] >>= \ [] > return (1 : []) -- Just [1] > > > > On Tue, Sep 26, 2017 at 12:59 PM, Jimbo wrote: >> Hello everyone, >> >> Just trying to understand the sequence function as follows: >> >> sequence [Just 1] >> >> -- evaluates to Just [1] >> >> sequence = foldr mcons (return []) >> where mcons p q = p >>= \x -> q >>= \y -> return (x:y) >> >> -- I'm trying to walk through the code as follows, I understand what is >> below isn't >> -- haskell code >> >> p >>= \x -> [] >> q >>= \y -> Just 1 >> return (x:y) -- [] : Just 1 >> >> Am I thinking of sequence correctly here? >> >> Best regards, >> >> Jim >> >> _______________________________________________ >> 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 toad3k at gmail.com Tue Sep 26 18:28:48 2017 From: toad3k at gmail.com (David McBride) Date: Tue, 26 Sep 2017 14:28:48 -0400 Subject: [Haskell-beginners] Sequence function In-Reply-To: References: Message-ID: Monadic bind has this signature (Monad m => m a -> (a -> m b) -> m b. Note that m is the same in both arguments and also the return value. So when you see p >>= \_ -> q ..., that means both p and q must be (m Something), where the m is the same. So when you go (Just 1 >>= \x -> return [] >>= \y -> return (x:y)) you know that return [] and return (x:y) are both using the Maybe Monad instance because in Just 1, the m is Maybe. So return [] is then equivalent to Just [], and return (x:y) is equivalent to Just (x:y). I hope that made sense. On Tue, Sep 26, 2017 at 2:10 PM, Jimbo wrote: > Thank you very much. Final question, in the line: > > return (1 : []) -- Just [1] > > Does the value ([1] in this case) get wrapped in Just because of the type > signature of sequence? I.e > > sequence :: Monad m => [m a] -> m [a] > > > > On 26/09/2017 1:49 PM, David McBride wrote: >> >> Remember that foldr has flipped operator order from foldl. >> >>> :t foldl >> >> foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b >>> >>> :t foldr >> >> foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b >> >> That means that you should expand them in the opposite order from how >> it seems to read. >> >> p >>= \x -> -- Just 1 >>= \ 1 >> q >>= \y -> -- return [] >>= \ [] >> return (1 : []) -- Just [1] >> >> >> >> On Tue, Sep 26, 2017 at 12:59 PM, Jimbo wrote: >>> >>> Hello everyone, >>> >>> Just trying to understand the sequence function as follows: >>> >>> sequence [Just 1] >>> >>> -- evaluates to Just [1] >>> >>> sequence = foldr mcons (return []) >>> where mcons p q = p >>= \x -> q >>= \y -> return (x:y) >>> >>> -- I'm trying to walk through the code as follows, I understand what is >>> below isn't >>> -- haskell code >>> >>> p >>= \x -> [] >>> q >>= \y -> Just 1 >>> return (x:y) -- [] : Just 1 >>> >>> Am I thinking of sequence correctly here? >>> >>> Best regards, >>> >>> Jim >>> >>> _______________________________________________ >>> 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 jimbo4350 at gmail.com Tue Sep 26 21:39:21 2017 From: jimbo4350 at gmail.com (Jimbo) Date: Tue, 26 Sep 2017 17:39:21 -0400 Subject: [Haskell-beginners] Sequence function In-Reply-To: References: Message-ID: "So when you go (Just 1 >>= \x -> return [] >>= \y -> return (x:y)) you know that return [] and return (x:y) are both using the Maybe Monad instance because in Just 1, the m is Maybe." I understand what you are saying but just to further clarify for my own understanding, is this what is meant by Haskell being able to reason about your program? That is, because you have "chosen" m to be the Maybe monad by using Just 1 (quoted above), the following return functions (in the above computation) use the definition for return below with m being Maybe? class Monad mwhere (>>=) :: m a-> (a-> m b) -> m b return :: a-> m a On 26/09/2017 2:28 PM, David McBride wrote: > Monadic bind has this signature (Monad m => m a -> (a -> m b) -> m b. > Note that m is the same in both arguments and also the return value. > > So when you see p >>= \_ -> q ..., that means both p and q must be (m > Something), where the m is the same. > > So when you go (Just 1 >>= \x -> return [] >>= \y -> return (x:y)) > you know that return [] and return (x:y) are both using the Maybe > Monad instance because in Just 1, the m is Maybe. > > So return [] is then equivalent to Just [], and return (x:y) is > equivalent to Just (x:y). I hope that made sense. > > On Tue, Sep 26, 2017 at 2:10 PM, Jimbo wrote: >> Thank you very much. Final question, in the line: >> >> return (1 : []) -- Just [1] >> >> Does the value ([1] in this case) get wrapped in Just because of the type >> signature of sequence? I.e >> >> sequence :: Monad m => [m a] -> m [a] >> >> >> >> On 26/09/2017 1:49 PM, David McBride wrote: >>> Remember that foldr has flipped operator order from foldl. >>> >>>> :t foldl >>> foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b >>>> :t foldr >>> foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b >>> >>> That means that you should expand them in the opposite order from how >>> it seems to read. >>> >>> p >>= \x -> -- Just 1 >>= \ 1 >>> q >>= \y -> -- return [] >>= \ [] >>> return (1 : []) -- Just [1] >>> >>> >>> >>> On Tue, Sep 26, 2017 at 12:59 PM, Jimbo wrote: >>>> Hello everyone, >>>> >>>> Just trying to understand the sequence function as follows: >>>> >>>> sequence [Just 1] >>>> >>>> -- evaluates to Just [1] >>>> >>>> sequence = foldr mcons (return []) >>>> where mcons p q = p >>= \x -> q >>= \y -> return (x:y) >>>> >>>> -- I'm trying to walk through the code as follows, I understand what is >>>> below isn't >>>> -- haskell code >>>> >>>> p >>= \x -> [] >>>> q >>= \y -> Just 1 >>>> return (x:y) -- [] : Just 1 >>>> >>>> Am I thinking of sequence correctly here? >>>> >>>> Best regards, >>>> >>>> Jim >>>> >>>> _______________________________________________ >>>> 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 > _______________________________________________ > 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 toad3k at gmail.com Tue Sep 26 23:55:36 2017 From: toad3k at gmail.com (David McBride) Date: Tue, 26 Sep 2017 19:55:36 -0400 Subject: [Haskell-beginners] Sequence function In-Reply-To: References: Message-ID: This is known as type inference. On Sep 26, 2017 17:41, "Jimbo" wrote: > "So when you go (Just 1 >>= \x -> return [] >>= \y -> return (x:y)) > you know that return [] and return (x:y) are both using the Maybe > Monad instance because in Just 1, the m is Maybe." > > I understand what you are saying but just to further clarify for my own understanding, is this what is meant by Haskell being able to reason about your program? That is, because you have "chosen" m to be the Maybe monad by using Just 1 (quoted above), the following return functions (in the above computation) use the definition for return below with m being Maybe? > class Monad m where > (>>=) :: m a -> (a -> m b) -> m b > return :: a -> m a > > > > > > > On 26/09/2017 2:28 PM, David McBride wrote: > > Monadic bind has this signature (Monad m => m a -> (a -> m b) -> m b. > Note that m is the same in both arguments and also the return value. > > So when you see p >>= \_ -> q ..., that means both p and q must be (m > Something), where the m is the same. > > So when you go (Just 1 >>= \x -> return [] >>= \y -> return (x:y)) > you know that return [] and return (x:y) are both using the Maybe > Monad instance because in Just 1, the m is Maybe. > > So return [] is then equivalent to Just [], and return (x:y) is > equivalent to Just (x:y). I hope that made sense. > > On Tue, Sep 26, 2017 at 2:10 PM, Jimbo wrote: > > Thank you very much. Final question, in the line: > > return (1 : []) -- Just [1] > > Does the value ([1] in this case) get wrapped in Just because of the type > signature of sequence? I.e > > sequence :: Monad m => [m a] -> m [a] > > > > On 26/09/2017 1:49 PM, David McBride wrote: > > > Remember that foldr has flipped operator order from foldl. > > > :t foldl > > > foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b > > > :t foldr > > > foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b > > That means that you should expand them in the opposite order from how > it seems to read. > > p >>= \x -> -- Just 1 >>= \ 1 > q >>= \y -> -- return [] >>= \ [] > return (1 : []) -- Just [1] > > > > On Tue, Sep 26, 2017 at 12:59 PM, Jimbo wrote: > > > Hello everyone, > > Just trying to understand the sequence function as follows: > > sequence [Just 1] > > -- evaluates to Just [1] > > sequence = foldr mcons (return []) > where mcons p q = p >>= \x -> q >>= \y -> return (x:y) > > -- I'm trying to walk through the code as follows, I understand what is > below isn't > -- haskell code > > p >>= \x -> [] > q >>= \y -> Just 1 > return (x:y) -- [] : Just 1 > > Am I thinking of sequence correctly here? > > Best regards, > > Jim > > _______________________________________________ > Beginners mailing listBeginners at haskell.orghttp://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > _______________________________________________ > Beginners mailing listBeginners at haskell.orghttp://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > _______________________________________________ > Beginners mailing listBeginners at haskell.orghttp://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > _______________________________________________ > Beginners mailing listBeginners at haskell.orghttp://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 aquagnu at gmail.com Wed Sep 27 15:50:38 2017 From: aquagnu at gmail.com (Baa) Date: Wed, 27 Sep 2017 18:50:38 +0300 Subject: [Haskell-beginners] Ambiguous type error: multiparam class + type alias Message-ID: <20170927185038.44cde600@Pavel> Hello, List! The further - the more interesting... For example, I want own `Show` analogue, which will be parameterized with type meaning "context"/"reason". So, to represent title of the value I will call: repr x::TitleRepr or simple `Show`: repr x::ShowRepr or repr x::Repr AsShow etc. I try: {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE MultiParamTypeClasses #-} data AsShow data AsTitle type Repr a = String class ReprC a b where repr :: a -> Repr b instance ReprC Int AsTitle where repr n = "a number " ++ show n main = do let n = 5 :: Int print $ (repr n :: Repr AsTitle) and sure I get error: • Ambiguous type variable ‘b0’ arising from a use of ‘repr’ prevents the constraint ‘(ReprC Int b0)’ from being solved. Probable fix: use a type annotation to specify what ‘b0’ should be. These potential instance exist: instance ReprC Int AsTitle -- Defined at .../.stack-work/intero/intero31144sPV.hs:12:10 • In the second argument of ‘($)’, namely ‘(repr n :: Repr AsTitle)’ In a stmt of a 'do' block: print $ (repr n :: Repr AsTitle) In the expression: do { let n = ...; print $ (repr n :: Repr AsTitle) } (intero) Sure, I can use as `Repr` not type-alias but `newtype`. But in this case I will need additional call (show/runRepr/coerce/etc.): coerce $ (repr x::AsTitle) So, what is the reason that GHCI is see that `repr n` is `::Repr AsTitle` (AsTitle!!) and says me that `b0` is ambigous?! It should know what concreate `repr` I mean! :) If I use `newtype` - no problem, so I suppose problem is in the type alias. It's not sterling type for such goal, right? Another question is: how to accomplish such goal, i.e. without to make additional call (coerce/show/runRepr/etc) when `repr` will return `String`, wrapped in newtype? PS. Execuse such silly and training example. Actually, I planned to made such class and to use it instead of `Show`. Sure, it can be splitted to several classed (my current state) but.. example is to learn Haskell and to understand my errors... === Best regards, Paul From toad3k at gmail.com Wed Sep 27 16:58:32 2017 From: toad3k at gmail.com (David McBride) Date: Wed, 27 Sep 2017 12:58:32 -0400 Subject: [Haskell-beginners] Ambiguous type error: multiparam class + type alias In-Reply-To: <20170927185038.44cde600@Pavel> References: <20170927185038.44cde600@Pavel> Message-ID: The reason is because 'type' is a type alias that changes nothing code wise, it is merely a visual clue to the reader of code that these two types are the same. You could replace 'Repr AsTitle' with 'String' and you would get the exact same error. That said I do think you can do what you want with type families, but I'm not having luck giving you a complete solution at this time. This would be a good question to ask on stackoverflow if no one here gives a satisfactory answer. Here is the code I had that doesn't quite work, although I'm not sure why. Maybe you can figure it out. I would love to know. {-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-} data AsShow data AsTitle class Repr a b where type ReprC a b :: * repr :: a -> ReprC a b instance Repr Int AsTitle where type ReprC Int AsTitle = String repr n = show n main = do let n = 5 :: Int print $ (repr n) On Wed, Sep 27, 2017 at 11:50 AM, Baa wrote: > Hello, List! > > The further - the more interesting... For example, I want own `Show` analogue, > which will be parameterized with type meaning "context"/"reason". So, to represent > title of the value I will call: > > repr x::TitleRepr > > or simple `Show`: > > repr x::ShowRepr > > or > > repr x::Repr AsShow > > etc. I try: > > {-# LANGUAGE AllowAmbiguousTypes #-} > {-# LANGUAGE MultiParamTypeClasses #-} > > data AsShow > data AsTitle > > type Repr a = String > > class ReprC a b where > repr :: a -> Repr b > > instance ReprC Int AsTitle where > repr n = "a number " ++ show n > > main = do > let n = 5 :: Int > print $ (repr n :: Repr AsTitle) > > and sure I get error: > > • Ambiguous type variable ‘b0’ arising from a use of ‘repr’ > prevents the constraint ‘(ReprC Int b0)’ from being solved. > Probable fix: use a type annotation to specify what ‘b0’ should be. > These potential instance exist: > instance ReprC Int AsTitle > -- Defined at .../.stack-work/intero/intero31144sPV.hs:12:10 > • In the second argument of ‘($)’, namely > ‘(repr n :: Repr AsTitle)’ > In a stmt of a 'do' block: print $ (repr n :: Repr AsTitle) > In the expression: > do { let n = ...; > print $ (repr n :: Repr AsTitle) } (intero) > > Sure, I can use as `Repr` not type-alias but `newtype`. But in this > case I will need additional call (show/runRepr/coerce/etc.): > > coerce $ (repr x::AsTitle) > > So, what is the reason that GHCI is see that `repr n` is `::Repr AsTitle` > (AsTitle!!) and says me that `b0` is ambigous?! It should know > what concreate `repr` I mean! :) If I use `newtype` - no problem, so I > suppose problem is in the type alias. It's not sterling type for such > goal, right? > > Another question is: how to accomplish such goal, i.e. without to > make additional call (coerce/show/runRepr/etc) when `repr` will return > `String`, wrapped in newtype? > > > PS. Execuse such silly and training example. Actually, I planned to made > such class and to use it instead of `Show`. Sure, it can be splitted to > several classed (my current state) but.. example is to learn Haskell > and to understand my errors... > > > === > Best regards, Paul > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From aquagnu at gmail.com Thu Sep 28 07:17:23 2017 From: aquagnu at gmail.com (Baa) Date: Thu, 28 Sep 2017 10:17:23 +0300 Subject: [Haskell-beginners] Ambiguous type error: multiparam class + type alias In-Reply-To: References: <20170927185038.44cde600@Pavel> Message-ID: <20170928101723.0bbb02ba@Pavel> David, hello again! Interesting is that class with one parameter is fine: class Repr a where type ReprAs a reprx :: a -> ReprAs a instance Repr Int where type ReprAs Int = Int reprx n = n main = do let n = 5 :: Int print $ (reprx n) but when I added 2nd param, I get ambogouse error again: class Repr a b where type ReprAs a b repr :: a -> ReprAs a b instance Repr Int AsTitle where type ReprAs Int AsTitle = String repr n = show n main = do let n = 5 :: Int print $ (repr n::ReprAs Int AsTitle) which looks the same as with type-alias: GHC says: 30 12 error error: • Couldn't match type ‘ReprAs Int b0’ with ‘String’ Expected type: ReprAs Int AsTitle Actual type: ReprAs Int b0 The type variable ‘b0’ is ambiguous • In the second argument of ‘($)’, namely ‘(repr n :: ReprAs Int AsTitle)’ In a stmt of a 'do' block: print $ (repr n :: ReprAs Int AsTitle) In the expression: do { let n = ...; print $ (repr n :: ReprAs Int AsTitle) } (intero) looks that `type ReprAs Int AsTitle` is treating type-alias and GHC can not match resulting `String` with `ReprAs Int AsTitle`. As I understand, the root of the problem is that class parameters are not the same as in results' parameters (contraposition types) - they turn out to be free/unbound (execuse my English). For example, to avoid this problem in the class I added extension: {-# LANGUAGE AllowAmbiguousTypes #-} I don't know is a way in Haskell to say to reuse already bound class parameters in "methods" bodies... I found this: https://stackoverflow.com/questions/4174187/reading-and-representing-input-which-specifies-the-data-type-to-use/4174266#4174266 Another variant which is compiling (w/ func-deps): {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} data AsShow data AsTitle type ReprAs a = String class Repr a b | a -> b where repr :: a -> ReprAs b instance Repr Int AsTitle where repr n = "a number '" ++ show n ++ "'" -- instance Repr Int AsShow where -- repr n = "a number '" ++ show n ++ "'" main = do let n = 5 :: Int print $ (repr n::ReprAs AsTitle) print $ (repr n::ReprAs AsShow) but due to `a -> b` it's impossible to instantiate another `Repr Int`! So, I think soultion is in: - func deps - or type families/associative types But unfortunately my knowledge of Haskell is limited to find it. I see only that I need to add another param to func dep of class - to "extend" dependency which allows to determine result type not only on one input argument's type... Thanks David! === Best regards, Paul > The reason is because 'type' is a type alias that changes nothing code > wise, it is merely a visual clue to the reader of code that these two > types are the same. You could replace 'Repr AsTitle' with 'String' > and you would get the exact same error. > > That said I do think you can do what you want with type families, but > I'm not having luck giving you a complete solution at this time. This > would be a good question to ask on stackoverflow if no one here gives > a satisfactory answer. Here is the code I had that doesn't quite > work, although I'm not sure why. Maybe you can figure it out. I > would love to know. > > {-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-} > > data AsShow > data AsTitle > > class Repr a b where > type ReprC a b :: * > repr :: a -> ReprC a b > > instance Repr Int AsTitle where > type ReprC Int AsTitle = String > repr n = show n > > main = do > let n = 5 :: Int > print $ (repr n) > > On Wed, Sep 27, 2017 at 11:50 AM, Baa wrote: > > Hello, List! > > > > The further - the more interesting... For example, I want own > > `Show` analogue, which will be parameterized with type meaning > > "context"/"reason". So, to represent title of the value I will call: > > > > repr x::TitleRepr > > > > or simple `Show`: > > > > repr x::ShowRepr > > > > or > > > > repr x::Repr AsShow > > > > etc. I try: > > > > {-# LANGUAGE AllowAmbiguousTypes #-} > > {-# LANGUAGE MultiParamTypeClasses #-} > > > > data AsShow > > data AsTitle > > > > type Repr a = String > > > > class ReprC a b where > > repr :: a -> Repr b > > > > instance ReprC Int AsTitle where > > repr n = "a number " ++ show n > > > > main = do > > let n = 5 :: Int > > print $ (repr n :: Repr AsTitle) > > > > and sure I get error: > > > > • Ambiguous type variable ‘b0’ arising from a use of ‘repr’ > > prevents the constraint ‘(ReprC Int b0)’ from being solved. > > Probable fix: use a type annotation to specify what ‘b0’ > > should be. These potential instance exist: > > instance ReprC Int AsTitle > > -- Defined > > at .../.stack-work/intero/intero31144sPV.hs:12:10 • In the second > > argument of ‘($)’, namely ‘(repr n :: Repr AsTitle)’ > > In a stmt of a 'do' block: print $ (repr n :: Repr AsTitle) > > In the expression: > > do { let n = ...; > > print $ (repr n :: Repr AsTitle) } (intero) > > > > Sure, I can use as `Repr` not type-alias but `newtype`. But in this > > case I will need additional call (show/runRepr/coerce/etc.): > > > > coerce $ (repr x::AsTitle) > > > > So, what is the reason that GHCI is see that `repr n` is `::Repr > > AsTitle` (AsTitle!!) and says me that `b0` is ambigous?! It should > > know what concreate `repr` I mean! :) If I use `newtype` - no > > problem, so I suppose problem is in the type alias. It's not > > sterling type for such goal, right? > > > > Another question is: how to accomplish such goal, i.e. without to > > make additional call (coerce/show/runRepr/etc) when `repr` will > > return `String`, wrapped in newtype? > > > > > > PS. Execuse such silly and training example. Actually, I planned to > > made such class and to use it instead of `Show`. Sure, it can be > > splitted to several classed (my current state) but.. example is to > > learn Haskell and to understand my errors... > > > > > > === > > Best regards, Paul > > _______________________________________________ > > 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 sylvain at haskus.fr Thu Sep 28 09:12:35 2017 From: sylvain at haskus.fr (Sylvain Henry) Date: Thu, 28 Sep 2017 11:12:35 +0200 Subject: [Haskell-beginners] Ambiguous type error: multiparam class + type alias In-Reply-To: <20170927185038.44cde600@Pavel> References: <20170927185038.44cde600@Pavel> Message-ID: <4041522b-8d46-f53f-d3a5-632999cc8641@haskus.fr> Hi, The issue is that (Repr a ~ Repr b) doesn't imply (a ~ b). Indeed: forall a b. Repr a ~ String ~ Repr b So given the type of `repr n`: repr n :: forall b. ReprC Int b => Repr b When you write: repr n :: Repr AsTitle You only add a constraint as follows: repr n :: forall b. (Repr b ~ Repr AsTitle, ReprC Int b) => Repr b But as we have seen, it doesn't imply (b ~ AsTitle) and b remains ambiguous. A solution is to fix b explicitly with a type application: {-# LANGUAGE TypeApplications #-} ... repr @_ @AsTitle n Best regards, Sylvain On 27/09/2017 17:50, Baa wrote: > Hello, List! > > The further - the more interesting... For example, I want own `Show` analogue, > which will be parameterized with type meaning "context"/"reason". So, to represent > title of the value I will call: > > repr x::TitleRepr > > or simple `Show`: > > repr x::ShowRepr > > or > > repr x::Repr AsShow > > etc. I try: > > {-# LANGUAGE AllowAmbiguousTypes #-} > {-# LANGUAGE MultiParamTypeClasses #-} > > data AsShow > data AsTitle > > type Repr a = String > > class ReprC a b where > repr :: a -> Repr b > > instance ReprC Int AsTitle where > repr n = "a number " ++ show n > > main = do > let n = 5 :: Int > print $ (repr n :: Repr AsTitle) > > and sure I get error: > > • Ambiguous type variable ‘b0’ arising from a use of ‘repr’ > prevents the constraint ‘(ReprC Int b0)’ from being solved. > Probable fix: use a type annotation to specify what ‘b0’ should be. > These potential instance exist: > instance ReprC Int AsTitle > -- Defined at .../.stack-work/intero/intero31144sPV.hs:12:10 > • In the second argument of ‘($)’, namely > ‘(repr n :: Repr AsTitle)’ > In a stmt of a 'do' block: print $ (repr n :: Repr AsTitle) > In the expression: > do { let n = ...; > print $ (repr n :: Repr AsTitle) } (intero) > > Sure, I can use as `Repr` not type-alias but `newtype`. But in this > case I will need additional call (show/runRepr/coerce/etc.): > > coerce $ (repr x::AsTitle) > > So, what is the reason that GHCI is see that `repr n` is `::Repr AsTitle` > (AsTitle!!) and says me that `b0` is ambigous?! It should know > what concreate `repr` I mean! :) If I use `newtype` - no problem, so I > suppose problem is in the type alias. It's not sterling type for such > goal, right? > > Another question is: how to accomplish such goal, i.e. without to > make additional call (coerce/show/runRepr/etc) when `repr` will return > `String`, wrapped in newtype? > > > PS. Execuse such silly and training example. Actually, I planned to made > such class and to use it instead of `Show`. Sure, it can be splitted to > several classed (my current state) but.. example is to learn Haskell > and to understand my errors... > > > === > Best regards, Paul > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From aquagnu at gmail.com Thu Sep 28 10:25:09 2017 From: aquagnu at gmail.com (Baa) Date: Thu, 28 Sep 2017 13:25:09 +0300 Subject: [Haskell-beginners] Ambiguous type error: multiparam class + type alias In-Reply-To: <4041522b-8d46-f53f-d3a5-632999cc8641@haskus.fr> References: <20170927185038.44cde600@Pavel> <4041522b-8d46-f53f-d3a5-632999cc8641@haskus.fr> Message-ID: <20170928132509.0ffcc173@Pavel> Hello, Sylvain. Your solution assumes that I need to pass `@_ @AsTitle` anywhere where I call `repr`? So, instead of `repr n::AsTitle` or `repr n::Something AsTitle` (depends on implementation) I'll write `repr @_ @AsTitle n`, right? > You only add a constraint as follows: > repr n :: forall b. (Repr b ~ Repr AsTitle, ReprC Int b) => Repr b Yes... So, `b` is unbound/free type param. But I can bind it with func. deps, yes? === Best regards, Paul > > But as we have seen, it doesn't imply (b ~ AsTitle) and b remains > ambiguous. > > A solution is to fix b explicitly with a type application: > > {-# LANGUAGE TypeApplications #-} > ... > repr @_ @AsTitle n > > > Best regards, > Sylvain > > > On 27/09/2017 17:50, Baa wrote: > > Hello, List! > > > > The further - the more interesting... For example, I want own > > `Show` analogue, which will be parameterized with type meaning > > "context"/"reason". So, to represent title of the value I will call: > > > > repr x::TitleRepr > > > > or simple `Show`: > > > > repr x::ShowRepr > > > > or > > > > repr x::Repr AsShow > > > > etc. I try: > > > > {-# LANGUAGE AllowAmbiguousTypes #-} > > {-# LANGUAGE MultiParamTypeClasses #-} > > > > data AsShow > > data AsTitle > > > > type Repr a = String > > > > class ReprC a b where > > repr :: a -> Repr b > > > > instance ReprC Int AsTitle where > > repr n = "a number " ++ show n > > > > main = do > > let n = 5 :: Int > > print $ (repr n :: Repr AsTitle) > > > > and sure I get error: > > > > • Ambiguous type variable ‘b0’ arising from a use of ‘repr’ > > prevents the constraint ‘(ReprC Int b0)’ from being solved. > > Probable fix: use a type annotation to specify what ‘b0’ > > should be. These potential instance exist: > > instance ReprC Int AsTitle > > -- Defined > > at .../.stack-work/intero/intero31144sPV.hs:12:10 • In the second > > argument of ‘($)’, namely ‘(repr n :: Repr AsTitle)’ > > In a stmt of a 'do' block: print $ (repr n :: Repr AsTitle) > > In the expression: > > do { let n = ...; > > print $ (repr n :: Repr AsTitle) } (intero) > > > > Sure, I can use as `Repr` not type-alias but `newtype`. But in this > > case I will need additional call (show/runRepr/coerce/etc.): > > > > coerce $ (repr x::AsTitle) > > > > So, what is the reason that GHCI is see that `repr n` is `::Repr > > AsTitle` (AsTitle!!) and says me that `b0` is ambigous?! It should > > know what concreate `repr` I mean! :) If I use `newtype` - no > > problem, so I suppose problem is in the type alias. It's not > > sterling type for such goal, right? > > > > Another question is: how to accomplish such goal, i.e. without to > > make additional call (coerce/show/runRepr/etc) when `repr` will > > return `String`, wrapped in newtype? > > > > > > PS. Execuse such silly and training example. Actually, I planned to > > made such class and to use it instead of `Show`. Sure, it can be > > splitted to several classed (my current state) but.. example is to > > learn Haskell and to understand my errors... > > > > > > === > > Best regards, Paul > > _______________________________________________ > > 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 sylvain at haskus.fr Thu Sep 28 10:58:16 2017 From: sylvain at haskus.fr (Sylvain Henry) Date: Thu, 28 Sep 2017 12:58:16 +0200 Subject: [Haskell-beginners] Ambiguous type error: multiparam class + type alias In-Reply-To: <20170928132509.0ffcc173@Pavel> References: <20170927185038.44cde600@Pavel> <4041522b-8d46-f53f-d3a5-632999cc8641@haskus.fr> <20170928132509.0ffcc173@Pavel> Message-ID: <2aab4bd9-f22c-e738-b467-1d9b7542f15d@haskus.fr> On 28/09/2017 12:25, Baa wrote: > Hello, Sylvain. > > Your solution assumes that I need to pass `@_ @AsTitle` anywhere where I > call `repr`? So, instead of `repr n::AsTitle` or `repr n::Something AsTitle` > (depends on implementation) I'll write `repr @_ @AsTitle n`, right? Yes. You could also avoid all this ambiguity/type application stuff with: data AsTitle = AsTitle class Repr a b where   repr :: a -> b -> Repr b instance Repr Int AsTitle where   repr n _ = ... ... print (repr n AsTitle) (Repr b can be an associated type if you want to support different representations) > >> You only add a constraint as follows: >> repr n :: forall b. (Repr b ~ Repr AsTitle, ReprC Int b) => Repr b > Yes... So, `b` is unbound/free type param. But I can bind it with func. > deps, yes? How? If you you bind it with a functional dependency on "a", you can only have a single "b" for each "a". Sylvain From aquagnu at gmail.com Thu Sep 28 13:30:19 2017 From: aquagnu at gmail.com (Baa) Date: Thu, 28 Sep 2017 16:30:19 +0300 Subject: [Haskell-beginners] Ambiguous type error: multiparam class + type alias In-Reply-To: <2aab4bd9-f22c-e738-b467-1d9b7542f15d@haskus.fr> References: <20170927185038.44cde600@Pavel> <4041522b-8d46-f53f-d3a5-632999cc8641@haskus.fr> <20170928132509.0ffcc173@Pavel> <2aab4bd9-f22c-e738-b467-1d9b7542f15d@haskus.fr> Message-ID: <20170928163019.00d48434@Pavel> > You could also avoid all this ambiguity/type application stuff with: > data AsTitle = AsTitle > class Repr a b where >   repr :: a -> b -> Repr b > instance Repr Int AsTitle where >   repr n _ = ... > ... > print (repr n AsTitle) Yes, "moving" of type from the right-side (result) to the left-side (arguments) solves the problem, sure. > (Repr b can be an associated type if you want to support different > representations) > > > > >> You only add a constraint as follows: > >> repr n :: forall b. (Repr b ~ Repr AsTitle, ReprC Int b) => Repr > >> b > > Yes... So, `b` is unbound/free type param. But I can bind it with > > func. deps, yes? > How? If you you bind it with a functional dependency on "a", you can > only have a single "b" for each "a". I don't know... I wrote to David my idea - additional param on the left-side of func. dependency, but how/what param? === Best regards, Paul