Added Abstraction.

This commit is contained in:
Jacob Signorovitch
2024-11-13 09:22:57 -05:00
parent 3913b3c4f3
commit f6cd74ff26
6 changed files with 170 additions and 13 deletions

View File

@@ -21,10 +21,10 @@ class Examples {
}
boolean testILoArmax(Tester t) {
return t.checkExpect(helloWorld.argmax(new IEvaluator<StrLen>()), "Hello, ")
&& t.checkExpect(helloAjcmsdj.argmax(new IEvaluator<StrLen>()), "Hello, ")
&& t.checkExpect(lint2.argmax(new IEvaluator<IntSize>()), 1)
&& t.checkExpect(lint.argmax(new IEvaluator<IntSize>()), 92);
return t.checkExpect(helloWorld.argmax(new StrLen()), "Hello, ")
&& t.checkExpect(helloAjcmsdj.argmax(new StrLen()), "Hello, ")
&& t.checkExpect(lint2.argmax(new IntSize()), 1)
&& t.checkExpect(lint.argmax(new IntSize()), 92);
}
@@ -35,22 +35,25 @@ interface IFunc<X, Y> {
Y apply(X input);
}
// Extracts the value of an input.
interface IEvaluator<X> extends IFunc<X, Integer> {}
// Calculate the length of a string.
class StrLen implements IFunc<String, Integer> { public Integer apply(String input) {
class StrLen implements IEvaluator<String> { public Integer apply(String input) {
return input.length();
}}
// Calculate the size of an integer.
class IntSize implements IFunc<Integer, Integer> { public Integer apply(Integer input) {
return input - 14;
class IntSize implements IEvaluator<Integer> { public Integer apply(Integer input) {
return input;
}}
// Extracts the value of an input.
interface IEvaluator<X> extends IFunc<X, Integer> {}
// A list of A.
interface ILo<A> {
ILo<A> append(ILo<A> a);
A argmax(IEvaluator<A> eval);
A argmaxHelper(IEvaluator<A> eval, A prev, Integer prevVal);
ILo<A> skip();
}
class Cons<A> implements ILo<A> {
@@ -64,8 +67,21 @@ class Cons<A> implements ILo<A> {
public ILo<A> append(ILo<A> a) { return new Cons<A>(this.first, this.rest.append(a)); }
public A argmax(IEvaluator<A> eval) {
return null;
public A argmax(IEvaluator<A> eval) {
return argmaxHelper(eval, this.first, eval.apply(this.first));
}
public A argmaxHelper(IEvaluator<A> eval, A prev, Integer prevVal) {
A now = this.first;
Integer nowVal = eval.apply(now);
return prevVal >= nowVal ?
this.rest.argmaxHelper(eval, prev, prevVal) :
this.rest.skip().argmaxHelper(eval, now, nowVal);
};
public ILo<A> skip() {
return this.rest;
}
}
@@ -74,4 +90,10 @@ class Mt<A> implements ILo<A> {
public A argmax(IEvaluator<A> eval) {
throw new UnsupportedOperationException("No max of empty list.");
}
}
public A argmaxHelper(IEvaluator<A> eval, A prev, Integer prevVal) {
return prev;
}
public ILo<A> skip() { return this; }
}