Skip to content

Instantly share code, notes, and snippets.

@Drezil
Created July 20, 2020 14:06
Show Gist options
  • Save Drezil/ea69525f038ae0ea15c0f266ecbdba31 to your computer and use it in GitHub Desktop.
Save Drezil/ea69525f038ae0ea15c0f266ecbdba31 to your computer and use it in GitHub Desktop.
Find all things of type a inside type b - dynamically at runtime.
import Data.Data
import Data.Functor.Const
import Data.Generics.Product.Types
-- This works on Data/Typeable, which is basically duck-typing from python
-- instead of GHC.Generics which work only at compile-time & have no runtime-cost.
extractAny :: (Data a, Typeable b) => a -> [b]
extractAny = getConst . gfoldl (\xs d -> case cast d of
Just a -> Const (a:getConst xs)
Nothing -> Const (extractAny d <> getConst xs)
) (\_ -> Const [])
-- use like this (implying JobPosting & PostalAddress exist & parsed :: [JobPosting])
main = print (extractAny @[JobPosting] @PostalAddress parsed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment