Hi guys,<br><br>Sorry for a silly questions but I didn&#39;t find a proper answer in Google. I&#39;ve started to learn Haskell and would like to implement a library for work with vectors. I found different implementations of this stuff but all of them made just for fun in a short as possible terms using lists or tuples. I suppose there should be a better way to go. First idea came to my mind was using of classes. Something like this:<br>
<br>[code]<br>-- Template Vector class<br><br>class Vector v where<br>&nbsp;&nbsp;&nbsp;&nbsp;(&lt;+&gt;) &nbsp;&nbsp;&nbsp; :: v -&gt; v -&gt; v<br>&nbsp;&nbsp;&nbsp;&nbsp;(&lt;-&gt;) &nbsp;&nbsp;&nbsp;&nbsp;:: v -&gt; v -&gt; v<br>&nbsp;&nbsp;&nbsp;&nbsp;(&lt;*&gt;)&nbsp;&nbsp;&nbsp;&nbsp;:: v -&gt; v -&gt; v<br>&nbsp;&nbsp;&nbsp;&nbsp;(*&gt;)&nbsp;&nbsp;&nbsp;&nbsp;:: v -&gt; Float -&gt; v<br>
&nbsp;&nbsp;&nbsp;&nbsp;-- other methods here<br><br>-- Vector3 instance<br><br>-- Declare new Vector3 type<br><br>data Vector3 = Vector3 (Float, Float, Float)<br><br>instance Vector Vector3 where<br>&nbsp;&nbsp;&nbsp;&nbsp;(&lt;+&gt;) (Vector3 (x1, y1, z1)) (Vector3 (x2, y2, z2)) = Vector3 (x1 + x2, y1 + y2, z1 + z2)<br>
&nbsp;&nbsp;&nbsp;&nbsp;(&lt;-&gt;) (Vector3 (x1, y1, z1)) (Vector3 (x2, y2, z2)) = Vector3 (x1 - x2, y1 - y2, z1 - z2)<br>&nbsp;&nbsp;&nbsp;&nbsp;(&lt;*&gt;) (Vector3 (x1, y1, z1)) (Vector3 (x2, y2, z2)) = Vector3 (x1 * x2, y1 * y2, z1 * z2)<br>&nbsp;&nbsp;&nbsp;&nbsp;(*&gt;) (Vector3 (x, y, z)) f = Vector3 (x * f, y * f, z * f)<br>
&nbsp;&nbsp;&nbsp;&nbsp;length (Vector3 (x, y, z)) = sqrt (x * x + y * y + z * z)<br>&nbsp;&nbsp;&nbsp; -- the rest of methods<br>[/code]<br><br>What I don&#39;t like here is using of data type constructors when even simple expression like v1 + v2 becomes too long (&lt;+&gt;) (Vector3 (1,2,3)) (Vector3 (4,5,6))<br>
Do I really need a data type constructor (in this particular case)? Or better to declare a vector3 type as: type Vector3 = (Float, Float, Float)?<br>Next question is how to make one instance which derives from several classes? For example from Eq, Num and Vector (if I want to overload +, -, &lt;, &gt;, == etc.)<br>
Is it good idea to use classes and ad hoc polymorphism or better to use parametric polymorphism? How you would implement such library? (not just for educational purposes but for development of _very_good_extensible_ software)<br>
<br>Thank you,<br>Alex.<br>