Examples of Promises

What LazyImage actually is

class LazyImage { friend class IMAGE; virtual void fill_in(IMAGE& im) const = 0; protected: card nrows, ncols, depth; public: LazyImage(const card _nrows, const card _ncols, const card _depth) : nrows(_nrows), ncols(_ncols), depth(_depth) {} };



How to amend a recipe

class FractalMap : public LazyImage { public: FractalMap(const card order, const Seeds& _seeds = Seeds(128), const card bits_per_pixel=8); virtual int get_noise(const card scale) const; private: Seeds seeds; void fill_in(IMAGE& im) const; }; class GaussClouds : public FractalMap { public: GaussClouds(const card order) : FractalMap(order) {} // Well-known Gaussian random number generator inline int get_noise(const card scale) const {...} }; IMAGE image = GaussClouds(8);



Lazy vectors/matrices in Numerical Math

a boon:
when a function has to compute a brand new vector/matrix and return them
SVD svd(A);
cout << "condition number of matrix A " << svd.q_cond_number();
Vector x = SVD_inv_mult(svd,b); // Solution of Ax=b


The last function "left-divides" vector b by a (possibly non-square) matrix A. Since the function (a constructor, actually) returns just a promise of this division, the actual computation occurs when it's required (while constructing a new vector in the main function). Note, b doesn't have to be merely a vector, it can be a thick matrix, too.



An advanced example

// Adjusting an image to a suitable size class adjust_image : public LazyImage { bool do_coerce; const IMAGE& raw_image; void fill_in(IMAGE& im) const; public: adjust_image(const IMAGE& _raw_image); }; void adjust_image::fill_in(IMAGE& im) const { if( do_coerce ) im.coerce(raw_image); else im.rectangle(rowcol(0,0), rowcol(raw_image.q_nrows()-1,raw_image.q_ncols()-1)) = (Rectangle)raw_image; } static void compress_image(const char * image_file, const char * out_file) { IMAGE image(image_file); NCLaplPyr lp(suitable_image_p(image) ? image : (IMAGE)adjust_image(image),2); }



Next | Table of contents