What's the difference between partial evaluation and function inlining in a functional language?
There is a difference between
- evaluating constant expressions over a given set of operators and functions known by the compiler (or even preprocessor), which happens at compile time . E.g. the compiler compiles
print(2*2)
asprint(4)
. This needs by no means to be limited to operator expressions, as you seem to imply (e.g.print(sqrt(2.0)
) - partial evaluation, which is a broader concept. A compiler could realise that
print(myfunc(2))
could be transformed intoprint(c)
wherec
is the result of callingmyfunc(2)
. It could then (at "specialisation time") callmyfunc(2)
to determinec
. Of course, this will go badly wrong ifmyfunc
has side-effects, like wiping one's own hard disk instead of the program user's. Hence the compiler needs some sort of annotation or attribute to know when this is allowed/desired (e.g. C++11's constexpr)
Inlining is an unrelated concept. Inlining a function call means replacing the call by the body of the called function. This body is not evaluated.
There is a distinction between the two in imperative languages like C, where operators are distinct from functions. However, is there any difference between the two in functional languages like Haskell where operators are functions too?
This distinctness (operators vs. functions) is purely syntactic, and is unrelated to the difference between inlining and partial evaluation:
Both function calls and expressions with operators can be inlined and compile-time evaluated in C. Compile-time evaluation is restricted to expressions over a fixed set of operators and functions (mostly operators, but that is historical accident)
Both concepts make sense and are distinct in Haskell.
- Inlining:
ghc
has{-# INLINE f #-}
, wheref
cannot be recursive, for obvious reasons, - Partial evaluation: this is usually generalised to Supercompilation where not only expressions of base type are transformed, but even functions, e.g. transforming
map f (map g xs
) intomap (f . g) xs
). It can (but need not) do inlining as well. Template Haskell is another way to (explicitely) evaluate part of a program at compile-time.
The answer to your title's question is thus: the difference between inlining and partial evaluation has nothing to do with the difference between functions and operators, and is much the same in functional languages as it is in C. Partial evaluation is probably more difficult in C because of side effects (cf the wiped hard disk above)