001package functions.one; 002interface ArrFun { 003 public int[] exec(int[] x); 004} 005 006interface IntFun { 007 public int exec(int x); 008} 009 010class Abs implements IntFun { 011 public int exec(int x) { 012 //SAME AS: if (x < 0) return -x; else return x; 013 return (x < 0) ? -x : x; 014 } 015} 016 017class Cube implements IntFun { 018 public int exec(int x) { 019 return x*x*x; 020 } 021} 022 023class Map implements ArrFun { 024 IntFun f; 025 public Map(IntFun f) { this.f = f; } 026 public int[] exec(int[] x) { 027 int[] answer = new int[x.length]; 028 for (int i=0; i<x.length; i++) { 029 answer[i] = f.exec(x[i]); 030 } 031 return answer; 032 } 033} 034 035class Main { 036 public static void print(int[] x) { 037 System.out.print("[ "); 038 for (int i=0; i<x.length; i++) 039 System.out.print(x[i]+ " "); 040 System.out.println("]"); 041 } 042 043 public static void main(String[] argv) { 044 IntFun f = new Abs(); 045 System.out.println(f.exec(-5)); 046 047 int[] a = new int[10]; 048 for (int i=0; i<a.length; i++) 049 a[i] = -i*10; 050 051 ArrFun mabs = new Map(new Comp(new Abs(), new Cube())); 052 print(mabs.exec(a)); 053 } 054} 055 056class Comp implements IntFun { 057 IntFun f, g; 058 public Comp(IntFun f, IntFun g) { this.f = f; this.g = g; } 059 public int exec(int x) { 060 return g.exec(f.exec(x)); 061 } 062}