The objective of this code-along is to develop skills in restructuring expressions. The evaluation of an expression is performed through a sequence of computations. In some cases, such sequences contain redundant computations. When this happens variables can be declared to store the results of such computations.
The focus of this code-along is to generalize expression patterns using functions. More specifically, a function can be created that captures the computational similarity between patterns consisting of sequences involving sums. The pattern can then be re-expressed as an expression involving the newly created function.
(1 + 2 + 3) + (6 + 7 + 8)
|
(* version 1 *) let fun f x = x + (x+1) + (x+2); in f 1 + f 6 end; (* version 2 *) let val c = 1 + 2; fun f x = x + x + x + c; in f 1 + f 6 end |
(1 + 2 + 3 + 4) + (6 + 7 + 8 + 9)
|
let val c = 1 + 2 + 3; fun f x = let val x1 = x + x; val x2 = x1 + x1; in x2 + x2 + c end in f 1 + f 6 end |
(4 + 9 + 16) + (16 + 25 + 36)
|
let fun sq x = x * x; fun f x = sq(x) + sq(x+1) + sq(x+2); in f 1 + f 6 end |