Jules Jacobs
Posts: 119
Nickname: jules2
Registered: Mar, 2006
|
|
Re: Language Purity and Dirty and Clean Functions
|
Posted: Jun 28, 2006 3:59 AM
|
|
> 4) "Pure programs are easier to optimize". Yet no purely > written program can reach the overall performance of > C/C++. Isn't C/C++ supposed to be more difficult to > optimize?
I think you don't want to understand it, but anyway:
Suppose we have this program:
a = [1,2,3]
for i = 0; i < a.length; i++ a[i] = f(a[i]) end
for i = 0; i < a.length; i++ a[i] = g(a[i]) end
This could be optimized to:
a = [1,2,3]
for i = 0; i < a.length; i++ a[i] = g(f(a[i])) end
But this isn't possible or may not be easy in a language with side effects. You can't be sure that f has a side effect on which g depends.
If you consider the functional equivalent:
a = [1,2,3] map(map(a, f), g)
where f and g are pure functions, this optimization *is* possible:
a = [1,2,3] map(a, g . f)
The big problem is that functional programs run slower on regular computers, because instructions on a computer are imperative. Functional languages like Haskell don't work very well on the machines we have.
Cat is different. Cat uses the stack, and each function transforms the stack. Cat could probably be very efficient, because (1) Cat code is pretty close to the machine (imperative) (2) Cat code can be optimized like functional programs:
[1,2,3] [f] map [g] map => [1,2,3] [f g] map
This transformation is not possible unless you can guarantee that f and g are pure. In this case that means that they don't use I/O and they have to pop exactly one element off the stack, and push exactly one back.
|
|