Personal tools

Type of empty list

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
(question)
 
(Answer, refer to phantom types)
 
Line 21: Line 21:
   
 
== Answer ==
 
== Answer ==
  +
  +
For an empty list it may seem silly to talk about the types of its elements, since it has no elements.
  +
However when you prepend new elements to the empty list it is important what elements are allowed.
  +
E.g. <hask>2 : ([]::String)</hask> makes no sense, right?
  +
  +
Lists can be defined by
  +
<haskell>
  +
data [a] = a : [a] | []
  +
</haskell>
  +
and you see that one of the constructors (the empty list <hask>[]</hask>)
  +
does not use the type parameter <hask>a</hask>.
  +
There are types, where none of the constructors refers to the type parameter
  +
and these types are very useful, e.g. for defining numbers with type-checked physical dimensions.
  +
For details refer to "[[phantom type]]s".
   
   

Latest revision as of 14:05, 5 January 2012

[edit] 1 Question

Why is

([]::[Int]) == ([]::[Char])
a type error and not just
True
(because both lists are empty) or
False
(because the types mismatch)?

Related question: Why is

map :: (a -> b) -> [a] -> [b]
map f (x:xs) = f x : map f xs
map f xs@[] = xs

a type error and the case definition

map f [] = []

is not?


[edit] 2 Answer

For an empty list it may seem silly to talk about the types of its elements, since it has no elements. However when you prepend new elements to the empty list it is important what elements are allowed.

E.g.
2 : ([]::String)
makes no sense, right?

Lists can be defined by

data [a] = a : [a] | []
and you see that one of the constructors (the empty list
[]
) does not use the type parameter
a
.

There are types, where none of the constructors refers to the type parameter and these types are very useful, e.g. for defining numbers with type-checked physical dimensions. For details refer to "phantom types".