How to create a Mk instance for GHC.Generics.U1?

62 views Asked by At

I'm working through content at the blog posting Building data constructors with GHC Generics. My previous question is here.

The posting has the following code to create a Rep:

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
{-# LANGUAGE TypeOperators #-}

import GHC.Generics
import Data.Functor.Compose

class Functor f => Mk rep f | rep -> f where
  mk :: f (rep a)

instance Mk (K1 i c) ((->) c) where
  mk = \x -> K1 x

instance (Mk l fl, Mk r fr) => Mk (l :*: r) (Compose fl fr) where
  mk = Compose (fmap (\l -> fmap (\r -> l :*: r) mk) mk)

instance (Mk f f') => Mk (M1 i c f) f' where
  mk = M1 <$> mk

Is it possible to create a similar instance for U1? If so, how?

1

There are 1 answers

0
Cactus On

Since U1 has no structure, you should be able to mk one out of thin air in Identity:

import Control.Monad.Identity

instance Mk U1 Identity where
    mk = pure U1