Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As you have specified it, the <code>OrdByKey</code> class can only have one instance per type, when it sounds like you would like to be able to declare an instance for each field in your record type. </p> <p>To accomplish that, you will have to put the field type into the class definition as well. This lets you do something like the following:</p> <pre><code>{-# LANGUAGE MultiParamTypeClasses #-} data Person = Person { name :: String, age :: Int } class (Ord r) =&gt; OrdByKey o r where orderKey :: o -&gt; r instance OrdByKey Person Int where orderKey p = age p x &lt;=? y = (orderKey x :: Int) &lt;= (orderKey y :: Int) </code></pre> <p>However, you can only have one instance per field type, so if your <code>Person</code> type looks like</p> <pre><code>data Person = Person { name :: String, age :: Int, ssn :: String} </code></pre> <p>you will not be able to have a version to compare on both the <code>name</code> and the <code>ssn</code> fields. You could get around this by wrapping each field in a <code>newtype</code> so each field has a unique type. So your <code>Person</code> type would look like</p> <pre><code>data Person = Person { name :: Name, age :: Age, ssn :: SSN} </code></pre> <p>That would lead to a lot of <code>newtypes</code> floating around though.</p> <p>The real downside of this is the need to specify the return type for the <code>orderKey</code> function. I would recommend using the <code>on</code> function from <code>Data.Function</code> to write the appropriate comparison functions. I think a function like </p> <pre><code>compareByKey :: (Ord b) =&gt; (a -&gt; b) -&gt; a -&gt; a -&gt; Bool compareByKey = on (&lt;=) </code></pre> <p>generalizes your idea of "can be compared by some key". You just have to give it the function that extracts that key, which would be exactly the accessor functions for your <code>Person</code> type, in this case.</p> <p>I can't think of an instance where the <code>OrdByKey</code> class would be useful and trying to overload the <code>&lt;=</code> with multiple versions for the same type seems like it would be down right confusing in practice.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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