diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..6c0071a --- /dev/null +++ b/build.gradle @@ -0,0 +1,13 @@ +version '1.0-SNAPSHOT' + +apply plugin: 'java' + +sourceCompatibility = 1.5 + +repositories { + mavenCentral() +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.11' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..ca78035 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a6289bf --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Wed Oct 12 15:32:21 MSK 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.13-bin.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..27309d9 --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f6d5974 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..88a2644 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'FunctionalJava' + diff --git a/src/main/java/Collections.java b/src/main/java/Collections.java new file mode 100644 index 0000000..4de4b51 --- /dev/null +++ b/src/main/java/Collections.java @@ -0,0 +1,68 @@ +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +public class Collections { + public static List < DestType > map (Iterable iterable, + Function1 function) throws Exception { + List resList = new LinkedList(); + for (SourceType curElement: iterable) { + resList.add(function.apply(curElement)); + } + return resList; + } + + public static List filter(Iterable iterable, + Predicate predicate) throws Exception{ + List trueList = new LinkedList(); + for (T curElement : iterable) { + if (predicate.apply(curElement)) { + trueList.add(curElement); + } + } + return trueList; + } + + public static List takeWhile(Iterable iterable, + Predicate predicate) throws Exception { + List resList = new LinkedList(); + Iterator it = iterable.iterator(); + while (it.hasNext()) { + T curElem = it.next(); + if (!predicate.apply(curElem)) { + break; + } + resList.add(curElem); + } + return resList; + } + + public static List takeUnless(Iterable iterable, Predicate + predicate) throws Exception { + return takeWhile(iterable, predicate.not()); + } + + public static DestType foldl( + Function2 function, + DestType init, Iterable iterable) throws Exception { + DestType res = init; + for (SourceType elem : iterable) { + res = function.apply(res, elem); + } + return res; + } + + public static DestType foldr(Function2 function, + DestType init, Iterable iterable) throws Exception { + return foldrImpl(function, init, iterable.iterator()); + } + + private static DestType foldrImpl(Function2 function, + DestType init, Iterator iterator) throws Exception { + if (iterator.hasNext()) { + SourceType curElem = iterator.next(); + return function.apply(curElem, foldrImpl(function, init, iterator)); + } + return init; + } +} diff --git a/src/main/java/Function1.java b/src/main/java/Function1.java new file mode 100644 index 0000000..6ee796b --- /dev/null +++ b/src/main/java/Function1.java @@ -0,0 +1,12 @@ +public abstract class Function1 < ArgType, ValueType > { + public abstract ValueType apply(ArgType x) throws Exception; + + public < GValue > Function1 < ArgType, GValue > compose(final Function1 < ? super ValueType, GValue > g) { + return new Function1() { + @Override + public GValue apply(ArgType x) throws Exception{ + return g.apply(Function1.this.apply(x)); + } + }; + } +} diff --git a/src/main/java/Function2.java b/src/main/java/Function2.java new file mode 100644 index 0000000..07d4f9b --- /dev/null +++ b/src/main/java/Function2.java @@ -0,0 +1,44 @@ +public abstract class Function2 { + public abstract ValueType apply(ArgOneType x, ArgTwoType y) throws Exception; + + public < GValueType > Function2 compose(final Function1 < ? super ValueType, GValueType > g) { + return new Function2() { + @Override + public GValueType apply(ArgOneType x, ArgTwoType y) throws Exception { + return g.apply(Function2.this.apply(x, y)); + } + }; + } + + public Function1 bind1(final ArgOneType argOne) { + return new Function1 < ArgTwoType, ValueType > () { + @Override + public ValueType apply(ArgTwoType x) throws Exception { + return Function2.this.apply(argOne, x); + } + }; + } + + public Function1 bind2(final ArgTwoType argTwo) { + return new Function1 < ArgOneType, ValueType > () { + @Override + public ValueType apply(ArgOneType x) throws Exception { + return Function2.this.apply(x, argTwo); + } + }; + } + + public Function1> carry() { + return new Function1> () { + @Override + public Function1 apply(final ArgOneType x) { + return new Function1 () { + @Override + public ValueType apply(ArgTwoType y) throws Exception{ + return Function2.this.apply(x, y); + } + }; + } + }; + } +} \ No newline at end of file diff --git a/src/main/java/Predicate.java b/src/main/java/Predicate.java new file mode 100644 index 0000000..25d0c3f --- /dev/null +++ b/src/main/java/Predicate.java @@ -0,0 +1,44 @@ +public abstract class Predicate extends Function1 { + public abstract Boolean apply(ArgType x) throws Exception; + + public Predicate or(final Predicate other) { + return new Predicate() { + @Override + public Boolean apply(ArgType x) throws Exception{ + return Predicate.this.apply(x) || other.apply(x); + } + }; + } + + public Predicate and(final Predicate other) { + return new Predicate() { + @Override + public Boolean apply(ArgType x) throws Exception { + return Predicate.this.apply(x) && other.apply(x); + } + }; + } + + public Predicate not() { + return new Predicate() { + @Override + public Boolean apply(ArgType x) throws Exception { + return !Predicate.this.apply(x); + } + }; + } + + public static final Predicate ALWAYS_TRUE = new Predicate() { + @Override + public Boolean apply(Object x) { + return true; + } + }; + + public static final Predicate ALWAYS_FALSE = new Predicate() { + @Override + public Boolean apply(Object x) { + return false; + } + }; +} diff --git a/src/test/java/CollectionsTest.java b/src/test/java/CollectionsTest.java new file mode 100644 index 0000000..e4aded1 --- /dev/null +++ b/src/test/java/CollectionsTest.java @@ -0,0 +1,121 @@ +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +public class CollectionsTest { + private ArrayList numbers = new ArrayList(); + private final int TEST_LENGTH = 10; + + @Before + public void initTests() { + for (int i = 0; i < TEST_LENGTH; i++) { + numbers.add(i); + } + } + + @Test + public void filterTest() throws Exception { + List filtered = Collections.filter(numbers, new Predicate() { + @Override + public Boolean apply(Number x) { + return (Integer)x % 2 == 0; + } + }); + + for (int i = 0; i < TEST_LENGTH / 2; i++) { + Assert.assertEquals("Filter doesn't work correctly", + i * 2, filtered.get(i)); + } + } + + @Test + public void foldlTest() throws Exception { + String allNumsFoldl = Collections.foldl(new Function2() { + @Override + public String apply(String y, Integer x) { + return y.concat(x.toString()); + } + }, "", numbers); + + String allNums = ""; + for (int i = 0; i < TEST_LENGTH; i++) { + allNums += String.valueOf(i); + } + + Assert.assertEquals("Foldl doesn't work correctly.", allNums, allNumsFoldl); + } + + @Test + public void foldrTest() throws Exception { + String allNumsFoldr = Collections.foldr(new Function2() { + @Override + public String apply(Number x, String y) { + return y.concat(x.toString()); + } + }, "", numbers); + + String allNums = ""; + for (int i = TEST_LENGTH - 1; i >= 0; i--) { + allNums += String.valueOf(i); + } + + Assert.assertEquals("Foldr doesn't work correctly.", allNums, allNumsFoldr); + } + + @Test + public void mapTest() throws Exception { + List mapped = Collections.map(numbers, new Function1() { + @Override + public Character apply(Integer x) { + return (char)((int)'a' + (int)x); + } + }); + + Character[] answer = new Character[TEST_LENGTH]; + int letter = (int)'a'; + for (int i = 0; i < TEST_LENGTH; i++) { + answer[i] = (char)(i + (char)'a'); + } + Assert.assertArrayEquals("Map doesn't work correctly.", + answer, mapped.toArray()); + } + + @Test + public void takeUnlessTest() throws Exception { + List taken = Collections.takeUnless(numbers, new Predicate() { + @Override + public Boolean apply(Integer x) { + return x >= TEST_LENGTH / 2; + } + }); + + Integer[] answer = new Integer[TEST_LENGTH / 2]; + for (int i = 0; i < TEST_LENGTH / 2; i++) { + answer[i] = i; + } + + Assert.assertArrayEquals("TakeUnless works incorrectly.", + answer, taken.toArray()); + } + + @Test + public void takeWhileTest() throws Exception { + List taken = Collections.takeWhile(numbers, new Predicate() { + @Override + public Boolean apply(Number x) { + return (Integer)x < TEST_LENGTH / 2; + } + }); + + Integer[] answer = new Integer[TEST_LENGTH / 2]; + for (int i = 0; i < TEST_LENGTH / 2; i++) { + answer[i] = i; + } + + Assert.assertArrayEquals("TakeWhile works incorrectly.", + answer, taken.toArray()); + } +} diff --git a/src/test/java/Function1Test.java b/src/test/java/Function1Test.java new file mode 100644 index 0000000..627aa58 --- /dev/null +++ b/src/test/java/Function1Test.java @@ -0,0 +1,26 @@ +import org.junit.Assert; +import org.junit.Test; + +public class Function1Test { + @Test + public void composeTest() throws Exception { + Function1 square = new Function1() { + @Override + public Integer apply(Number x) { + return (Integer) x * (Integer)x; + } + }; + + Function1 duplicate = new Function1() { + @Override + public Integer apply(Number x) { + return 2 * (Integer)x; + } + }; + + Assert.assertEquals("Compose works incorrectly.", (Integer) 18, + square.compose(duplicate).apply(3)); + Assert.assertEquals("Compose works incorrectly.", (Integer)36, + duplicate.compose(square).apply(3)); + } +} diff --git a/src/test/java/Function2Test.java b/src/test/java/Function2Test.java new file mode 100644 index 0000000..db834e7 --- /dev/null +++ b/src/test/java/Function2Test.java @@ -0,0 +1,43 @@ +import org.junit.Assert; +import org.junit.Test; + +public class Function2Test { + private Function2 difference = new Function2() { + @Override + public Integer apply(Number x, Number y) { + return (Integer)x - (Integer)y; + } + }; + + private Function1 triple = new Function1() { + @Override + public Integer apply(Number x) { + return 3 * (Integer) x; + } + }; + + + @Test + public void composeTest() throws Exception { + Assert.assertEquals("Compose works incorrectly.", (Integer)6, + difference.compose(triple).apply(10, 8)); + } + + @Test + public void bind1Test() throws Exception { + Assert.assertEquals("Binding first argument works incorrectly.", + (Integer)3, difference.bind1(10).apply(7)); + } + + @Test + public void bind2Test() throws Exception { + Assert.assertEquals("Binding second argument doesn't work correctly.", + (Integer) 4, difference.bind2(6).apply(10)); + } + + @Test + public void carryTest() throws Exception { + Assert.assertEquals("Carry works incorrectly.", + (Integer)5, difference.carry().apply(10).apply(5)); + } +} diff --git a/src/test/java/PredicateTest.java b/src/test/java/PredicateTest.java new file mode 100644 index 0000000..7b4f9f9 --- /dev/null +++ b/src/test/java/PredicateTest.java @@ -0,0 +1,68 @@ +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.fail; + +public class PredicateTest { + @Test + public void testConstants() throws Exception { + Assert.assertTrue("ALWAYS_TRUE should return true for any input.", + Predicate.ALWAYS_TRUE.apply(null)); + Assert.assertFalse("ALWAYS_FALSE should return false for any input", + Predicate.ALWAYS_FALSE.apply(null)); + } + + @Test + public void testNot() throws Exception { + Assert.assertFalse("Not should invert the predicate value.", + Predicate.ALWAYS_TRUE.not().apply(null)); + Assert.assertTrue("Not should invert the predicate value.", + Predicate.ALWAYS_FALSE.not().apply(null)); + } + + @Test + public void testAnd() throws Exception { + Assert.assertTrue("And should perform conjunction.", + Predicate.ALWAYS_TRUE.and(Predicate.ALWAYS_TRUE).apply(null)); + Assert.assertFalse("And should perform conjunction.", + Predicate.ALWAYS_TRUE.and(Predicate.ALWAYS_FALSE).apply(null)); + Assert.assertFalse("And should perform conjunction.", + Predicate.ALWAYS_FALSE.and(Predicate.ALWAYS_TRUE).apply(null)); + Assert.assertFalse("And should perform conjunction.", + Predicate.ALWAYS_FALSE.and(Predicate.ALWAYS_FALSE).apply(null)); + + try { + Predicate.ALWAYS_FALSE.and(new Predicate() { + @Override + public Boolean apply(Object x) throws Exception { + throw new Exception(); + } + }).apply(new Object()); + } catch (Exception e) { + fail("And should be lazy."); + } + } + + @Test + public void testOr() throws Exception { + Assert.assertTrue("Or should perform disjunction.", + Predicate.ALWAYS_TRUE.or(Predicate.ALWAYS_TRUE).apply(null)); + Assert.assertTrue("Or should perform disjunction.", + Predicate.ALWAYS_TRUE.or(Predicate.ALWAYS_FALSE).apply(null)); + Assert.assertTrue("Or should perform disjunction.", + Predicate.ALWAYS_FALSE.or(Predicate.ALWAYS_TRUE).apply(null)); + Assert.assertFalse("Or should perform disjunction.", + Predicate.ALWAYS_FALSE.or(Predicate.ALWAYS_FALSE).apply(null)); + + try { + Predicate.ALWAYS_TRUE.or(new Predicate() { + @Override + public Boolean apply(Object x) throws Exception { + throw new Exception(); + } + }).apply(null); + } catch (Exception e) { + fail("Or should be lazy."); + } + } +}