Last active
July 23, 2020 03:03
-
-
Save anthonyjoeseph/314b8f623b7f672524be38b070d5d888 to your computer and use it in GitHub Desktop.
Composing Optionals across a Morphic ADT
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 { pipe } from 'fp-ts/lib/pipeable' | |
import * as L from 'monocle-ts/lib/Lens' | |
import * as Op from 'monocle-ts/lib/Optional' | |
import { makeADT, ofType, ADTType } from '@morphic-ts/adt' | |
interface Bicycle { | |
type: 'Bicycle' | |
color: string | |
} | |
interface Motorbike { | |
type: 'Motorbike' | |
seats: number | |
} | |
interface Car { | |
type: 'Car' | |
kind: 'electric' | 'fuel' | 'gaz' | |
attributes: { | |
power: number | |
seats: number | |
} | |
} | |
const Vehicle = makeADT('type')({ | |
Car: ofType<Car>(), | |
Motorbike: ofType<Motorbike>(), | |
Bicycle: ofType<Bicycle>() | |
}) | |
type Vehicle = ADTType<typeof Vehicle> | |
const fromMotorbike = pipe( | |
L.id<Motorbike>(), | |
L.prop('seats'), | |
L.asOptional, | |
) | |
const fromCar = pipe( | |
L.id<Car>(), | |
L.prop('attributes'), | |
L.prop('seats'), | |
L.asOptional, | |
) | |
const seatOptional: Op.Optional<Vehicle, number> = { | |
getOption: Vehicle.match({ | |
Motorbike: fromMotorbike.getOption, | |
Car: fromCar.getOption, | |
}, _ => O.none), | |
set: (a) => Vehicle.transform({ | |
Motorbike: fromMotorbike.set(a), | |
Car: fromCar.set(a), | |
}), | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment