O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Create a new project working-with-GADTs with simple stack template:
        stack new working-with-GADTs simple
  1. Open src/Main.hs. We will be adding our source here.
  2. Enable GADTs, and StandaloneDeriving:
 {-# LANGUAGE GADTs, StandaloneDeriving #-}
 module Main where

 import Control.Monad
 import Data.Char
 import Control.Applicative
  1. 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:
 data Expr where
   Value :: Int -> Expr
   Add :: Expr -> Expr -> Expr
   Mult :: Expr -> Expr -> Expr

 deriving instance Show Expr 
  1. We can evaluate the preceding expression as follows:
 eval :: Expr -> Int
 eval (Value i) = i
 eval (Add ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required