Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Biased am I, but I think this is a great opportunity to make use of <a href="http://hackage.haskell.org/packages/archive/newtype/0.2/doc/html/Control-Newtype.html" rel="noreferrer">Control.Newtype</a>, a little piece of kit that's a mere "cabal install newtype" away.</p> <p>Here's the deal. You want to flip around type constructors to get your hands on functoriality (for example) in a different parameter. Define a newtype</p> <pre><code> newtype Flip f x y = Flip (f y x) </code></pre> <p>and add it to the <code>Newtype</code> class thus</p> <pre><code> instance Newtype (Flip f x y) (f y x) where pack = Flip unpack (Flip z) = z </code></pre> <p>The <code>Newtype</code> class is just a directory mapping newtypes to their unvarnished equivalents, providing handy kit, e.g. <code>op Flip</code> is the inverse of <code>Flip</code>: you don't need to remember what you called it.</p> <p>For the problem in question, we can now do stuff like this:</p> <pre><code> data Bif x y = BNil | BCons x y (Bif x y) deriving Show </code></pre> <p>That's a two parameter datatype which happens to be functorial in both parameters. (Probably, we should make it an instance of a Bifunctor class, but anyway...) We can make it a <code>Functor</code> twice over: once for the last parameter...</p> <pre><code>instance Functor (Bif x) where fmap f BNil = BNil fmap f (BCons x y b) = BCons x (f y) (fmap f b) </code></pre> <p>...and once for the first:</p> <pre><code>instance Functor (Flip Bif y) where fmap f (Flip BNil) = Flip BNil fmap f (Flip (BCons x y b)) = Flip (BCons (f x) y (under Flip (fmap f) b)) </code></pre> <p>where <code>under p f</code> is a neat way to say <code>op p . f . p</code>.</p> <p>I tell you no lies: let us try.</p> <pre><code>someBif :: Bif Int Char someBif = BCons 1 'a' (BCons 2 'b' (BCons 3 'c' BNil)) </code></pre> <p>and then we get</p> <pre><code>*Flip&gt; fmap succ someBif BCons 1 'b' (BCons 2 'c' (BCons 3 'd' BNil)) *Flip&gt; under Flip (fmap succ) someBif BCons 2 'a' (BCons 3 'b' (BCons 4 'c' BNil)) </code></pre> <p>In these circumstances, there really are many ways the same thing can be seen as a <code>Functor</code>, so it's right that we have to make some noise to say which way we mean. But the noise isn't all that much if you're systematic about it.</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