Article View: comp.lang.functional
Article #1135Re: Haskell Operator Overloading. (Very) trivial newbie question.
From: Adam P. Jenkins
Date: Tue, 02 Mar 1999 00:00
Date: Tue, 02 Mar 1999 00:00
46 lines
2660 bytes
2660 bytes
"James" <reply@newsgroup.com> writes: > Hello, > > The following is not a homework question, just something that has been > testing my patience. I have an algorithm that sorts a list of pairs. Say one > instance of the input is of type, > > :: ((a,a),(a,a)) > > I find that if I use the derived ordering it sorts, but the result is not > what I want. I want to introduce an ordering based on a function I already > have. For example a metric on the above input with type, > > :: Floating a => ((a,a),(a,a)) -> a > > My understanding is that I should be able to achieve this by operator > overloading. I have looked at both the gentle intro and the Hugs prelude but > have just not had much success expressing it precisely in Haskell. > > An example from any of you would be greatly appreciated. First of all, overloading the comparison operators for your type is only appropriate if you want to change the ordering for your type everywhere in your program. If you just want to sort differently, then use the sortBy function instead of sort. sortBy takes a comparison function as an argument, so you can just pass your existing comparison function. If you do want to overload, you need to create a new type first, using the data or newtype keyword. You can't just overload type Floating a => ((a,a), (a,a)) because that's an existing type. You'd need to define something like newtype Floating a => MyType a = Pair ((a,a), (a,a)) Now you can create instances of Eq and Ord for (MyType a) that do what you want. Note that for Eq you only need to define (==), and for Ord you only need to define (<=) or compare. The rest of the methods come "for free". See the Haskell 98 Report at www.haskell.org for details. Also, if you use hugs, just look at it's Prelude.hs for examples of how to define instances of Eq and Ord. -- Adam P. Jenkins ajenkins@netway.com
Technical Details
Message-ID:
<yzh7lsz32f1.fsf@xcom-79-181.mdc.net>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<7bhonu$qto$1@news8.svr.pol.co.uk>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 107f24,96995099712e3974 X-Google-Attributes: gid107f24,public X-Google-Thread: 10707f,96995099712e3974 X-Google-Attributes: gid10707f,public From: ajenkins@netway.com (Adam P. Jenkins) Subject: Re: Haskell Operator Overloading. (Very) trivial newbie question. Date: 1999/03/02 Message-ID: <yzh7lsz32f1.fsf@xcom-79-181.mdc.net> X-Deja-AN: 450541324 Sender: ajenkins@xcom-79-181.mdc.net References: <7bhonu$qto$1@news8.svr.pol.co.uk> X-Trace: newsfeed.slurp.net 920416799 209.251.79.181 (Tue, 02 Mar 1999 17:19:59 CDT) Organization: ChainWave Systems, Inc., Lexington, MA NNTP-Posting-Date: Tue, 02 Mar 1999 17:19:59 CDT Newsgroups: comp.lang.functional,fa.haskell