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
module Optional where

import Builder
import GHC.Records (getField)
import MyPrelude

newtype Optional a = OptionalInternal (Maybe a)
  deriving newtype (Functor)

mkOptional :: a -> Optional a
mkOptional defaultValue = OptionalInternal $ Just defaultValue

defaults :: Optional a
defaults = OptionalInternal Nothing

optionalB :: (forall x. Build Byt x) -> Build Byt a -> Build Byt (Optional a)
optionalB (Build x) (Build a) = Build $ (\opt -> (fmap a opt).withDefault (x absurd))

-- optionalB' :: Build to from -> Build to (Optional from)
-- optionalB' (Build x) (Build a) = Build $ \opt -> todo

instance HasField "withDefault" (Optional a) (a -> a) where
  getField (OptionalInternal m) defaultValue = case m of
    Nothing -> defaultValue
    Just a -> a