NixLabConnectionconnecting
ProjectsProject
horizon /

dependent-nixlab-examples

publicguest

Worked examples of where dependent types help NixLab.

git clone git@nixlab.openfp.net:horizon/dependent-nixlab-examples.git
{-# LANGUAGE DependentTypes #-}
{-# LANGUAGE ListTuplePuns #-}

-- | A schema is an ordinary value; the Haskell type of a field is computed
-- from it, so decoders and printers need no generated modules.
module NixLab.Dependent.Schema (
    Ty (..),
    interp,
    Value (..),
    decode,
    encode,
) where

import Data.List (List)
import Data.Text (Text)
import Prelude.Dependent
import Prelude qualified as P

-- | Field types of a Vortex schema.
data Ty = TInt | TText | TBool | TList Ty | TMaybe Ty

-- | The Haskell type a schema field denotes.
interp :: Ty -> Type
interp TInt = Int
interp TText = Text
interp TBool = Bool
interp (TList t) = List (interp t)
interp (TMaybe t) = Maybe (interp t)

-- | Untyped values as the Vortex reader produces them.
data Value = VInt Int | VText Text | VBool Bool | VList [Value] | VNull

-- | Decode an untyped value against a schema chosen at runtime.
decode :: foreach (t :: Ty) -> Value -> Maybe (interp t)
decode TInt (VInt i) = Just i
decode TText (VText s) = Just s
decode TBool (VBool b) = Just b
decode (TList t) (VList vs) = P.traverse (decode t) vs
decode (TMaybe _) VNull = Just Nothing
decode (TMaybe t) v = P.fmap Just (decode t v)
decode _ _ = Nothing

-- | Encode a typed value; the schema fixes which value is accepted.
encode :: foreach (t :: Ty) -> interp t -> Value
encode TInt i = VInt i
encode TText s = VText s
encode TBool b = VBool b
encode (TList t) xs = VList (P.map (encode t) xs)
encode (TMaybe _) Nothing = VNull
encode (TMaybe t) (Just x) = encode t x