title: Functors and Applicatives for types of kind (* -> *) -> *
body: <p>I ran into a situation where my code would benefit from using <code>Functor</code> and <code>Applicative</code> -like abstractions, but for types of kind <code>(* -&gt; *) -&gt; *</code>. Defining a higher-kinded functor can be done with <code>RankNTypes</code> like this</p>
  
  <pre><code>class HFunctor f where
      hfmap :: (forall x. a x -&gt; b x) -&gt; f a -&gt; f b
  </code></pre>
  
  <p>But the higher kind version of <code>Applicative</code> is a bit trickier. This is the best I could come up with:</p>
  
  <pre><code>class HFunctor f =&gt; HApplicative f where
      hpure  :: (forall x. a x) -&gt; f a
      (&lt;**&gt;) :: f (a :-&gt; b) -&gt; f a -&gt; f b
  
  newtype (:-&gt;) a b x = HFunc (a x -&gt; b x)
  
  infixr 5 :-&gt;
  </code></pre>
  
  <p>We need the <code>:-&gt;</code> wrapper type in order to have functions with the kind <code>* -&gt; *</code>, but this doesn't let us nicely chain function application like we can with <code>&lt;$&gt;</code> and <code>&lt;*&gt;</code> for normal Applicatives. I can manage with helper such as</p>
  
  <pre><code>liftHA2 :: HApplicative f =&gt; (forall x. a x -&gt; b x -&gt; c x) -&gt; f a -&gt; f b -&gt; f c
  liftHA2 f fa fb = hpure (fun2 f) &lt;**&gt; fa &lt;**&gt; fb where
      fun2 = HFunc . (HFunc .)
  </code></pre>
  
  <p>But it would be nice to have a general way to "lift" functions of any arity.</p>
  
  <p>Some simple examples how the above instances can be used:</p>
  
  <pre><code>data Example f = Example (f Int) (f String)
  
  instance HFunctor Example where
      hfmap f (Example i s) = Example (f i) (f s)
  
  instance HApplicative Example where
      hpure a = Example a a
      Example (HFunc fi) (HFunc fs) &lt;**&gt; Example i s = Example (fi i) (fs s)
  
  e :: Example []
  e = Example [1,2,3] ["foo", "bar"]
  
  e' :: Example ((,) Int)
  e' = hfmap (length &amp;&amp;&amp; head) e  -- Example (3,1) (2, "foo")
  
  e'' :: Example []
  e'' = liftHA2 (++) e e  -- Example [1,2,3,1,2,3] ["foo", "bar", "foo", "bar"]
  </code></pre>
  
  <p>So, my question is: what are the above typeclasses called and are they already provided by some library in hackage? By googling I came up with <code>Functor2</code> in <a href="http://hackage.haskell.org/packages/archive/linear-maps/0.6.1/doc/html/Control-Functor.html"><code>linear-maps</code></a> and <code>HFunctor</code>in <a href="http://hackage.haskell.org/packages/archive/multirec/0.7.2/doc/html/Generics-MultiRec-HFunctor.html"><code>multi-rec</code></a> but neither does exactly what I need.</p>
  
  <p>Also, is there some way to write <code>HApplicative</code> without the <code>:-&gt;</code> wrapper or some other way to make function lifting easier?</p>