Created
September 11, 2018 04:27
-
-
Save tlehman/ca6d1e96383be013474e43af16f98493 to your computer and use it in GitHub Desktop.
from ch2 of Elements of Programming
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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