Last active
January 14, 2019 11:08
-
-
Save ocramz/3004ea47846dc120e7c63d88ff165a87 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 qualified GHC.Generics as G | |
-- | generics-sop | |
import Generics.SOP | |
import Generics.SOP.NP (collapse_NP) | |
-- | Python in Haskell yay! | |
-- | |
-- Example : | |
-- >>> data P = P { unP1 :: Int , unP2 :: Char } deriving (G.Generic) | |
-- >>> instance Generic P | |
-- | |
-- >>> > npToValue $ P 42 'z' | |
-- >>> [VInt 42,VChar 'z'] | |
npToValue :: (Generic a, All ToValue xs, Code a ~ '[xs]) => a -> [Value] | |
npToValue = collapse_NP . gMapToValue . gToList | |
data Value = VInt Int | VDouble Double | VText T.Text | VChar Char deriving (Eq, Show) | |
class ToValue v where | |
toValue :: v -> Value | |
instance ToValue Int where toValue = VInt | |
instance ToValue Double where toValue = VDouble | |
instance ToValue T.Text where toValue = VText | |
instance ToValue Char where toValue = VChar | |
-- | This is a slight specialization of the signature inferred by GHC | |
gMapToValue :: All ToValue xs => NP I xs -> NP (K Value) xs | |
gMapToValue d = hcmap (Proxy :: Proxy ToValue) (mapIK toValue) d | |
-- | Compute the generic representation and unpack | |
gToList :: (Generic a, Code a ~ '[x]) => a -> NP I x | |
gToList d = unZ $ unSOP (from d) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment