Understanding Haskell Type Signatures

前端 未结 3 1807
轮回少年
轮回少年 2020-12-14 07:18

I am in the process of teaching myself Haskell and I was wondering about the following type signatures:

Prelude> :t ($)
($) :: (a -> b) -> a -> b         


        
3条回答
  •  时光取名叫无心
    2020-12-14 08:02

    ($) is just function application. It gets a function of type a->b, an argument of type a, applies the function and returns a value of type b.

    map is a wonderful example for how reading a function type signature helps understanding it. map's first argument is a function that takes a and returns b, and its second argument is a list of type [a]. So map applies a function of type a->b to a list of a values. And the result type is indeed of type [b] - a list of b values!

    (a->b)->[a]->[b] can be interpreted as "Accepts a function and a list and returns another list", and also as "Accepts a function of type a->b and returns another function of type [a]->[b]". When you look at it this way, map "upgrade" f (the term "lift" is often used in this context) to work on lists: if double is a function that doubles an integer, then map double is a function that double every integer in a list.

提交回复
热议问题