Created
July 20, 2020 14:06
-
-
Save Drezil/ea69525f038ae0ea15c0f266ecbdba31 to your computer and use it in GitHub Desktop.
Find all things of type a inside type b - dynamically at runtime.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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