Skip to content

Instantly share code, notes, and snippets.

@tlehman
Created September 11, 2018 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlehman/ca6d1e96383be013474e43af16f98493 to your computer and use it in GitHub Desktop.
Save tlehman/ca6d1e96383be013474e43af16f98493 to your computer and use it in GitHub Desktop.
from ch2 of Elements of Programming
/** Chapter 2 of "Elements of Programming": Transformations
*/
#define DistanceType(F) int
#define Domain(F) int
#define pointer(T) *T
template<typename T>
class Transformation {
public:
Transformation() {};
virtual T operator() (T x) = 0;
};
template<typename T>
class Square : public Transformation<T> {
public:
virtual T operator() (T x) { return x * x; }
};
DistanceType(F) distance(Domain(F) x, Domain(F) y, Square<int> f) {
typedef DistanceType(F) N;
// Precondition: y is reachable from x under f
N n(0);
while(x != y) {
x = f(x);
n += 1;
}
return n;
}
#include <iostream>
using namespace std;
int main() {
int x = 2;
int y = 256;
Square<int> f = Square<int>();
int d = distance(x, y, f);
cout << "the distance between " << x << " and "
<< y << " is " << d << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment