Why is function definition for all types at once not allowed in Haskell?

后端 未结 5 1755
迷失自我
迷失自我 2020-12-10 01:14

This is probably a very basic question, but ...

A function that\'s defined as, say

foo :: a -> Integer

denotes a function from <

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 01:48

    The type a -> Integer does not really mean "function from any type to Integer" as you're describing it. When a definition or expression has type a -> Integer, it means that for any type T, it is possible to specialize or instantiate this definition or expression into a function of type T -> Integer.

    Switching notation slightly, one way to think of this is that foo :: forall a. a -> Integer is really a function of two arguments: a type a and a value of that type a. Or, in terms of currying, foo :: forall a. a -> Integer is a function that takes a type T as its argument, and produces a specialized function of type T -> Integer for that T. Using the identity function as an example (the function that produces its argument as its result), we can demonstrate this as follows:

    -- | The polymorphic identity function (not valid Haskell!)
    id :: forall a. a -> a
    id = \t -> \(x :: t) -> x
    

    This idea of implementing polymorphism as a type argument to a polymorphic function comes from a mathematical framework called System F, which Haskell actually uses as one of its theoretical sources. Haskell completely hides the idea of passing type parameters as arguments to functions, however.

提交回复
热议问题