Difference between revisions of "Keywords"

From HaskellWiki
Jump to: navigation, search
(expand)
(more stuff)
Line 25: Line 25:
 
</haskell>
 
</haskell>
   
In case statements:
+
To denote alternatives in case statements:
 
<haskell>
 
<haskell>
 
case Just 3 of
 
case Just 3 of
Line 32: Line 32:
 
</haskell>
 
</haskell>
   
And on the kind level:
+
And on the kind level (GHC specific):
 
<haskell>
 
<haskell>
 
(->) :: ?? -> ? -> *
 
(->) :: ?? -> ? -> *
Line 58: Line 58:
 
== @ ==
 
== @ ==
   
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:
+
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:
  +
<haskell>
 
case e of { xs@(x:rest) -> if x==0 then rest else xs }
 
case e of { xs@(x:rest) -> if x==0 then rest else xs }
  +
</haskell>
   
 
is equivalent to:
 
is equivalent to:
   
  +
<haskell>
 
let { xs = e } in
 
let { xs = e } in
 
case xs of { (x:rest) -> if x==0 then rest else xs }
 
case xs of { (x:rest) -> if x==0 then rest else xs }
  +
</haskell>
   
 
== ! ==
 
== ! ==
   
Whenever a data [[constructor]] is applied, each argument to the constructor is evaluated if and only if the corresponding type in the algebraic data[[type]] declaration has a strictness flag, denoted by an exclamation point. For example:
+
Whenever a data [[constructor]] is applied, each argument to the
  +
constructor is evaluated if and only if the corresponding type in the
  +
algebraic data[[type]] declaration has a strictness flag, denoted by an
  +
exclamation point. For example:
   
  +
<haskell>
 
data STList a
 
data STList a
 
= STCons a !(STList a) -- the second argument to STCons will be
 
= STCons a !(STList a) -- the second argument to STCons will be
 
-- evaluated before STCons is applied
 
-- evaluated before STCons is applied
 
| STNil
 
| STNil
  +
</haskell>
   
to illustrate the difference between strict versus lazy constructor application, consider the following:
+
to illustrate the difference between strict versus lazy constructor
  +
application, consider the following:
   
  +
<haskell>
 
stList = STCons 1 undefined
 
stList = STCons 1 undefined
 
lzList = (:) 1 undefined
 
lzList = (:) 1 undefined
 
stHead (STCons h _) = h -- this evaluates to undefined when applied to stList
 
stHead (STCons h _) = h -- this evaluates to undefined when applied to stList
 
lzHead (h : _) = h -- this evaluates to 1 when applied to lzList
 
lzHead (h : _) = h -- this evaluates to 1 when applied to lzList
  +
</haskell>
   
! is also used in the "bang patterns" GHC extension, to indicate strictness in patterns:
+
! is also used in the "bang patterns" (GHC extension), to indicate
  +
strictness in patterns:
   
 
<haskell>
 
<haskell>
 
f !x !y = x + y
 
f !x !y = x + y
  +
</haskell>
  +
  +
Finally, it is the array subscript operator:
  +
<haskell>
  +
let x = arr ! 10
 
</haskell>
 
</haskell>
   
 
== :: ==
 
== :: ==
   
"type of"
 
  +
Read as "has type":
   
 
<haskell>
 
<haskell>
 
length :: [a] -> Int
 
length :: [a] -> Int
 
</haskell>
 
</haskell>
  +
  +
"Length has type list-of-'a' to Int"
   
 
== _ ==
 
== _ ==
   
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,
+
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,
   
  +
<haskell>
 
case e of { [x,_,_] -> if x==0 then True else False }
 
case e of { [x,_,_] -> if x==0 then True else False }
  +
</haskell>
   
 
is equivalent to:
 
is equivalent to:
   
  +
<haskell>
 
case e of { [x,y,z] -> if x==0 then True else False }
 
case e of { [x,y,z] -> if x==0 then True else False }
  +
</haskell>
   
 
== ~ ==
 
== ~ ==
   
Lazy pattern bindings. Matching the pattern ~pat against a value always suceeds,
+
Lazy pattern bindings. Matching the pattern ~pat against a value always
and matching will only diverge when one of the variables bound in the
+
suceeds, and matching will only diverge when one of the variables bound
pattern is used.
+
in the pattern is used.
   
 
<haskell>
 
<haskell>
Line 118: Line 136:
   
 
== as ==
 
== as ==
  +
  +
Renaming module imports.
   
 
<haskell>
 
<haskell>
Line 129: Line 149:
 
A case expression has the general form
 
A case expression has the general form
   
  +
<haskell>
 
