Copyright | (C) 2020 Csongor Kiss |
---|---|
License | BSD3 |
Maintainer | Csongor Kiss <kiss.csongor.kiss@gmail.com> |
Stability | experimental |
Portability | non-portable |
Safe Haskell | None |
Language | Haskell2010 |
Data.Generics.Sum.Typed
Contents
Description
Derive constructor-field-type-based prisms generically.
Synopsis
- class AsType a s where
- _Typed :: Prism' s a
- injectTyped :: a -> s
- projectTyped :: s -> Maybe a
Prisms
>>>
:set -XTypeApplications
>>>
:set -XDataKinds
>>>
:set -XDeriveGeneric
>>>
import GHC.Generics
>>>
import Control.Lens
>>>
:{
data Animal = Dog Dog | Cat Name Age | Duck Age | Turtle Age deriving (Generic, Show) data Dog = MkDog { name :: Name , age :: Age } deriving (Generic, Show) type Name = String newtype Age = Age Int deriving Show dog, cat, duck :: Animal dog = Dog (MkDog "Shep" (Age 3)) cat = Cat "Mog" (Age 5) duck = Duck (Age 2)>>>
:}
class AsType a s where Source #
Types that can represent another type, either by being a sum with a constructor containing that type, or by actually being that type.
Minimal complete definition
Methods
A prism that projects a constructor uniquely identifiable by the type of
its field. Compatible with the lens package's Prism
type.
>>>
dog ^? _Typed @Dog
Just (MkDog {name = "Shep", age = Age 3})>>>
cat ^? _Typed @(Name, Age)
Just ("Mog",Age 5)>>>
dog ^? _Typed @Age
... ... ... The type Animal contains multiple constructors whose fields are of type Age. ... The choice of constructor is thus ambiguous, could be any of: ... Duck ... Turtle ...
injectTyped :: a -> s Source #
Inject by type.
>>>
:{
dog :: Dog dog = MkDog "Fido" (Age 11) dogAsAnimal :: Animal dogAsAnimal = injectTyped dog dogAsItself :: Dog dogAsItself = injectTyped dog>>>
:}
projectTyped :: s -> Maybe a Source #
Project by type.
>>>
:{
dogAsAnimal :: Animal dogAsAnimal = Dog (MkDog "Fido" (Age 11)) mDog :: Maybe Dog mDog = projectTyped dogAsAnimal>>>
:}
Instances
AsType Void a Source # | Uncluttering type signatures (see
|
Defined in Data.Generics.Sum.Typed | |
AsType a Void Source # | Uncluttering type signatures (see
|
Defined in Data.Generics.Sum.Typed | |
AsType a a Source # | Every type can be treated |
Defined in Data.Generics.Sum.Typed | |
Context a s => AsType a s Source # | |
Defined in Data.Generics.Sum.Typed |