ErlGrey
ErlGrey

Reputation: 121

Default type of id function

What type will have id function if I apply this function to an empty list? Is there some default type for id function or it depends on default type of list?

id []

Upvotes: 2

Views: 76

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477240

In short: id [] has type [a], the exact type will depend on the context of the caller.

We can perform the reasoning of the types ourselves. We basically have two items here: id and [], id has as type id :: a -> a, and [] is just a constructor, so it has type [] :: [b].

So we can derive the type with:

  id :: a   -> a
  [] :: [b]
----------------
  a ~ [b]

we thus conclude that the a in id :: a -> a is the same type as [b], and hence it means that the type of the result of id [], is a which is equal to [b], so that means that:

id [] :: [b]

We get the same result when we let ghci derive the type of id []:

Prelude> :t id []
id [] :: [t]

Of course in a real program if you use id [], it will "collapse" to a certain type. That type depends on the use of id [], so of the "caller". For example if we call this with:

putStrLn (id [])

Since putStrLn expects a String as parameter, this means that id [] in this context should be a String. A String is just an alias for [Char]. So the type system reasons that in that case b ~ Char, so the list [] is in this context an empty list of Chars.

But if we would use it in the context of sum (id []), then the type would be totally different, since we can not sumup Chars, since we can only sum up types that are members of the Num type class.

In case the ambiguity of the type ramains, Haskell has some defaulting rules [Kwang's Haskell blog]. The Haskell '10 report for example also has a section on defining defaults for type classes.

Upvotes: 1

Related Questions