Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deriving Filterable: add an instance for Generically1 #89

Open
Icelandjack opened this issue Sep 12, 2022 · 1 comment
Open

Deriving Filterable: add an instance for Generically1 #89

Icelandjack opened this issue Sep 12, 2022 · 1 comment

Comments

@Icelandjack
Copy link

Icelandjack commented Sep 12, 2022

Since Filterable has instances for all the polynomial functors except Par1/Identity it can be given a Generically1 f instance. It was added in base-4.17.0.0, for earlier versions you can use the generically package.

instance (Generic1 f, Filterable (Rep1 f)) => Filterable (Generically1 f) where
  mapMaybe :: (a -> Maybe b) -> Generically1 f a -> Generically1 f b
  mapMaybe f (Generically1 as) = Generically1 (to1 (mapMaybe f (from1 as)))

  catMaybes :: Generically1 f (Maybe a) -> Generically1 f a
  catMaybes (Generically1 as) = Generically1 (to1 (catMaybes (from1 as)))

  filter :: (a -> Bool) -> Generically1 f a -> Generically1 f a
  filter pred (Generically1 as) = Generically1 (to1 (filter pred (from1 as)))

This allows deriving Filterable for generic types

-- >> filter isLower (Yah "Hello!")
-- Yah "ello"
-- >> filter isLower Nah
-- Nah
type Opt :: Type -> Type
data Opt a = Nah | Yah [a]
  deriving stock (Show, Generic1)
  deriving (Functor, Filterable) via Generically1 Opt
 
-- >> filter isLower (Both ["Hello!", "my"] ["BEAUTIFUL!", "World!"])
-- Both ["ello","my"] ["","orld"]
type Both :: Type -> Type
data Both a = Both [[a]] [[a]]
  deriving stock (Show, Generic1)
  deriving (Functor, Filterable) via Generically1 Both

The same can be done for Witherable but only once there is a Traversable (Generically1 t) instance.

This can wait since neither Traversable nor Witherable are coerce-derivable at the moment but I am working on allowing them to be derived.

@fumieval
Copy link
Owner

Interesting. I wonder if there's a place for orphan instances anticipated to be official; we don't have to wait if there is one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants