Construct a Haskell GADT (Generalized Algebraic Data Type) that enforces type-safe…
- User
Construct a Haskell GADT (Generalized Algebraic Data Type) that enforces type-safe expression evaluation for a simple calculator DSL (Int vs Bool).
Assistant
Construct a Haskell GADT (Generalized Algebraic Data Type) that enforces type-safe expression evaluation for a simple calculator DSL (Int vs Bool).
1. Understand the Goal: The user wants a Haskell GADT (Generalized Algebraic Data Type) representing a simple calculator DSL. This DSL needs to handle both Int and Bool types in a type-safe way (i.e., preventing ill-typed expressions like adding an integer to a boolean at compile time).
Identify Key Concepts:
LitInt 1 :+: LitBool True should fail to compile.a representing the type of the expression (e.g., Expr Int, Expr Bool).Design the GADT Structure:
Expr a.LitInt :: Int -> Expr IntLitBool :: Bool -> Expr BoolAdd :: Expr Int -> Expr Int -> Expr IntGt :: Expr Int -> Expr Int -> Expr BoolAnd :: Expr Bool -> Expr Bool -> Expr BoolIf :: Expr Bool -> Expr a -> Expr a -> Expr aRefine the Operations (Standard approach vs. Type Classes):
Add, Mul, And, Or etc. This is clearer for a tutorial example.Drafting the Code (Mental or Scratchpad):
{-# LANGUAGE GADTs #-}
data Expr a where
LitInt :: Int -> Expr Int
LitBool :: Bool -> Expr Bool
Add :: Expr Int -> Expr Int -> Expr Int
Mul :: Expr Int -> Expr Int -> Expr Int
IsZero :: Expr Int -> Expr Bool -- Useful for conversion
If :: Expr Bool -> Expr a -> Expr a -> Expr a
Adding an Evaluator:
eval :: Expr a -> a.eval (LitInt i) = ieval (Add e1 e2) = eval e1 + eval e2eval (If cond t f) = if eval cond then eval t else eval fRefining for the Prompt:
Structuring the Explanation:
Expr GADT.eval function.Self-Correction/Edge Cases:
Eq instance for Expr? Not strictly necessary, but nice.StandAloneDeriving. I'll skip deriving instances to keep the code focused on the core logic, or just implement a simple Show for the REPL experience.Lt (Less Than) to show Expr Int -> Expr Int -> Expr Bool.Final Code Plan:
GADTsExpr aLitInt :: Int -> Expr IntLitBool :: Bool -> Expr BoolAdd :: Expr Int -> Expr Int -> Expr IntMul :: Expr Int -> Expr Int -> Expr IntLt :: Expr Int -> Expr Int -> Expr Bool (Int to Bool transition)If :: Expr Bool -> Expr a -> Expr a -> Expr a (Polymorphic result)eval :: Expr a -> aWriting the Response: (Proceeding to generate output based on these steps.)
where keyword).Add forces Int).eval function to show how the types align perfectly.Review against constraints:
This looks solid. I will present the solution clearly with comments. Here is a complete Haskell example implementing a simple DSL that enforces type safety (preventing you from adding Integers to Booleans) at compile time using a GADT.
{-# LANGUAGE GADTs #-}
-- We need this to derive Show automatically for GADTs
{-# LANGUAGE StandaloneDeriving #-}
module CalculatorDSL where
-- | The GADT definition.
-- The parameter 'a' represents the *result type* of the expression.
data Expr a where
-- 1. Literal values construct an expression of their specific type
LitInt :: Int -> Expr Int
LitBool :: Bool -> Expr Bool
-- 2. Arithmetic operations only work on Ints and return Ints
Add :: Expr Int -> Expr Int -> Expr Int
Mul :: Expr Int -> Expr Int -> Expr Int
-- 3. Comparison operations take Ints but return a Bool
-- This allows us to mix types in a controlled, type-safe way.
Equal :: Expr Int -> Expr Int -> Expr Bool
LessThan :: Expr Int -> Expr Int -> Expr Bool
-- 4. Logic operations only work on Bools and return Bools
And :: Expr Bool -> Expr Bool -> Expr Bool
Or :: Expr Bool -> Expr Bool -> Expr Bool
-- 5. Conditional: The condition must be Bool,
-- but the branches can be any type 'a', as long as they match.
If :: Expr Bool -> Expr a -> Expr a -> Expr a
-- Deriving Show instances for debugging (requires StandaloneDeriving)
deriving instance Show (Expr a)
-- | The Evaluator.
-- Because the GADT constrains the types, the evaluator is straightforward and
-- does not need error handling for type mismatches (e.g. "Adding Int to Bool").
-- The compiler guarantees that situation is impossible.
eval :: Expr a -> a
eval expr = case expr of
LitInt i -> i
LitBool b -> b
Add e1 e2 -> eval e1 + eval e2
Mul e1 e2 -> eval e1 * eval e2
Equal e1 e2 -> eval e1 == eval e2
LessThan e1 e2 -> eval e1 < eval e2
And e1 e2 -> eval e1 && eval e2
Or e1 e2 -> eval e1 || eval e2
If cond t f -> if eval cond then eval t else eval f
The magic of the GADT is that it allows us to specify exactly what types go in and come out for each constructor.
If you try to construct an invalid expression, the compiler will reject it.
-- VALID: Adding two integers
validMath :: Expr Int
validMath = Add (LitInt 5) (LitInt 10)
-- INVALID: Adding an Integer and a Boolean
-- This causes a Compile Error:
-- • Couldn't match type ‘Bool’ with ‘Int’
badMath :: Expr Int
badMath = Add (LitInt 5) (LitBool True)
We defined Equal to take Expr Int but return Expr Bool. This allows logic to depend on math safely.
-- VALID: The condition is an Expr Bool (result of Equal)
-- The branches are Expr Int
safeCondition :: Expr Int
safeCondition = If (Equal (LitInt 5) (LitInt 5))
(LitInt 100)
(LitInt 0)
-- INVALID: Using an Int expression as the condition
-- This causes a Compile Error:
-- • Couldn't match type ‘Int’ with ‘Bool’
badCondition :: Expr Int
badCondition = If (LitInt 5) -- LitInt is Expr Int, If requires Expr Bool
(LitInt 1)
(LitInt 2)
By using data Expr a where ..., we encode the typing rules of our mini-language into the Haskell type system.
LitInt forces the phantom type a to be Int.Add forces its inputs to be Int and promises the output is Int.If forces the condition to be Bool, but uses polymorphism (a) to allow the result to be either Int or Bool, as long as both branches agree.