Skip to content

Instantly share code, notes, and snippets.

@ocramz
Last active January 14, 2019 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ocramz/3004ea47846dc120e7c63d88ff165a87 to your computer and use it in GitHub Desktop.
Save ocramz/3004ea47846dc120e7c63d88ff165a87 to your computer and use it in GitHub Desktop.
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