Haskell类型签名解读:为何:type输出函数而非数值?
:type Command Great question—let’s break this down step by step, since Haskell’s approach to functions and types can feel counterintuitive at first if you’re coming from more imperative languages.
First: What the :type Command Actually Does
The :type (or :t for short) command in GHCi doesn’t show you the value of an expression—it shows you its type. That’s why when you run :type (+), you get Num a => a -> a -> a instead of a number: (+) isn’t a number yet—it’s a function waiting to receive arguments.
For example:
- If you run
:type 3 + 5, you’ll seeNum a => a—this tells you the expression is a numeric type (the actual value when you evaluate it is 8, but:typeonly cares about the type). - If you run
:type (+3), you’ll getNum a => a -> a—this is a partial application: we’ve given(+)one argument, so it returns a function that’s waiting for the second number to add.
Why (+) Returns a Function (Not a Number)
Haskell uses currying for all functions by default. That means every function in Haskell takes exactly one argument, and returns either a value or another function.
Your observation that (+) can be rewritten as a -> (a -> a) is spot-on. Let’s unpack that:
- When you pass the first argument to
(+), say3, you get back a function of typea -> a—this function takes a number and adds 3 to it. - Only when you pass the second argument to that returned function (e.g.,
(+3) 5) do you get a numeric result (8).
This isn’t just a quirk—it’s a powerful feature! Currying lets you create reusable partial functions. For example:
-- Add 10 to every element in a list map (+10) [1,2,3] -- Returns [11,12,13]
Here, (+10) is a standalone function we pass to map, which wouldn’t be possible if (+) required both arguments upfront.
To Sum Up
:typeshows you the type of an expression, not its computed value.(+)is a function, so its type reflects that it takes two numeric arguments (via currying) and returns a number.- Haskell’s curried functions let you build up computations incrementally, which is key to writing concise, reusable code. If you want a numeric result from
(+), you need to provide both arguments (like2 + 4), at which point evaluating the expression will give you a number, and:typewill confirm it’s a numeric type.
内容的提问来源于stack exchange,提问作者Thomas Windisch

