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
571e42096581aca5754d235d36ad79f1f629eb05src/NixLab/Dependent/Fuel.hs
{-# LANGUAGE DependentTypes #-}
{-# LANGUAGE ListTuplePuns #-}

-- | A program's fuel cost is computed from the program, and the evaluator
-- takes a proof that the budget covers it. Each step spends one unit, and
-- there is no out-of-fuel case to write: it cannot happen.
module NixLab.Dependent.Fuel (
    Program (..),
    cost,
    exec,
    execChecked,
) where

import Data.Nat.Dependent.Properties (decLE)
import Prelude.Dependent

-- | A forge program: a sequence of costed host commands.
data Program = Done | Step String Program

-- | Deterministic fuel needed to run a program.
cost :: Program -> Nat
cost Done = Zero
cost (Step _ p) = Succ (cost p)

-- | Run a program within a budget proven to cover it. The fuel shrinks by
-- one on every step; the proof rules out reaching zero with steps left.
exec :: foreach (p :: Program) -> foreach (fuel :: Nat) -> LE (cost p) fuel -> [String]
exec Done _ _ = []
exec (Step c p) (Succ fuel) (LESucc covered) = c : exec p fuel covered

-- | Check the budget once, at the boundary, then run with the proof.
execChecked :: Program -> Nat -> Maybe [String]
execChecked p fuel = case decLE (cost p) fuel of
    Yes covered -> Just (exec p fuel covered)
    No _ -> Nothing