This section exposed me to the full power and beauty of functional programming. The expressiveness of using functions as values is awesome. For example, a sum of cubes function can use a sum function which itself relies on a reduce function. Think of higher order differentiation in mathematics and you do get the idea.
An interesting concept involves using lambda function as operators, if the value of an expression is a function, then it can be used as an operator! This pattern allows using functions the same way numbers and strings are used. A derived usage can be found in JavaScript, which allows invoking function expressions using the function invocation operator ().
A lot of programmers are familiar with callbacks (which pass functions into functions). However callbacks might mask the full untapped potential of functional programming. A callback can be passed a function as a value – it doesn’t necessarily have to be a number / string all the time. The other issue with callbacks is that they do not return values and thus limit function composition.
There are no limits to using functions as values (provided there is language support). Alhamdulillaah I got my eye-opening experience after solving exercise 1.45. The main points are
- The repeated procedure accepts a procedure and returns a new procedure.
- Repeated’s return value (a procedure) also accepts a procedure as input (a lambda) and returns another new procedure.
- The final return value is then passed into the fixed-point procedure which does return a non-procedure value (although it can also be written to return a procedure).
The subtle trick was to realize that functions could be substituted with values and used in just about every way a value could be (provided you handle it right).
The amazing expressive power and flexibility comes at a cost though – first-class procedures are difficult to support in languages and this explains why few languages provide this. The main challenge is finding a way to safely store and retrieve the procedure’s free variables when it is not currently executing.
A free variable is defined on c2.com as any value that meets the following conditions:
- It is not defined in the body of a function
- It is not passed in as an input parameter
- It is not available in scope at the point of usage
Alhamdulillaah I completed the chapter in two weeks (I initially though it would take four). Chapter 2 is next with about 92 exercises, about 14 weeks insha Allaah? We’ll see!
3 thoughts on “SICP Section 1.3 : Thoughts and Concepts”