https://github.com/justinwoo/purescript-kishimen
Sum types with Generics-Rep instances to Variant for free!
https://github.com/justinwoo/purescript-kishimen
purescript
Last synced: 8 months ago
JSON representation
Sum types with Generics-Rep instances to Variant for free!
- Host: GitHub
- URL: https://github.com/justinwoo/purescript-kishimen
- Owner: justinwoo
- License: mit
- Created: 2019-02-19T00:06:52.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2021-12-15T13:00:26.000Z (over 4 years ago)
- Last Synced: 2025-09-18T11:27:59.983Z (9 months ago)
- Topics: purescript
- Language: PureScript
- Homepage:
- Size: 8.79 KB
- Stars: 8
- Watchers: 3
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# PureScript-Kishimen
## aka PureScript-Dan-Abramov
 
Sum types with Generics-Rep instances to Variant for free!
## Usage
First, make a sum type of zero or one argument constructors, and derive generic:
```purs
data Fruit = Apple | Banana Int | Kiwi String
derive instance genericFruit :: Generic Fruit _
```
Then use `genericSumToVariant`:
```purs
main :: Effect Unit
main = do
logShow $ genericSumToVariant Apple
logShow $ genericSumToVariant (Banana 3)
logShow $ genericSumToVariant (Kiwi "green")
-- results:
-- (inj @"Apple" {})
-- (inj @"Banana" 3)
-- (inj @"Kiwi" "green")
log $ JSON.writeJSON $ genericSumToVariant Apple
log $ JSON.writeJSON $ genericSumToVariant (Banana 3)
log $ JSON.writeJSON $ genericSumToVariant (Kiwi "green")
-- results:
-- {"type":"Apple","value":{}}
-- {"type":"Banana","value":3}
-- {"type":"Kiwi","value":"green"}
```
Amazing!
## How?
You can see the inferred type in the expectInferred test:
```purs
test1 :: Unit
test1 = expectInferred expectedP simpleValue
where
expectedP = Proxy :: _
(Variant
( "Apple" :: {}
, "Banana" :: Int
, "Kiwi" :: String
))
simpleValue = genericSumToVariant Apple
```