Working with GADTs
In this recipe, we will work with GADTs. GADTs extend the data constructors, and allow us more expressivity for representing a complex structure such as a DSL. In this recipe, we will use GADTs to create an expression representation, and a simple parser.
How to do it...
- Create a new project
working-with-GADTs
withsimple
stack template:
stack new working-with-GADTs simple
- Open
src/Main.hs
. We will be adding our source here. - Enable
GADTs
, andStandaloneDeriving
:
{-# LANGUAGE GADTs, StandaloneDeriving #-} moduleMainwhere import Control.Monad import Data.Char import Control.Applicative
GADTs
take an algebraic data type one step further, and allow us to write data constructors explicitly. For example, we can represent a set of expressions as follows:
dataExprwhereValue ::Int->ExprAdd ::Expr->Expr->ExprMult ::Expr->Expr->Expr derivinginstanceShowExpr
- We can evaluate the preceding expression as follows:
eval ::Expr->Int eval (Value i) = i eval (Add e1 e2...