case e of { p1 match1 ; ... ; pn matchn }
 
case e of { p1 match1 ; ... ; pn matchn }
  +
</haskell>
   
 
where each match is of the general form
 
where each match is of the general form
   
  +
<haskell>
 
| g1 -> e1
 
| g1 -> e1
 
...
 
...
 
| gm -> em
 
| gm -> em
 
where decls
 
where decls
  +
</haskell>
   
Each alternative consists of a pattern pi and its matches, matchi. Each match in turn consists of a sequence of pairs of guards gj and bodies ej (expressions), followed by optional bindings (decls) that scope over all of the guards and expressions of the alternative. An alternative of the form
 
  +
Each alternative consists of a pattern pi and its matches, matchi. Each
  +
match in turn consists of a sequence of pairs of guards gj and bodies ej
  +
(expressions), followed by optional bindings (decls) that scope over all
  +
of the guards and expressions of the alternative. An alternative of the
  +
form
   
  +
<haskell>
 
pat -> exp where decls
 
pat -> exp where decls
  +
</haskell>
   
 
is treated as shorthand for:
 
is treated as shorthand for:
   
  +
<haskell>
 
pat | True -> exp
 
pat | True -> exp
where decls
+
where decls
  +
</haskell>
   
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 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 declsi 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 _|_.
 
  +
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 declsi 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 _|_.
   
 
== class ==
 
== class ==
   
Please write this
 
  +
A [http://haskell.org/onlinereport/decls.html#class-decls|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.
  +
<haskell>
  +
class Num a where
  +
(+) :: a -> a -> a
  +
negate :: a -> a
  +
</haskell>
   
 
== data ==
 
== data ==
   
The <code>data</code> declaration is how one introduces new algebraic data [[type]]s into Haskell. As an example, to create a datatype to hold an [[Abstract syntax tree]] for an expression, one could use:
 
  +
The [http://haskell.org/onlinereport/decls.html#user-defined-datatypes|data]
  +
declaration is how one introduces new algebraic data [[type]]s into
  +
Haskell. For example:
 
 
data Exp = Ebin Operator Exp Exp |
 
  +
<haskell>
Eunary Operator Exp |
 
  +
data Set a = NilSet
Efun FunctionIdentifier [Exp] |
+
| ConsSet a (Set a)
Eid SimpleIdentifier
+
</haskell>
  +
  +
Another example, to create a datatype to hold an [[Abstract syntax
  +
tree]] for an expression, one could use:
  +
  +
<haskell>
  +
data Exp = Ebin Operator Exp Exp
  +
| Eunary Operator Exp
  +
| Efun FunctionIdentifier [Exp]
  +
| Eid SimpleIdentifier
  +
</haskell>
   
 
where the [[type]]s <code>Operator, FunctionIdentifier</code> and <code>SimpleIdentifier</code> are defined elsewhere.
 
where the [[type]]s <code>Operator, FunctionIdentifier</code> and <code>SimpleIdentifier</code> are defined elsewhere.
Line 170: Line 220:
 
== default ==
 
== default ==
   
Please write this
 
  +
Ambiguities in the class Num are most common, so Haskell provides
  +
a way to resolve them---with a default declaration:
  +
  +
<haskell>
  +
default (Int)
  +
</haskell>
  +
  +
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:
  +
  +
<haskell>
  +
default (Integer, Double)
  +
</haskell>
   
 
== deriving ==
 
== deriving ==
   
Please write this
 
  +
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.
  +
  +
[http://haskell.org/onlinereport/decls.html#derived-decls|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.
  +
  +
<haskell>
  +
data T = A
  +
| B
  +
| C
  +
deriving (Eq, Ord, Show)
  +
</haskell>
   
 
== do ==
 
== do ==
Line 180: Line 257:
 
Syntactic sugar for use with monadic expressions. For example:
 
Syntactic sugar for use with monadic expressions. For example:
   
  +
<haskell>
 
do { x ; result <- y ; foo result }
 
do { x ; result <- y ; foo result }
  +
</haskell>
   
 
is shorthand for:
 
is shorthand for:
   
  +
<haskell>
 
x >>
 
x >>
 
y >>= \result ->
 
y >>= \result ->
 
foo result
 
foo result
  +
</haskell>
   
 
== forall ==
 
== forall ==
   
 
This is a GHC/Hugs extension, and as such is not portable Haskell 98.
 
This is a GHC/Hugs extension, and as such is not portable Haskell 98.
  +
  +
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. For example, the type expression
  +
<code>a -> a</code> denotes the type <code>forall a. a ->a</code>.
  +
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,
  +
<haskell>
  +
forall a. a -> a
  +
</haskell>
  +
means
  +
<haskell>
  +
forall a. (a -> a)
  +
</haskell>
  +
  +
GHC [http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#type-synonyms|introduces] a <code>forall</code> keyword, allowing explicit quantification, for example, to encode
  +
[http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#existential-quantification|existential types]:
  +
<haskell>
  +
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]
  +
</haskell>
   
 
== hiding ==
 
== hiding ==
   
Please write this
 
  +
When importing modules, entities can be excluded by using the form
  +
<haskell>
  +
hiding (import1 , ... , importn )
  +
</haskell>
  +
which specifies that all entities exported by the named module should be
  +
imported except for those named in the list.
  +
  +
For example:
  +
<haskell>
  +
import Prelude hiding (lookup,filter,foldr,foldl,null,map)
  +
</haskell>
   
 
== if, then, else ==
 
== if, then, else ==
Line 200: Line 319:
 
A conditional expression has the form:
 
A conditional expression has the form:
   
  +
<haskell>
 
if e1 then e2 else e3
 
if e1 then e2 else e3
  +
</haskell>
   
...and returns the value of e2 if the value of e1 is True, e3 if e1 is False, and _|_ otherwise.
+
and returns the value of e2 if the value of e1 is True, e3 if e1 is False, and _|_ otherwise.
   
  +
<haskell>
 
max a b = if a > b then a else b
 
max a b = if a > b then a else b
  +
</haskell>
   
 
== import ==
 
== import ==
   
Please write this
 
  +
[http://haskell.org/onlinereport/modules.html|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:
  +
<haskell>
  +
module Main where
  +
import A
  +
import B
  +
main = A.f >> B.f
  +
  +
module A where
  +
f = ...
  +
  +
module B where
  +
f = ...
  +
</haskell>
   
 
== infix, infixl, infixr ==
 
== infix, infixl, infixr ==
   
Please write this
 
  +
A [http://haskell.org/onlinereport/decls.html|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).
  +
  +
<haskell>
  +
module Bar where
  +
infixr 7 `op`
  +
op = ...
  +
</haskell>
   
 
== instance ==
 
== instance ==
   
Please write this
 
  +
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.
  +
  +
<haskell>
  +
instance Num Int where
  +
x + y = addInt x y
  +
negate x = negateInt x
  +
</haskell>
   
 
== let, in ==
 
== let, in ==
Line 239: Line 401:
 
fringe (Leaf x) = [x]
 
fringe (Leaf x) = [x]
 
fringe (Branch left right) = fringe left ++ fringe right
 
fringe (Branch left right) = fringe left ++ fringe right
 
   
 
== newtype ==
 
== newtype ==

Revision as of 13:05, 13 September 2006

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 98 report.

|

Guards.

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

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

->

The function type constructor:

length :: [a] -> Int

In lambdas:

\x -> x + 1

To denote alternatives in case statements:

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

And on the kind level (GHC specific):

(->) :: ?? -> ? -> *

<-

In do-notation:

    do x <- getChar
       putChar x

In list comprehension generators:

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

In pattern guards (a GHC extension):

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

@

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 }

!

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

Finally, it is the array subscript operator:

let x = arr ! 10

::

Read as "has type":

length :: [a] -> Int

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

_

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 }

~

Lazy pattern bindings. Matching the pattern ~pat against a value always suceeds, and matching will only diverge when one of the variables bound in the pattern is used.

(f *** g) ~(x,y) = (f x, g y)

as

Renaming module imports.

import qualified Data.Map as M

main = print (M.empty :: M.Map Int ())

case, of

A case expression has the general form

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

where each match is of the general form

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

Each alternative consists of a pattern pi and its matches, matchi. Each match in turn consists of a sequence of pairs of guards gj and bodies ej (expressions), followed by optional bindings (decls) 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 declsi 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 _|_.

class

A 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

data

The [1] 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.

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)

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.

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)

do

Syntactic sugar for use with monadic expressions. For example:

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

is shorthand for:

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

forall

This is a GHC/Hugs extension, and as such is not portable Haskell 98.

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. For example, the type expression a -> a denotes the type forall a. a ->a. 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)

GHC [2] a forall keyword, allowing explicit quantification, for example, to encode types:

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]

hiding

When importing modules, 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)

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

import

[3] 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 = ...

infix, infixl, infixr

A 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 = ...

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

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.

module

taken from: http://www.haskell.org/tutorial/modules.html

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

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 Identifiers 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.

qualified

Please write this

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.

where

Used to introduce a module, instance or class:

module Main where

class Num a where
    ...

instance Num Int  where
    ...

And to bind local variables:

f x = y
    where y = x * 2

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