Haskell Cheat Sheet Page 13

ADVERTISEMENT

However, for efficiency or other reasons you
Haskell cannot compile that function because it
may only want to allow
types. You would
does not know the type of . We must limit the
accomplish that with a type signature:
type through an annotation:
Of course, lambdas can be the returned from func-
Annotations have the same syntax as type signa-
Type signatures can appear on top-level func-
tions too. This classic returns a function which will
tures, but may adorn any expression.
tions and nested
or
definitions. Gener-
then multiply its argument by the one originally
ally this is useful for documentation, although in
given:
Unit
some cases they are needed to prevent polymor-
phism. A type signature is first the name of the
– “unit” type and “unit” value. The value and
item which will be typed, followed by a
, fol-
type that represents no useful information.
For example:
lowed by the types. An example of this has already
been seen above.
Contributors
Type signatures do not need to appear directly
above their implementation. They can be specified
My thanks to those who contributed patches and
anywhere in the containing module (yes, even be-
useful suggestions:
Dave Bayer, Cale Gibbard,
low!). Multiple items with the same signature can
Type Signatures
Stephen Hicks, Kurt Hutchinson, Johan Kiviniemi,
also be defined together:
Adrian Neumann, Barak Pearlmutter, Lanny Rip-
Haskell supports full type inference, meaning in
ple, Markus Roberts, Holger Siegel, Leif Warner,
most cases no types have to be written down. Type
and Jeff Zaroyko.
signatures are still useful for at least two reasons.
Documentation—Even if the compiler can figure
Version
out the types of your functions, other pro-
grammers or even yourself might not be able
This is version 1.8.
The source can be found
to later. Writing the type signatures on all
2
at GitHub
.
The latest released version of the
top-level functions is considered very good
3
PDF can be downloaded from Hackage
.
Visit
form.
4
for other projects and writings.
Type Annotations
Sometimes Haskell cannot
Specialization—Typeclasses allow functions with
determine what type is meant. The classic demon-
overloading.
For example, a function to
stration of this is the so-called “
” prob-
negate any list of numbers has the signature:
lem:
2
3
4
c 2009 Justin Bailey.
13

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education