Beginning Haskell
This is a set of growing notes on Haskell programming. The note is mostly for myself at the moment.
Hello World
To respect the grand tradition of programming language tutorial, we will start with the example on how to print hello world to the screen:
main :: IO()
main = do
print "Hello world"
Put the snippet in the file hello-world.hs
, run runhaskell hello-world.hs
.
Generalized Algebraic Data Types (GADTs)
Generalized Algebraic Data Types (GADTs) allows data constructor to return different types. The feature is an extension of GHC included that can be enabled by GADTs. It’s built upon another extension named GADTSyntax. It’s sometimes confusing and intimating to have many extensions in GHC, but the separation can actually help understanding the feature. The syntax part allows you to provide the type signature of each value constructor:
data Data a where
Nothing :: Data a
Something :: a -> Data a
and with the newtype
:
newtype Data a where
Data :: a -> Data a
When annotating the type explicitly, we changed the use of |
to simple new lines. So far, we are still returning a single consistent type for each constructor. To have a true GADT, based on the syntax, we can write:
data Expr a b where
Add :: Num n => Expr a n -> Expr a n -> Expr a n
Negate :: Expr a Bool -> Expr a Bool
Notice that in the above snippet, two value constructors return different types, hence the name generalized.