Created
November 8, 2018 03:44
-
-
Save adamczykm/9f37fe7a91721e206adaa2492d68d206 to your computer and use it in GitHub Desktop.
A class for types that supports default values.
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
module Default where | |
import Control.Category (identity, (<<<)) | |
import Data.Maybe (Maybe(..)) | |
import Data.Symbol (class IsSymbol, SProxy(..)) | |
import Data.Tuple (Tuple(..)) | |
import Prim.Row as Row | |
import Prim.RowList (class RowToList, Cons, Nil, kind RowList) | |
import Record.Builder (Builder) | |
import Record.Builder as Builder | |
import Type.Data.RowList (RLProxy(..)) | |
class HasDefault a where | |
default :: a | |
instance defaultNothing :: HasDefault (Maybe a) where | |
default = Nothing | |
instance tupleHasDefault :: | |
( HasDefault a | |
, HasDefault b | |
) => HasDefault (Tuple a b) where | |
default = Tuple default default | |
instance recordWriteForeign :: | |
( RowToList row rl | |
, HasDefaultFields rl () row | |
) => HasDefault (Record row) where | |
default = Builder.build (defaultFields (RLProxy :: RLProxy rl)) {} | |
class HasDefaultFields | |
(rl :: RowList) (from :: # Type) (to :: # Type) | |
| rl -> from to where | |
defaultFields :: forall g. g rl -> Builder (Record from) (Record to) | |
instance defaultFieldsNil :: | |
HasDefaultFields Nil () () where | |
defaultFields _ = identity | |
instance readFieldsCons :: | |
( IsSymbol name | |
, HasDefault ty | |
, HasDefaultFields tail from from' | |
, Row.Lacks name from' | |
, Row.Cons name ty from' to | |
) => HasDefaultFields (Cons name ty tail) from to where | |
defaultFields _ = | |
let | |
first :: Builder (Record from') (Record to) | |
first = Builder.insert (SProxy :: SProxy name) default | |
in | |
first <<< defaultFields (RLProxy :: RLProxy tail) | |
--------------------------------------- | |
----- USAGE : | |
data Switch = On | Off | |
instance hasDefaultSwitch :: HasDefault Switch | |
where | |
default = Off | |
testX :: {a :: { b :: Maybe Int, c :: Tuple Switch Switch}} | |
testX = default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment