简体   繁体   中英

what is [a] as a type in Haskell?

This question is about type in Haskell programming language.

When I type

:t []

I get the return as:

[] :: [a]

What is [a] ?

Rewriting it like so might make things clearer:

[] :: forall a. [a]

So, since it doesn't contain any value, haskell can't decide on a type and leaves it open. If you use it in a typed expression, however, like

x = []

f :: [Int] -> [Int]
f l = l

y = f x

it automatically gets resolved to [Int] , since it is used as this type.

It's a placeholder. It basically means any type could go there. In other words, if you had a function

someFunc :: [Int] -> ()

You could pass [] to it because [] is [a] , which will match [Int] (by replacing the a placeholder with the concrete Int type).

Now if you look at, say, id , you'll find it has the type a -> a . This means that it's a function that takes an object of any type, and returns an object of the same type. Interestingly, because the function knows absolutely nothing about the object it's given (since it has no constraints on the type), you know that this function has to do either of two things:

  1. Return the input object, or
  2. Return ⊥ ( bottom ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM