-
Notifications
You must be signed in to change notification settings - Fork 4
/
Person.hs
122 lines (112 loc) · 3.07 KB
/
Person.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
module Person where
import Data.Generics.Labels ()
import GHC.Generics
import qualified Generics.SOP as SOP
import Schemas
import Schemas.SOP
data Education = NoEducation | Degree {unDegree :: String} | PhD {unPhD :: String}
deriving (Generic, Eq, Show)
instance HasSchema Education where
schema = union
[("NoEducation", alt #_NoEducation)
,("PhD", alt #_PhD)
,("Degree", alt #_Degree)
]
data Person = Person
{ name :: String
, age :: Int
, addresses :: [String]
, studies :: Education
}
deriving (Generic, Eq, Show)
deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)
instance HasSchema Person where
schema = gSchema defOptions
pepe :: Person
pepe = Person
"Pepe"
38
["2 Edward Square", "La Mar 10"]
(PhD "Computer Science")
-- >>> import Data.Aeson.Encode.Pretty
-- >>> import qualified Data.ByteString.Lazy.Char8 as B
-- >>> B.putStrLn $ encodePretty $ encode pepe
-- {
-- "addresses": [
-- "2 Edward Square",
-- "La Mar 10"
-- ],
-- "age": 38,
-- "studies": {
-- "PhD": "Computer Science"
-- },
-- "name": "Pepe"
-- }
-- >>> B.putStrLn $ encodePretty $ encode (schemaFor @Person)
-- {
-- "Record": {
-- "addresses": {
-- "schema": {
-- "Array": {
-- "Prim": "String"
-- }
-- }
-- },
-- "age": {
-- "schema": {
-- "Prim": "Integer"
-- }
-- },
-- "studies": {
-- "schema": {
-- "Union": [
-- {
-- "schema": {
-- "Prim": "String"
-- },
-- "constructor": "Degree"
-- },
-- {
-- "schema": {
-- "Prim": "String"
-- },
-- "constructor": "PhD"
-- },
-- {
-- "schema": {
-- "Record": {}
-- },
-- "constructor": "NoEducation"
-- }
-- ]
-- }
-- },
-- "name": {
-- "schema": {
-- "Prim": "String"
-- }
-- }
-- }
-- }
-- >>> import Text.Pretty.Simple
-- >>> pPrintNoColor $ decode @Person $ encode pepe
-- Right
-- ( Person
-- { name = "Pepe"
-- , age = 38
-- , addresses =
-- [ "2 Edward Square"
-- , "La Mar 10"
-- ]
-- , studies =
-- ( PhD { unPhD = "Computer Science" } )
-- }
-- )