# Keywords

### From HaskellWiki

(Add ' and '') |
(removing (#), removed in GHC 7.6) |

(17 intermediate revisions by 8 users not shown) |

## Revision as of 21:30, 20 April 2013

This page lists all Haskell keywords, feel free to edit. Hoogle searches will return results from this page. Please respect the Anchor macros.

For additional information you might want to look at the Haskell 2010 report.

## 1 !

Whenever a data constructor is applied, each argument to the constructor is evaluated if and only if the corresponding type in the algebraic datatype declaration has a strictness flag, denoted by an exclamation point. For example:

data STList a = STCons a !(STList a) -- the second argument to STCons will be -- evaluated before STCons is applied | STNil

to illustrate the difference between strict versus lazy constructor application, consider the following:

stList = STCons 1 undefined lzList = (:) 1 undefined stHead (STCons h _) = h -- this evaluates to undefined when applied to stList lzHead (h : _) = h -- this evaluates to 1 when applied to lzList

! is also used in the "bang patterns" (GHC extension), to indicate strictness in patterns:

f !x !y = x + y

## 2 '

- Character literal: 'a'
- Template Haskell: Name of a (value) variable or data constructor: ,'length'Left

## 3 ''

- Template Haskell: Name of a type constructor or class: ,''Int,''Either''Show

## 4 -

This operator token is magic/irregular in the sense that

(- 1)

is parsed as the negative integer -1, rather than as an operator section, as it would be for any other operator:

(* 1) :: Num a => a -> a

(++ "foo") :: String -> String

## 5 --

Starts a single-line comment, unless immediately followed by an operator character other thanmain = print "hello world" -- this is a comment --this is a comment as well ---this too foobar --+ this_is_the_second_argument_of_the_dash_dash_plus_operator

## 6 -<

## 7 -<<

## 8 ->

- The function type constructor:

length :: [a] -> Int

- In lambda functions:

\x -> x + 1

- To denote alternatives in case statements:

case Just 3 of Nothing -> False Just x -> True

- On the kind level (GHC specific):

ghci> :kind (->) (->) :: * -> * -> *

-- This examples assumes that each type 'c' can "contain" only one type -- i.e. type 'c' uniquely determines type 'elt' class Contains c elt | c -> elt where ...

## 9 ::

Read as "has type":

length :: [a] -> Int

"Length has type list-of-'a' to Int"

Or "has kind" (GHC specific):

Either :: * -> * -> *

## 10 ;

- Statement separator in an explicit block (see layout)

## 11 <-

- In do-notation, "draw from":

do x <- getChar putChar x

- In list comprehension generators, "is drawn from":

[ (x,y) | x <- [1..10], y <- ['a'..'z'] ]

- In pattern guards, "matches":

f x y | Just z <- g x = True | otherwise = False

## 12 =

Used in definitions.

x = 4

## 13 =>

Used to indicate instance contexts, for example:

sort :: Ord a => [a] -> [a]

## 14 >

In a Bird's style Literate Haskell file, the > character is used to introduce a code line.

comment line > main = print "hello world"

## 15 ?

ghci> :t ?foo ++ "bar" ?foo ++ "bar" :: (?foo::[Char]) => [Char]

## 16 #

ghci> :m +GHC.Prim ghci> :set -XMagicHash ghci> :kind Int# Int# :: #

## 17 *

- Is an ordinary operator name on the value level

- On the kind level: The kind of boxed types (GHC-specific)

ghci> :kind Int Int :: *

## 18 @

Patterns of the form var@pat are called as-patterns, and allow one to use var as a name for the value being matched by pat. For example:

case e of { xs@(x:rest) -> if x==0 then rest else xs }

is equivalent to:

let { xs = e } in case xs of { (x:rest) -> if x==0 then rest else xs }

## 19 [|, |]

- Template Haskell
- Expression quotation: [| print 1 |]
- Declaration quotation: [d| main = print 1 |]
- Type quotation: [t| Either Int () |]
- Pattern quotation: [p| (x,y) |]
- Quasiquotation: [nameOfQuasiQuoter| ... |]

- Expression quotation:

## 20 \

The backslash "\" is used

- in multiline strings

```
"foo\
\bar"
```

- in lambda functions

\x -> x + 1

## 21 _

Patterns of the form _ are wildcards and are useful when some part of a pattern is not referenced on the right-hand-side. It is as if an identifier not used elsewhere were put in its place. For example,

case e of { [x,_,_] -> if x==0 then True else False }

is equivalent to:

case e of { [x,y,z] -> if x==0 then True else False }

## 22 `

A function enclosed in back ticks "`" can be used as an infix operator.

2 `subtract` 10

is the same as

subtract 2 10

## 23 {, }

- Explicit block (disable layout), possibly with ";" .

- Record update notation

changePrice :: Thing -> Price -> Thing changePrice x new = x { price = new }

- Comments (see below)

## 24 {-, -}

Everything between "{-" followed by a space and "-}" is a block comment.

```
{-
hello
world
-}
```

## 25 |

The "pipe" is used in several places

- Data type definitions, "or"

data Maybe a = Just a | Nothing

- List comprehensions, "where"

squares = [a*a | a <- [1..]]

- Guards, "when"

safeTail x | null x = [] | otherwise = tail x

- Functional dependencies, "where"

class Contains c elt | c -> elt where ...

## 26 ~

- Lazy pattern bindings. Matching the pattern ~pat against a value always

succeeds, and matching will only diverge when one of the variables bound in the pattern is used.

f1, f2 :: Maybe Int -> String f1 x = case x of Just n -> "Got it" f2 x = case x of ~(Just n) -> "Got it" (+++), (++++) :: (a -> b) -> (c -> d) -> (a, c) -> (b, d) (f +++ g) ~(x, y) = (f x, g y) (f ++++ g) (x, y) = (f x, g y)

Then we have:

f1 Nothing Exception: Non-exhaustive patterns in case f2 Nothing "Got it" (const 1 +++ const 2) undefined (1,2) (const 1 ++++ const 2) undefined Exception: Prelude.undefined

For more details see the Haskell Wikibook.

- Equality constraints. Assert that two types in a context must be the same:

example :: F a ~ b => a -> b

Here the type "F a" must be the same as the type "b", which allows one to constrain polymorphism (especially where type families are involved), but to a lesser extent than functional dependencies. See Type Families.

## 27 as

Renaming module imports. Likeimport qualified Data.Map as M main = print (M.empty :: M.Map Int ())

## 28 case, of

A case expression has the general form

case e of { p1 match1 ; ... ; pn matchn }

where each `match`

_{i} is of the general form

| g1 -> e1 ... | gm -> em where decls

Each alternative consists of patterns `p`

_{i} and their matches, `match`

_{i}. Each
`match`

_{i} in turn consists of a sequence of pairs of guards `g`

_{ij} and bodies `e`

_{ij}
(expressions), followed by optional bindings (`decls`

_{i}) that scope over all
of the guards and expressions of the alternative. An alternative of the
form

pat -> exp where decls

is treated as shorthand for:

pat | True -> exp where decls

A case expression must have at least one alternative and each alternative must have at least one body. Each body must have the same type, and the type of the whole expression is that type.

A case expression is evaluated by pattern matching the expression `e`

against the individual alternatives. The alternatives are tried
sequentially, from top to bottom. If `e`

matches the pattern in the
alternative, the guards for that alternative are tried sequentially from
top to bottom, in the environment of the case expression extended first
by the bindings created during the matching of the pattern, and then by
the `decls`

_{i} in the `where`

clause associated with that alternative. If one
of the guards evaluates to `True`

, the corresponding right-hand side is
evaluated in the same environment as the guard. If all the guards
evaluate to `False`

, matching continues with the next alternative. If no
match succeeds, the result is _|_.

## 29 class

A class declaration introduces a new type class and the overloaded operations that must be supported by any type that is an instance of that class.

class Num a where (+) :: a -> a -> a negate :: a -> a

## 30 data

The data declaration is how one introduces new algebraic data types into Haskell. For example:

data Set a = NilSet | ConsSet a (Set a)

Another example, to create a datatype to hold an abstract syntax tree for an expression, one could use:

data Exp = Ebin Operator Exp Exp | Eunary Operator Exp | Efun FunctionIdentifier [Exp] | Eid SimpleIdentifier

where the types `Operator, FunctionIdentifier`

and `SimpleIdentifier`

are defined elsewhere.

See the page on types for more information, links and examples.

## 31 data family

Declares a datatype family (see type families). GHC language extension.

## 32 data instance

Declares a datatype family instance (see type families). GHC language extension.

## 33 default

Ambiguities in the class Num are most common, so Haskell provides a way to resolve them---with a default declaration:

default (Int)

Only one default declaration is permitted per module, and its effect is limited to that module. If no default declaration is given in a module then it assumed to be:

default (Integer, Double)

## 34 deriving

data and newtype declarations contain an optional deriving form. If the form is included, then derived instance declarations are automatically generated for the datatype in each of the named classes.

Derived instances provide convenient commonly-used operations for user-defined datatypes. For example, derived instances for datatypes in the class Eq define the operations == and /=, freeing the programmer from the need to define them.

data T = A | B | C deriving (Eq, Ord, Show)

In the case of newtypes, GHC extends this mechanism to Cunning Newtype Deriving.

## 35 deriving instance

Standalone deriving (GHC language extension).

{-# LANGUAGE StandaloneDeriving #-} data A = A deriving instance Show A

## 36 do

Syntactic sugar for use with monadic expressions. For example:

do { x ; result <- y ; foo result }

is shorthand for:

x >> y >>= \result -> foo result

## 37 forall

This is a GHC/Hugs extension, and as such is not portable Haskell 98/2010. It is only a reserved word within types.

Type variables in a Haskell type expression are all assumed to be universally quantified; there is no explicit syntax for universal quantification, in standard Haskell 98/2010. For example, the type expression

For clarity, however, we often write quantification explicitly when discussing the types of Haskell programs. When we write an explicitly quantified type, the scope of the forall extends as far to the right as possible; for example,

forall a. a -> a

means

forall a. (a -> a)

data Foo = forall a. MkFoo a (a -> Bool) | Nil MkFoo :: forall a. a -> (a -> Bool) -> Foo Nil :: Foo [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]

## 38 foreign

A keyword for the Foreign Function Interface (commonly called the FFI) that introduces either a## 39 hiding

When importing modules, without introducing a name into scope, entities can be excluded by using the form

hiding (import1 , ... , importn )

which specifies that all entities exported by the named module should be imported except for those named in the list.

For example:

import Prelude hiding (lookup,filter,foldr,foldl,null,map)

## 40 if, then, else

A conditional expression has the form:

if e1 then e2 else e3

and returns the value of e2 if the value of e1 is True, e3 if e1 is False, and _|_ otherwise.

max a b = if a > b then a else b

## 41 import

Modules may reference other modules via explicit import declarations, each giving the name of a module to be imported and specifying its entities to be imported.

For example:

module Main where import A import B main = A.f >> B.f module A where f = ... module B where f = ...

See also as, hiding , qualified and the page Import

## 42 infix, infixl, infixr

A fixity declaration gives the fixity and binding precedence of one or more operators. The integer in a fixity declaration must be in the range 0 to 9. A fixity declaration may appear anywhere that a type signature appears and, like a type signature, declares a property of a particular operator.

There are three kinds of fixity, non-, left- and right-associativity (infix, infixl, and infixr, respectively), and ten precedence levels, 0 to 9 inclusive (level 0 binds least tightly, and level 9 binds most tightly).

module Bar where infixr 7 `op` op = ...

## 43 instance

An instance declaration declares that a type is an instance of a class and includes the definitions of the overloaded operations - called class methods - instantiated on the named type.

instance Num Int where x + y = addInt x y negate x = negateInt x

## 44 let, in

Let expressions have the general form:

let { d1 ; ... ; dn } in e

They introduce a nested, lexically-scoped, mutually-recursive list of declarations (let is often called letrec in other languages). The scope of the declarations is the expression e and the right hand side of the declarations.

Within## 45 mdo

The recursive## 46 module

Taken from: A Gentle Introduction to Haskell, Version 98

Technically speaking, a module is really just one big declaration which begins with the keyword module; here's an example for a module whose name is Tree:

module Tree ( Tree(Leaf,Branch), fringe ) where data Tree a = Leaf a | Branch (Tree a) (Tree a) fringe :: Tree a -> [a] fringe (Leaf x) = [x] fringe (Branch left right) = fringe left ++ fringe right

## 47 newtype

The `newtype`

declaration is how one introduces a renaming for an algebraic data type into Haskell. This is different from `type`

below, as a `newtype`

requires a new constructor as well. As an example, when writing a compiler
one sometimes further qualifies `Identifier`

s to assist in type safety checks:

newtype SimpleIdentifier = SimpleIdentifier Identifier newtype FunctionIdentifier = FunctionIdentifier Identifier

Most often, one supplies smart constructors and destructors for these to ease working with them.

See the page on types for more information, links and examples.

For the differences between `newtype`

and `data`

, see Newtype.

## 48 proc

proc (arrow abstraction) is a kind of lambda, except that it constructs an arrow instead of a function.

## 49 qualified

Used to import a module, but not introduce a name into scope. For example, Data.Map exports lookup, which would clash with the Prelude version of lookup, to fix this:

import qualified Data.Map f x = lookup x -- use the Prelude version g x = Data.Map.lookup x -- use the Data.Map version

Of course, Data.Map is a bit of a mouthful, so qualified also allows the use of as.

import qualified Data.Map as M f x = lookup x -- use Prelude version g x = M.lookup x -- use Data.Map version

## 50 rec

The rec keyword can be used when the `-XDoRec`

flag is given; it allows recursive bindings in a do-block.

{-# LANGUAGE DoRec #-} justOnes = do { rec { xs <- Just (1:xs) } ; return (map negate xs) }

## 51 type

The `type`

declaration is how one introduces an alias for an algebraic data type into Haskell. As an example, when writing a compiler
one often creates an alias for identifiers:

type Identifier = String

This allows you to use `Identifer`

wherever you had used `String`

and if something is of type `Identifier`

it
may be used wherever a `String`

is expected.

See the page on types for more information, links and examples.

Some common `type`

declarations in the Prelude include:

type FilePath = String type String = [Char] type Rational = Ratio Integer type ReadS a = String -> [(a,String)] type ShowS = String -> String

## 52 type family

Declares a type synonym family (see type families). GHC language extension.

## 53 type instance

Declares a type synonym family instance (see type families). GHC language extension.

## 54 where

Used to introduce a module, instance, class or GADT:

module Main where class Num a where ... instance Num Int where ... data Something a where ...

And to bind local variables:

f x = y where y = x * 2 g z | z > 2 = y where y = x * 2