tag:blogger.com,1999:blog-54565069790395306592015-09-16T19:17:12.902+01:00Haskell for MathsDavidAhttp://www.blogger.com/profile/15255897396572158190noreply@blogger.comBlogger2125tag:blogger.com,1999:blog-5456506979039530659.post-72469972719012484922007-08-19T20:20:00.000+01:002007-08-24T13:23:20.574+01:00What is a Ring?The concept of a ring is fundamental to advanced algebra, with applications throughout pure maths. Basically, a ring is the mathematical concept that the Haskell Num type class is trying to capture (but not quite succeeding).<br /><br />A ring is a set R with two binary operations, addition and multiplication, satisfying certain rules. Specifically:<br /><br />R is a commutative group with respect to addition<br /><ul><li>Addition is associative: a+(b+c) = (a+b)+c</li><li>There is an additive identity, 0, such that a+0 = 0+a = a</li><li>There is an additive inverse, -a, such that a+(-a) = (-a)+a = 0</li><li>Addition is commutative: a+b = b+a</li></ul>R is a semigroup with respect to multiplication<br /><ul><li>Multiplication is associative: a*(b*c) = (a*b)*c</li><li>Often, there will be a multiplicative identity, 1, such that 1*a = a*1 = a</li><li>Quite often, multiplication will be commutative</li></ul>Multiplication distributes over addition<br /><ul><li>a*(b+c) = a*b + a*c</li><li>(a+b)*c = a*c + b*c</li></ul>Now of course, there are plenty of examples of rings - in fact they're the sort of thing that we run into all the time. Here are some of the most obvious:<br /><ul><li>The integers. These are really the prototype for the concept. However the integers are actually quite a special ring, having many properties that other rings can fail to have. Part of understanding rings is understanding which properties of the integers <span style="font-style: italic;">don't</span> hold for all rings. Mathematicians use the abbreviation Z for the integers (from the German <span style="font-style: italic;">Zahlen</span>, meaning numbers)</li><li>The rational numbers (Q), real numbers (R), and complex numbers (C).</li><li>For fixed n, the set of n*n matrices. For example, the set of 2*2 matrices.</li><li>The set of polynomials in x</li></ul>And so on. It's also worth pointing out a couple of non-examples:<br /><ul><li>The natural numbers N (the positive integers). They're not a ring because we don't have additive inverses (the negative integers).</li><li>Vectors with the cross product as multiplication. The problem is that the cross product isn't associative.</li></ul>Time for some Haskell. Let's start with 2*2 matrices:<br /><pre><br />{-# OPTIONS_GHC -fglasgow-exts #-}<br /><br />module Rings where<br /><br />newtype Matrix r = M [[r]] deriving (Eq,Show)<br /><br />instance Num r => Num (Matrix r) where<br /> M [[a,b],[c,d]] + M [[a',b'],[c',d']] = M [[a+a',b+b'],[c+c',d+d']]<br /> negate (M [[a,b],[c,d]]) = M [[-a,-b],[-c,-d]]<br /> M [[a,b],[c,d]] * M [[e,f],[g,h]] = M [[a*e+b*g, a*f+b*h] ,[c*e+d*g, c*f+d*h]]<br /> fromInteger n = M [[fromInteger n, 0],[0, fromInteger n]]<br /></pre><br />It wouldn't have been much harder to handle the n*n case rather than just the 2*2 case, but I thought the code was clearer this way.<br /><br />Let's quickly test it:<br /><pre><br />> M [[1,2],[3,4]] - M [[1,0],[0,1]]<br />M [[0,2],[3,3]]<br />> M [[2,0],[0,3]] * M [[1,2],[3,4]]<br />M [[2,4],[9,12]]<br /></pre><br />Notice that in Haskell, the Num type class is what you use when you want to define a ring. It provides the (+), (-), and (*) operators that you need. We also need a way to say what the 0 and 1 are in our ring. This is what the fromInteger function is for. If we wanted, we could have just defined fromInteger 0 and fromInteger 1, and left the other cases unmatched, like so:<br /><pre><br />fromInteger 0 = M [[0,0],[0,0]]<br />fromInteger 1 = M [[1,0],[0,1]]<br /></pre><br />As far as defining a ring goes, this would have been fine. But once someone knows what fromInteger 1 is, they can use the ring laws to work out fromInteger n as follows:<br /><pre><br />fromInteger n | n >= 0 = sum $ replicate n $ fromInteger 1<br /> | otherwise = negate $ fromInteger $ negate n<br /></pre><br />So we might as well save them the trouble and just do it for them.<br /><br />Note that because Haskell will do fromInteger calls implicitly for us, we can write things like this:<br /><pre><br />> 2 * M [[1,2],[3,4]]<br />M [[2,4],[6,8]]<br /></pre><br />A couple of things to point out about the ring of 2*2 matrices:<br /><ul><li>Multiplication is not commutative</li><li>There are zero divisors - we can find matrices a/=0, b/=0 such that a*b==0<br /></li></ul><br />Okay, next, polynomials in x:<br /><pre><br />newtype UPoly a = UP [a] deriving (Eq)<br />-- the list [a_0, a_1, ..., a_n] represents the polynomial a_0 + a_1 x + ... + a_n x^n<br /><br />x = UP [0,1] :: UPoly Integer<br /><br />instance (Show a, Num a) => Show (UPoly a) where<br /> show (UP []) = "0"<br /> show (UP as) = let powers = reverse $ filter ( (/=0) . fst ) $ zip as [0..]<br /> c:cs = concatMap showTerm powers<br /> in if c == '+' then cs else c:cs<br /> where showTerm (a,i) = showCoeff a ++ showPower a i<br /> showCoeff a | a == 1 = "+"<br /> | a == -1 = "-"<br /> | otherwise = let cs = show a<br /> in if head cs == '-' then cs else '+':cs<br /> showPower a i | i == 0 = if a `elem` [1,-1] then "1" else ""<br /> | i == 1 = "x"<br /> | i > 1 = "x^" ++ show i<br /><br />instance Num a => Num (UPoly a) where<br /> UP as + UP bs = toUPoly $ as <+> bs<br /> negate (UP as) = UP $ map negate as<br /> UP as * UP bs = toUPoly $ as <*> bs<br /> fromInteger 0 = UP []<br /> fromInteger a = UP [fromInteger a]<br /><br />toUPoly as = UP (reverse (dropWhile (== 0) (reverse as)))<br /><br />(a:as) <+> (b:bs) = (a+b) : (as <+> bs)<br />as <+> [] = as<br />[] <+> bs = bs<br /><br />[] <*> _ = []<br />_ <*> [] = []<br />(a:as) <*> (b:bs) = [a*b] <+> (0 : map (a*) bs) <+> (0 : map (*b) as) <+> (0 : 0 : as <*> bs)<br /></pre><br />Quick test:<br /><pre><br />> (x+1)^3<br />x^3+3x^2+3x+1<br /></pre><br />Unlike the matrices, this ring of polynomials over the integers (which mathematicians write as Z[x]) is quite a nicely behaved ring. Multiplication is commutative, and there are no zero divisors.<br /><br />There are many other important rings. Let's look at one more: the integers modulo n (for fixed n) - also known as "clock arithmetic", and denoted Z<sub>n</sub> by mathematicians. Here I'm going to use some phantom type trickery, so the following code may not compile in all environments:<br /><br /><pre>class IntegerAsType a where<br /> value :: a -> Integer<br /><br />data T12<br />instance IntegerAsType T12 where value _ = 12<br /><br />data T10<br />instance IntegerAsType T10 where value _ = 10<br /><br />newtype Zn n = Zn Integer deriving (Eq)<br /><br />instance Show (Zn n) where<br /> show (Zn x) = show x<br /><br />instance IntegerAsType n => Num (Zn n) where<br /> Zn x + Zn y = Zn $ (x+y) `mod` value (undefined :: n)<br /> negate (Zn 0) = 0<br /> negate (Zn x) = Zn $ value (undefined :: n) - x<br /> Zn x * Zn y = Zn $ (x*y) `mod` value (undefined :: n)<br /> fromInteger n = Zn $ n `mod` value (undefined :: n)<br /></pre>When using this code, I need to make sure that the interpreter knows which type I am working in:<br /><pre><br />> 2*9 :: Zn T12<br />6<br />> 2*9 :: Zn T10<br />8<br /></pre>Z<sub>n</sub> is a commutative ring. However, when n is composite (not a prime), then it has zero divisors.<br /><br />So there you have it, a few examples of the concept of ring.<br /><br />At the beginning, I said that the Num type class didn't quite succeed at capturing the concept of ring. That's because it has a couple of other functions that we've been ignoring up to now - abs and signum. This is the little blot in Haskell's copybook. abs and signum don't have anything to do with rings. They don't make sense for most of the rings we've discussed. In fact they're only really relevant to rings which can be embedded into the complex numbers. I'm hoping that in the next version of Haskell, this little wrinkle will be ironed out.<br /><br />Next time: fieldsDavidAhttp://www.blogger.com/profile/15255897396572158190noreply@blogger.com10tag:blogger.com,1999:blog-5456506979039530659.post-57133380141813940332007-08-19T14:05:00.000+01:002007-08-19T20:25:20.010+01:00WelcomeHi there. Welcome to Haskell for Maths.<br /><br />One of my hobbies is learning maths. The areas of maths I'm most interested in are Combinatorics, Algebra and Number Theory, although I do occasionally stray into other areas too. I have a stretch target to understand Andrew Wiles' proof of Fermat's Last Theorem - but I think that may take a while.<br /><br />When I'm reading maths, I find that a good way to understand it is to write some code. For example, if I'm learning about some new algebraic structure, I might represent it in code, and then play around with some examples. That way I get a really concrete understanding of the concepts.<br /><br />The language I use is Haskell. There are two main reasons for this:<br /><ul><li>Haskell is a very mathematical language. It feels very natural to express mathematical concepts in Haskell.</li><li>Haskell is a very concise language. I can write code much faster in Haskell than in any other language I know.</li></ul><br />So anyway, if you're interested in maths then I want to share some of my Haskell code with you, and that's what this blog is all about.<br /><br />(This is my second attempt. I already published some code <a href="http://www.polyomino.f2s.com/david/haskell/main.html">here</a>. However, that project got too big, and became unmanageable. This time round I'm going to do more, smaller projects, and hopefully keep things simple. Also, my Haskell coding skills have improved, so the code should be better this time round.)<br /><br />Enjoy.DavidAhttp://www.blogger.com/profile/15255897396572158190noreply@blogger.com0