Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 57 ยท Advanced types

GHC Extensions Worth Knowing

Learn what LANGUAGE pragmas do and which GHC extensions are worth knowing: LambdaCase, TupleSections, RecordWildCards, OverloadedStrings and TypeApplications.

The Haskell language is defined by a standard, but almost every real program also uses GHC extensions: optional features that GHC adds on top, each switched on by name. Many are small conveniences that remove boilerplate; a few unlock whole styles of programming. Reading other people's code is much easier once you recognise the common ones.

This lesson shows how to enable extensions and then tours the ones you will meet most often. The Haskell blocks are read-only, because GHC is not installed on this site. The runnable examples are JavaScript stand-ins that mimic what each extension saves you from writing, and say so.

Small conveniences

LambdaCase A function that is a case.
TupleSections (,True) fills one slot.
RecordWildCards Bring every field into scope.
1 / 2

Turning extensions on

There are three ways, from narrowest to broadest.

A pragma at the top of a file applies to that file only. It must come before the module line:

HASKELL
# LANGUAGE LambdaCase #
# LANGUAGE TupleSections, RecordWildCards #

module Main (main) where

default-extensions in the .cabal file applies to every module of a stanza (see Cabal, Stack and Packages):

CABAL
library
    default-language:   GHC2021
    default-extensions: LambdaCase, OverloadedStrings

A language edition switches on a whole bundle. With default-language: GHC2021 (the default for modern GHC when you run it directly), many popular extensions are already on, including BangPatterns, TupleSections, ScopedTypeVariables, TypeApplications, DeriveFunctor and GeneralisedNewtypeDeriving-style conveniences. The newer GHC2024 edition adds more, among them LambdaCase. If a feature in this lesson does not need a pragma for you, an edition is the reason. If you see an error such as "Illegal lambda-case", the extension is off; add the pragma.

You can also try an extension in GHCi with :set -XLambdaCase.

LambdaCase

A function whose only job is to pattern match on its argument forces you to invent a name for that argument. \case removes it:

HASKELL
# LANGUAGE LambdaCase #

data Light = Red | Yellow | Green

next :: Light -> Light
next = \case
  Red    -> Green
  Green  -> Yellow
  Yellow -> Red

It is the same as next l = case l of .... It shines inside map, traverse and >>=, where the lambda is passed as an argument: mapM_ (\case Left e -> putStrLn e; Right v -> print v) results. (Pattern matching itself is covered in Pattern Matching.)

TupleSections

With TupleSections you may leave out parts of a tuple, and the result is a function that fills them in:

HASKELL
# LANGUAGE TupleSections #

labelled :: [String] -> [(String, Bool)]
labelled = map (, True)          -- same as map (\x -> (x, True))

indexed :: [a] -> [(Int, a)]
indexed = zipWith (,) [0 ..]     -- (,) alone needs no extension

(, True) turns each element x into (x, True), and (0, ,) would build a triple. It is pure sugar for a lambda, and very common when you build a Map from a list.

RecordWildCards

Records with many fields lead to repetitive code. RecordWildCards lets .. bring every field of a record into scope as a local variable, both when matching and when constructing:

HASKELL
# LANGUAGE RecordWildCards #

data Config = Config
  { host :: String
  , port :: Int
  , debug :: Bool
  }

describe :: Config -> String
describe Config{..} = host ++ ":" ++ show port ++ (if debug then " [debug]" else "")

defaultConfig :: Config
defaultConfig =
  let host = "localhost"
      port = 8080
      debug = False
  in Config{..}

In describe, host, port and debug are now ordinary variables taken from the argument. In defaultConfig, the .. collects the three local variables with the same names to build the record. The cost is clarity: a reader cannot see which names come from the wildcard, and it can silently shadow other bindings. A narrower alternative is NamedFieldPuns, where you write Config{host, port} and name exactly the fields you use. Prefer the pun style in code you want others to read easily.

OverloadedStrings

By default the literal "abc" has type String. With OverloadedStrings, it has type IsString a => a, so the same literal can be a Text, a ByteString or your own type:

HASKELL
# LANGUAGE OverloadedStrings #

import Data.Text (Text)
import qualified Data.Text as T

title :: Text
title = "Haskell"             -- no T.pack needed

shout :: Text -> Text
shout t = T.toUpper t <> "!"

This is nearly universal in programs that use the text library (see Essential Libraries). The downside is ambiguity: an expression such as length "abc" can no longer be resolved, because "abc" could be any IsString type that is also Foldable. GHC then asks you to add a type annotation. A related extension, OverloadedLists, does the same for list literals but is rarer.

ScopedTypeVariables

Normally the type variable a in a signature is local to that signature, so a where helper cannot refer to it. With ScopedTypeVariables and an explicit forall, the variable scopes over the whole function body:

HASKELL
# LANGUAGE ScopedTypeVariables #

import Data.List (sortBy)

sortedPairs :: forall a. Ord a => [a] -> [(a, a)]
sortedPairs xs = zip sorted (drop 1 sorted)
  where
    sorted :: [a]            -- the same 'a' as in the signature
    sorted = sortBy compare xs

Without the extension, the inner signature sorted :: [a] would mean "for any a", which is wrong and gives a confusing error. The same extension lets you annotate pattern variables, as in \(x :: Int) -> ..., and is vital for exception handlers: catch action (\(e :: SomeException) -> ...).

TypeApplications

Some expressions leave GHC with a type it cannot guess. A classic example is read:

HASKELL
# LANGUAGE TypeApplications #

main :: IO ()
main = do
  print (read @Int "42")            -- 42
  print (read @Double "3.5")        -- 3.5
  print (maxBound @Int)             -- the largest Int
  print (show @Integer 7)           -- "7"

@Int supplies the first type variable of the function's signature explicitly. It replaces annotations like (read "42" :: Int) and is especially handy with fromIntegral, minBound and class methods that have no argument to infer from. The order of type variables follows the signature (or the forall), so check it with :type +v or :t in GHCi if the result is surprising. Our type class lesson explains why GHC sometimes cannot choose a type by itself.

Other extensions you will see

Extension What it does
MultiWayIf An if with several guard-style branches
NamedFieldPuns Config{host} binds just the field you name
DeriveGeneric, DeriveAnyClass Derive instances for libraries like aeson
DerivingStrategies, DerivingVia Choose how an instance is derived
StrictData Make every field of the module's data types strict
GADTs, TypeFamilies, DataKinds Type-level programming (the next lesson)
KindSignatures, RankNTypes Explicit kinds and polymorphic function arguments
NumericUnderscores Write 1_000_000
ImportQualifiedPost Write import Data.Map qualified as Map

Read an unfamiliar pragma as a small contract: it changes what some syntax means in that file. GHC's user guide documents each one exactly, and new programs rarely need more than a handful.

Stand-ins in JavaScript

JavaScript has none of these features, so the stand-ins show the shape of what they save you from writing. The first one covers \case and tuple sections.

JS LambdaCase and TupleSections (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second one models RecordWildCards and TypeApplications: bringing record fields into scope, and choosing a result type by naming it.

JS RecordWildCards and TypeApplications (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In real Haskell the type application is checked at compile time and the failing read raises a runtime exception named Prelude.read: no parse; here a plain Error stands in for it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where must a LANGUAGE pragma appear in a source file?

    File-header pragmas come before the module line. You can also enable extensions in the .cabal file with default-extensions.
  2. 2. What does map (, True) xs produce for xs = ["a"]?

    With TupleSections, (, True) is the function \x -> (x, True).
  3. 3. What is the main drawback of RecordWildCards?

    A reader cannot see which variables the .. introduces, and it can shadow others. NamedFieldPuns is more explicit.
  4. 4. What does read @Int "42" do?

    TypeApplications supplies the type variable of read, replacing an annotation like (read "42" :: Int).
  5. 5. Why can length "abc" become ambiguous with OverloadedStrings?

    The literal's type is no longer fixed to String, so GHC may need a type annotation to choose one.

Summary

  • Extensions are switched on with # LANGUAGE Name #, default-extensions in Cabal, or a language edition such as GHC2021.
  • LambdaCase gives \case; TupleSections gives (, x).
  • RecordWildCards (Config{..}) removes record boilerplate at some cost in clarity; NamedFieldPuns is more explicit.
  • OverloadedStrings lets literals be Text or ByteString but can cause ambiguity.
  • ScopedTypeVariables with forall lets inner signatures refer to the outer type variables.
  • TypeApplications (read @Int) chooses a type explicitly.

Next: GADTs, Type Families and DataKinds.