Note that there are some explanatory texts on larger screens.

plurals
  1. PODeclaring a type class for multiplication of an N-by-N-element matrix and an N-element column vector
    text
    copied!<p>In Haskell, if you have a "family" of types (say, N-by-N-element matrices, for some values of N), and a parallel family of "related" types (say, N-element vectors, for the same values of N), and an operation that requires one specific type from each family (say, multiplying an N-by-N-element matrix and an N-element column vector), is it then possible to declare a type class for that operation?</p> <p>For this specific example, I imagine it would look something like this:</p> <pre><code>class MatrixNxN m where --| Multiplication of two N-by-N-element matrices mmul :: Num a =&gt; m a -&gt; m a -&gt; m a --| Multiplication of an N-by-N-element matrix and an N-element column vector vmul :: Num a =&gt; m a -&gt; v a -&gt; v a </code></pre> <p>I don't know how to constrain the type <code>v</code>, however. Is it possible to do something like this?</p> <p>Please note that I welcome both answers to the general question of declaring a type class of multiple, related types, as well as answers to the specific question of declaring a type class for matrix-vector multiplication. In my specific case, there is only a small, known set of values of N (2, 3, and 4), but I'm generally interested in understanding what is possible to encode in Haskell's type system.</p> <p><strong>EDIT:</strong> I implemented this using <a href="http://www.haskell.org/haskellwiki/Multi-parameter_type_class" rel="nofollow"><code>MultiParamTypeClasses</code></a> and <a href="http://www.haskell.org/haskellwiki/Functional_dependencies" rel="nofollow"><code>FunctionalDependencies</code></a> as suggested by Gabriel Gonzalez and MFlamer below. This is what the relevant bits of my implementation ended up looking like:</p> <pre><code>class MatrixVectorMultiplication m v | m -&gt; v, v -&gt; m where vmul :: Num a =&gt; m a -&gt; v a -&gt; v a data Matrix3x3 a = ... data Vector3 a = ... instance MatrixVectorMultiplication Matrix3x3 Vector3 where vmul = ... </code></pre> <p>This is the type signature of <code>vmul</code>, on its own and partially applied:</p> <pre><code>vmul :: (Num a, MatrixVectorMultiplication m v) =&gt; m a -&gt; v a -&gt; v a (`vmul` v) :: Matrix3x3 Integer -&gt; Vector3 Integer (m `vmul`) :: Vector3 Integer -&gt; Vector3 Integer </code></pre> <p>I find this all very elegant. Thanks for the answers! :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload