Search code examples
haskelltypestype-signature

Type of any in Haskell?


I've recently started trying to learn Haskell by reading LearnYouAHaskell and random articles from the internet.

I'm having hard time understanding more sophisticated function types.

Some examples that I understand.

> :t map  
map :: (a -> b) -> [a] -> [b]

It takes in a function (which takes a and gives out b, i.e a and b can be of different types) and a list of a's and return a list of b's.

> :t fst  
fst :: (a, b) -> a

Takes in a tuple of 2 elements (allows different types) and returns the first one.

> :t any  

At a higher level, I understand any. It takes in a function and a list and returns true if any of the list entries return true for that particular function. I've used it in Python and JavaScript as well.

Questions

  • I don't understand how does any :: Foldable t => (a -> Bool) -> t a -> Bool translate to the above.

    • (a -> Bool) is the predicate. Takes in an argument and returns true or false.
    • t a -> Bool Bool is the end result of any. According to my understanding t and a represent the predicate and the list. Why aren't they separated by a ->
  • How to go about understanding type signatures in general and how to dig deeper so that I can approach them myself?


Solution

  • any :: Foldable t => (a -> Bool) -> t a -> Bool
    

    Here Foldable t means, that t is an instance of type class Foldable.

    Foldable is a type class and if type t is an instance of the type class Foldable we know from the t a part of the signature or from the definition of the type class Foldable, that t is actually a type constructor.

    So t a is a type and therefore t a -> Bool is a function, that maps a value of type t a to Bool. This function will be closure, which will apply the predicate to each "element" of the value of type t a, until it finds one, that yields True under the predicate or it doesn't find such an element returning either True or False in the respective cases. (The actual implementation might be very different.)

    For example [] is an instance of the type class Foldable and therefore t a could be a list of something. In this case, we can also write [a] instead of [] a.

    But there are other type constructors, which can be instances of Foldable, for example some kinds of trees.