├── .gitignore
├── .idea
├── .name
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── net
│ │ └── petitviolet
│ │ └── monad_example
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── net
│ │ │ └── petitviolet
│ │ │ └── monad_example
│ │ │ ├── MainActivity.java
│ │ │ ├── MainActivityFragment.java
│ │ │ └── SampleFragment.java
│ └── res
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ ├── content_main.xml
│ │ ├── fragment_main.xml
│ │ ├── fragment_plus_one.xml
│ │ └── input_column.xml
│ │ ├── menu
│ │ └── menu_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-v21
│ │ └── styles.xml
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── net
│ └── petitviolet
│ └── maybe_example
│ └── ExampleUnitTest.java
├── bintray.gradle.skelton
├── build.gradle
├── circle.yml
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── monad
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ └── java
│ │ └── net
│ │ └── petitviolet
│ │ └── monad
│ │ ├── Functor.java
│ │ ├── Identity.java
│ │ ├── Monad.java
│ │ ├── Tuple.java
│ │ ├── func
│ │ └── Function.java
│ │ ├── list
│ │ └── ListM.java
│ │ ├── maybe
│ │ ├── Just.java
│ │ ├── Maybe.java
│ │ └── None.java
│ │ ├── state
│ │ └── State.java
│ │ └── type
│ │ ├── IntM.java
│ │ └── Monoid.java
│ └── test
│ └── java
│ └── net
│ └── petitviolet
│ └── monad
│ ├── IdentityTest.java
│ ├── list
│ └── ListMTest.java
│ ├── maybe
│ └── MaybeTest.java
│ └── state
│ └── StateTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | ### https://raw.github.com/github/gitignore/2544a6b71027a1832e01f5c7f78bdfcea727f4ec/android.gitignore
10 |
11 | # Built application files
12 | *.apk
13 | *.ap_
14 |
15 | # Files for the Dalvik VM
16 | *.dex
17 |
18 | # Java class files
19 | *.class
20 |
21 | # Generated files
22 | bin/
23 | gen/
24 |
25 | # Gradle files
26 | .gradle/
27 | build/
28 |
29 | # Local configuration file (sdk path, etc)
30 | local.properties
31 |
32 | # Proguard folder generated by Eclipse
33 | proguard/
34 |
35 |
36 | /gradle.properties
37 | bintray.gradle
38 |
--------------------------------------------------------------------------------
/.idea/.name:
--------------------------------------------------------------------------------
1 | Android-Monad
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android-Monad
2 |
3 | [](https://circleci.com/gh/petitviolet/Android-Monad/tree/master)
4 | [ ](https://bintray.com/petitviolet/maven/android-monad/\_latestVersion)
5 | [](https://android-arsenal.com/details/1/2786)
6 |
7 | This repository is Yet Another Android-M.
8 |
9 | Implemented "Monadic" data structures.
10 |
11 | # Set up
12 |
13 | ```groovy
14 | dependencies {
15 | compile 'net.petitviolet.android:monad:latest-version'
16 | }
17 | ```
18 |
19 | And, I strongly recommend to use [orfjackal/retrolambda](https://github.com/orfjackal/retrolambda) together.
20 |
21 | # How to Use
22 |
23 | ## Maybe
24 |
25 | The name of `Maybe` is derived from Haskell.
26 | In Scala, `Option`.
27 |
28 | ```java
29 | // with lambda
30 | Maybe maybeInt = Maybe.of(x);
31 | maybeInt.flatMap(integer -> Maybe.of(integer % 2 == 0 ? integer : null))
32 | .map(integer -> integer + 5)
33 | .filter(integer -> integer % 3 == 0)
34 | .foreach(integer -> Log.d(TAG, "result: " + integer));
35 |
36 | // without lambda
37 | maybeInt.flatMap(new Function.F1>() {
38 | @Override
39 | public Maybe invoke(Integer integer) {
40 | return Maybe.of(integer % 2 == 0 ? integer : null);
41 | }
42 | }).map(new Function.F1() {
43 | @Override
44 | public Integer invoke(Integer integer) {
45 | return integer + 5;
46 | }
47 | }).filter(new Function.F1() {
48 | @Override
49 | public Boolean invoke(Integer integer) {
50 | return integer % 3 == 0;
51 | }
52 | }).foreach(new Function.F() {
53 | @Override
54 | public void invoke(Integer integer) {
55 | Log.d(TAG, "result: " + integer);
56 | }
57 | });
58 | ```
59 |
60 | More detailes of `Maybe` interface is shown in [MaybeTest.java](https://github.com/petitviolet/Android-Monad/blob/master/monad%2Fsrc%2Ftest%2Fjava%2Fnet%2Fpetitviolet%2Fmaybe%2FMaybeTest.java).
61 |
62 | ## ListM
63 |
64 | Implemented `ListM` based on `ArrayList` as a implementation of `List` interface.
65 |
66 | ```java
67 | ListM listM = ListM.unit();
68 | listM.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
69 | ListM result = listM.filter(i -> i % 3 == 0)
70 | .flatMap(i -> ListM.of(i * 10))
71 | .map(s -> s + "!");
72 | .foldRight((a, acc) -> a + ", " + acc, " <= end");
73 | // result -> 90!, 60!, 30!, <= end
74 | ```
75 |
76 | More detailes of `ListM` interface is shown in [ListMTest.java](https://github.com/petitviolet/Android-Monad/blob/master/monad%2Fsrc%2Ftest%2Fjava%2Fnet%2Fpetitviolet%2Flist%2FListMTest.java).
77 |
78 | ## State
79 |
80 | State monad.
81 | Sequencial computations share a state, and each of them uses the state and modify or not, then pass it to next computation.
82 |
83 | ```java
84 | // state is List, and value is Integer
85 | Tuple> result =
86 | State.init((List strings) -> {
87 | // modify state
88 | strings.add("nice");
89 | // value is 1
90 | return Tuple.of(1, strings);
91 | }).map(i -> {
92 | // apply function to value of State
93 | return i + 10;
94 | }).map(i -> {
95 | // apply function to value of State
96 | return i * 2;
97 | }).flatMap(integer -> {
98 | // apply function to value of State
99 | return State.init(strings -> {
100 | if (integer % 2 == 0) {
101 | // modify state
102 | strings.add("awesome");
103 | return Tuple.of(integer, strings);
104 | } else {
105 | // modify state
106 | strings.add("Oops");
107 | return Tuple.of(-100, strings);
108 | }
109 | });
110 | // empty list is given as the first state of above sequencial computations
111 | }).apply(new ArrayList<>());
112 | assert result._1 == 22;
113 | assert result._2 == List("nice", "awesome"); // dummy code
114 | ```
115 |
116 | # Identity
117 |
118 | Id monad.
119 | Have a value and do nothing.
120 | Just monadic.
121 |
122 | ```java
123 | Identity id = Identity.id("hoge");
124 | Identity result = id.flatMap(new Function.F1>() {
125 | @Override
126 | public Identity invoke(String s) {
127 | return Identity.id(s.length());
128 | }
129 | });
130 | assert result.value.equals(4);
131 | ```
132 |
133 | # Lisence
134 |
135 | This code is licensed under the Apache Software License 2.0.
136 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'me.tatarka.retrolambda'
3 |
4 | android {
5 | compileSdkVersion 23
6 | buildToolsVersion "23.0.1"
7 |
8 | defaultConfig {
9 | applicationId "net.petitviolet.maybe_example"
10 | minSdkVersion 15
11 | targetSdkVersion 23
12 | versionCode 1
13 | versionName "1.0"
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | compileOptions {
22 | sourceCompatibility JavaVersion.VERSION_1_8
23 | targetCompatibility JavaVersion.VERSION_1_8
24 | }
25 | }
26 |
27 | dependencies {
28 | compile fileTree(dir: 'libs', include: ['*.jar'])
29 | testCompile 'junit:junit:4.12'
30 | compile project(':monad')
31 | // compile 'net.petitviolet.android:monad:0.1.0'
32 | compile 'com.android.support:appcompat-v7:23.1.0'
33 | compile 'com.android.support:design:23.1.0'
34 | compile 'com.android.support:support-v4:23.1.0'
35 | }
36 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/petitviolet/android-sdks/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.unit.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/net/petitviolet/monad_example/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad_example;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
14 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/java/net/petitviolet/monad_example/MainActivity.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad_example;
2 |
3 | import android.os.Bundle;
4 | import android.support.design.widget.FloatingActionButton;
5 | import android.support.design.widget.Snackbar;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.support.v7.widget.Toolbar;
8 | import android.util.Log;
9 | import android.view.Menu;
10 | import android.view.MenuItem;
11 |
12 | import net.petitviolet.monad.Tuple;
13 | import net.petitviolet.monad.func.Function;
14 | import net.petitviolet.monad.list.ListM;
15 | import net.petitviolet.monad.maybe.Maybe;
16 | import net.petitviolet.monad.state.State;
17 |
18 | import java.util.ArrayList;
19 | import java.util.Arrays;
20 | import java.util.List;
21 |
22 | public class MainActivity extends AppCompatActivity {
23 | private static final String TAG = MainActivity.class.getSimpleName();
24 |
25 | @Override
26 | protected void onCreate(Bundle savedInstanceState) {
27 | super.onCreate(savedInstanceState);
28 | setContentView(R.layout.activity_main);
29 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
30 | setSupportActionBar(toolbar);
31 |
32 | FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
33 | fab.setOnClickListener(view -> {
34 | testMaybeWithLambda(3);
35 | testMaybeWithLambda(100);
36 | testMaybeOldStyle(null);
37 | testListMWithLambda();
38 | sampleState();
39 | Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
40 | .setAction("Action", null).show();
41 | });
42 | }
43 |
44 | private Maybe findByNumber(Integer target) {
45 | List sourceList = Arrays.asList(2, 3, 5, 7, 9, 11);
46 | return Maybe.of(sourceList.contains(target) ? sourceList.indexOf(target) : null);
47 | }
48 |
49 | private void testMaybeWithLambda(Integer x) {
50 | Log.d(TAG, "lambda start↓↓↓↓↓↓↓↓↓↓");
51 | Maybe maybeInt = Maybe.of(x);
52 | Log.d(TAG, "maybeInt:" + maybeInt);
53 | maybeInt
54 | .flatMap(this::findByNumber)
55 | .map(integer -> integer + 5)
56 | .filter(integer -> integer % 2 == 0)
57 | .foreach(integer -> Log.d(TAG, "result: " + integer));
58 | Log.d(TAG, "lambda end↑↑↑↑↑↑↑↑↑↑");
59 | }
60 |
61 | private void testMaybeOldStyle(Integer x) {
62 | Log.d(TAG, "oldstyle start↓↓↓↓↓↓↓↓↓↓");
63 |
64 | Maybe maybeInt = Maybe.of(x);
65 | Log.d(TAG, "maybeInt:" + maybeInt);
66 | maybeInt.flatMap(new Function.F1>() {
67 | @Override
68 | public Maybe invoke(Integer integer) {
69 | return Maybe.of(integer * 2);
70 | }
71 | }).map(new Function.F1() {
72 | @Override
73 | public Integer invoke(Integer integer) {
74 | return integer + 5;
75 | }
76 | }).filter(new Function.F1() {
77 | @Override
78 | public Boolean invoke(Integer integer) {
79 | return integer % 2 == 0;
80 | }
81 | }).foreach(new Function.F() {
82 | @Override
83 | public void invoke(Integer integer) {
84 | Log.d(TAG, "result: " + integer);
85 | }
86 | });
87 |
88 | Log.d(TAG, "oldstyle end↑↑↑↑↑↑↑↑↑↑");
89 | }
90 |
91 | private void testListMWithLambda() {
92 | ListM listM = ListM.unit();
93 | listM.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
94 | ListM seed = listM.filter(i -> i % 2 == 0)
95 | .flatMap(this::alphabets)
96 | .map(s -> s + "!")
97 | .map(s -> {
98 | Log.d(TAG, s);
99 | return s;
100 | });
101 | String rightResult = seed.foldRight((a, acc) -> a + ", " + acc, " <= end");
102 | String leftResult = seed.foldLeft("start -> ", (acc, a) -> acc + ", " + a);
103 | Log.d(TAG, "resultRight => " + rightResult);
104 | Log.d(TAG, "resultLeft => " + leftResult);
105 | }
106 |
107 | private static final ListM ALPHABETS = ListM.unit();
108 |
109 | static {
110 | for (char a = 'a'; a <= 'z'; a++) {
111 | ALPHABETS.add(String.valueOf(a));
112 | }
113 | }
114 |
115 | private ListM alphabets(int num) {
116 | return ALPHABETS.subList(0, num <= ALPHABETS.size() ? num : ALPHABETS.size());
117 | }
118 |
119 | private void sampleState() {
120 | Tuple> result =
121 | State.init((List strings) -> {
122 | strings.add("nice");
123 | return Tuple.of(1, strings);
124 |
125 | }).map(i -> {
126 | return i + 6;
127 | }).map(i -> {
128 | return i * 3;
129 | }).flatMap(integer -> {
130 | return State.init(strings -> {
131 | if (integer == 42) {
132 | strings.add("awesome");
133 | return Tuple.of(integer, strings);
134 | } else {
135 | strings.add("Oops");
136 | return Tuple.of(-100, strings);
137 | }
138 | });
139 | }).apply(new ArrayList<>());
140 | Log.d(TAG, "State -> " + result.toString());
141 | }
142 |
143 | private void combineMaybeListM() {
144 | ListM.of(1, 2, 3, 4, 5)
145 | .map(i -> i * 2)
146 | .bindMaybe(Maybe::of)
147 | .foreach(System.out::println);
148 | }
149 |
150 | @Override
151 | public boolean onCreateOptionsMenu(Menu menu) {
152 | // Inflate the menu; this adds items to the action bar if it is present.
153 | getMenuInflater().inflate(R.menu.menu_main, menu);
154 | return true;
155 | }
156 |
157 | @Override
158 | public boolean onOptionsItemSelected(MenuItem item) {
159 | int id = item.getItemId();
160 |
161 | if (id == R.id.action_settings) {
162 | return true;
163 | }
164 |
165 | return super.onOptionsItemSelected(item);
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/app/src/main/java/net/petitviolet/monad_example/MainActivityFragment.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad_example;
2 |
3 | import android.os.Bundle;
4 | import android.support.v4.app.ListFragment;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 |
9 | /**
10 | * A placeholder fragment containing a simple view.
11 | */
12 | public class MainActivityFragment extends ListFragment {
13 |
14 | public MainActivityFragment() {
15 | }
16 |
17 | @Override
18 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
19 | Bundle savedInstanceState) {
20 | return inflater.inflate(R.layout.fragment_main, container, false);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/java/net/petitviolet/monad_example/SampleFragment.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad_example;
2 |
3 | import android.os.Bundle;
4 | import android.support.v4.app.Fragment;
5 | import android.text.TextUtils;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 | import android.widget.Button;
10 | import android.widget.CheckBox;
11 | import android.widget.EditText;
12 | import android.widget.TextView;
13 |
14 | import net.petitviolet.monad.Tuple;
15 | import net.petitviolet.monad.list.ListM;
16 |
17 | public class SampleFragment extends Fragment {
18 | private Button mAddFormButton;
19 | private TextView mSumTextView;
20 | private TextView mIncomeTextView;
21 | private TextView mOutcomeTextView;
22 | private ListM mFormLayoutList;
23 |
24 | public SampleFragment() {
25 | }
26 |
27 | public static SampleFragment newInstance() {
28 | SampleFragment fragment = new SampleFragment();
29 | Bundle args = new Bundle();
30 | fragment.setArguments(args);
31 | return fragment;
32 | }
33 |
34 | @Override
35 | public void onCreate(Bundle savedInstanceState) {
36 | super.onCreate(savedInstanceState);
37 | }
38 |
39 | @Override
40 | public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
41 | Bundle savedInstanceState) {
42 | View view = inflater.inflate(R.layout.fragment_plus_one, container, false);
43 | mAddFormButton = (Button) view.findViewById(R.id.button_add_form);
44 | mSumTextView = (TextView) view.findViewById(R.id.textview_sum);
45 | mIncomeTextView = (TextView) view.findViewById(R.id.textview_income);
46 | mOutcomeTextView = (TextView) view.findViewById(R.id.textview_outcome);
47 | final ViewGroup formContainer = (ViewGroup) view.findViewById(R.id.form_container);
48 | mFormLayoutList = ListM.of(formContainer);
49 |
50 | mAddFormButton.setOnClickListener(v -> {
51 | Tuple, ListM> partitionLayouts = mFormLayoutList.partition(layout -> ((CheckBox) layout.findViewById(R.id.select_plus_or_minus)).isChecked());
52 |
53 | int income = partitionLayouts._1
54 | .map(layout -> ((EditText) layout.findViewById(R.id.input_number)).getText().toString())
55 | .filter(s -> !TextUtils.isEmpty(s))
56 | .map(Integer::parseInt)
57 | .foldLeft(0, (acc, i) -> acc + i);
58 |
59 | int outcome = partitionLayouts._2
60 | .map(layout -> ((EditText) layout.findViewById(R.id.input_number)).getText().toString())
61 | .filter(s -> !TextUtils.isEmpty(s))
62 | .map(Integer::parseInt)
63 | .foldRight((acc, i) -> acc + i, 0);
64 |
65 | mIncomeTextView.setText("¥" + income);
66 | mOutcomeTextView.setText("¥ -" + outcome);
67 | mSumTextView.setText("¥" + (income - outcome));
68 |
69 | View formLayout = inflater.inflate(R.layout.input_column, container, false);
70 | formContainer.addView(formLayout);
71 | mFormLayoutList.add(formLayout);
72 | });
73 |
74 | return view;
75 | }
76 |
77 | @Override
78 | public void onResume() {
79 | super.onResume();
80 | }
81 |
82 | @Override
83 | public void onDetach() {
84 | super.onDetach();
85 | }
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
15 |
16 |
22 |
23 |
24 |
25 |
26 |
27 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/content_main.xml:
--------------------------------------------------------------------------------
1 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_main.xml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
19 |
20 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_plus_one.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
14 |
15 |
23 |
24 |
32 |
33 |
41 |
42 |
43 |
49 |
50 |
59 |
60 |
67 |
68 |
75 |
76 |
83 |
84 |
85 |
91 |
92 |
97 |
98 |
99 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/input_column.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
21 |
22 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/petitviolet/Android-Monad/845b12aaf6e6cae55566e36c4ef6b8997157391a/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/petitviolet/Android-Monad/845b12aaf6e6cae55566e36c4ef6b8997157391a/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/petitviolet/Android-Monad/845b12aaf6e6cae55566e36c4ef6b8997157391a/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/petitviolet/Android-Monad/845b12aaf6e6cae55566e36c4ef6b8997157391a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/petitviolet/Android-Monad/845b12aaf6e6cae55566e36c4ef6b8997157391a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 | >
2 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 16dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Example
3 | Settings
4 | Add Form
5 | 0
6 | 項目
7 | 収入?
8 | 金額
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/test/java/net/petitviolet/maybe_example/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad_example;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/bintray.gradle.skelton:
--------------------------------------------------------------------------------
1 | bintray_user=
2 | bintray_api_key=
3 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:1.3.0'
9 | classpath 'me.tatarka:gradle-retrolambda:3.2.3'
10 |
11 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.+'
12 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | jcenter()
21 | }
22 | }
23 |
24 | task clean(type: Delete) {
25 | delete rootProject.buildDir
26 | }
27 |
--------------------------------------------------------------------------------
/circle.yml:
--------------------------------------------------------------------------------
1 | machine:
2 | java:
3 | version: openjdk7
4 | environment:
5 | ANDROID_HOME: /usr/local/android-sdk-linux
6 | # JAVA_OPTS: "-Xmx1048m -XX:MaxPermSize=512m"
7 |
8 | dependencies:
9 | pre:
10 | - echo y | android update sdk --no-ui --all --filter "android-23,build-tools-23.0.1"
11 | - echo y | android update sdk --no-ui --all --filter "extra-android-m2repository,extra-android-support"
12 |
13 | override:
14 | - ./gradlew monad:dependencies
15 |
16 | test:
17 | override:
18 | - ./gradlew clean monad:test -PdisablePreDex
19 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/petitviolet/Android-Monad/845b12aaf6e6cae55566e36c4ef6b8997157391a/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Oct 24 19:05:44 JST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/monad/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/monad/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 |
4 | android {
5 | compileSdkVersion 23
6 | buildToolsVersion "23.0.1"
7 |
8 | defaultConfig {
9 | minSdkVersion 9
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile "com.android.support:support-annotations:23.1.1"
26 | }
27 |
28 | apply plugin: 'com.github.dcendents.android-maven'
29 | apply plugin: 'com.jfrog.bintray'
30 |
31 | group = 'net.petitviolet.android'
32 | version = '0.5.2'
33 | def siteUrl = 'https://github.com/petitviolet/android-monad'
34 | def gitUrl = 'https://github.com/petitviolet/android-monad.git'
35 |
36 | def bintrayProps = new Properties()
37 | def bintrayFile = new File("bintray.gradle")
38 | if (bintrayFile.exists()) {
39 | bintrayProps.load(new FileInputStream("bintray.gradle"))
40 | } else {
41 | bintrayProps.load(new FileInputStream("bintray.gradle.skelton"))
42 | }
43 |
44 | bintray {
45 | user = bintrayProps["bintray_user"]
46 | key = bintrayProps["bintray_api_key"]
47 |
48 | configurations = ['archives'] //When uploading configuration files
49 | pkg {
50 | repo = 'maven'
51 | name = 'android-monad'
52 | desc = 'Monadic data structures like Scala'
53 | websiteUrl = siteUrl
54 | issueTrackerUrl = 'https://github.com/petitviolet/android-monad/issues'
55 | vcsUrl = gitUrl
56 | licenses = ['Apache-2.0']
57 | labels = ['android']
58 | publicDownloadNumbers = true
59 | }
60 | }
61 |
62 | install {
63 | repositories.mavenInstaller {
64 | pom {
65 | project {
66 | packaging 'aar'
67 | name 'android-monad'
68 | url siteUrl
69 | licenses {
70 | license {
71 | name 'The Apache Software License, Version 2.0'
72 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
73 | }
74 | }
75 | developers {
76 | developer {
77 | id 'petitviolet'
78 | name 'Hiroki Komurasaki'
79 | email 'violethero0820@gmail.com'
80 | }
81 | }
82 | scm {
83 | connection gitUrl
84 | developerConnection gitUrl
85 | url siteUrl
86 | }
87 | }
88 | }
89 | }
90 | }
91 |
92 | task sourcesJar(type: Jar) {
93 | from android.sourceSets.main.java.srcDirs
94 | classifier = 'sources'
95 | }
96 |
97 | task javadoc(type: Javadoc) {
98 | source = android.sourceSets.main.java.srcDirs
99 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
100 | }
101 |
102 | task javadocJar(type: Jar, dependsOn: javadoc) {
103 | classifier = 'javadoc'
104 | from javadoc.destinationDir
105 | }
106 | artifacts {
107 | archives javadocJar
108 | archives sourcesJar
109 | }
110 |
111 | task findConventions << {
112 | println project.getConvention()
113 | }
114 |
--------------------------------------------------------------------------------
/monad/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/petitviolet/android-sdks/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/monad/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/Functor.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad;
2 |
3 | import net.petitviolet.monad.func.Function;
4 |
5 | public interface Functor> {
6 | F map(Function.F1 super A, ? extends B> func);
7 | }
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/Identity.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad;
2 |
3 | import net.petitviolet.monad.func.Function;
4 |
5 | public class Identity implements Monad> {
6 | public final A value;
7 |
8 | public Identity(A value) {
9 | this.value = value;
10 | }
11 |
12 | public static Identity id(A value) {
13 | return new Identity<>(value);
14 | }
15 |
16 | @Override
17 | public boolean equals(Object o) {
18 | if (o instanceof Identity) {
19 | return ((Identity) o).value.equals(value);
20 | }
21 | return super.equals(o);
22 | }
23 |
24 | @Override
25 | public String toString() {
26 | return "Identity{" + "value=" + value + '}';
27 | }
28 |
29 | @Override
30 | public Identity flatMap(Function.F1 super A, ? extends Identity>> f) {
31 | return (Identity) f.invoke(value);
32 | }
33 |
34 | @Override
35 | public Identity map(Function.F1 super A, ? extends B> func) {
36 | return Identity.id(func.invoke(value));
37 | }
38 | }
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/Monad.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad;
2 |
3 | import net.petitviolet.monad.func.Function;
4 |
5 | public interface Monad> extends Functor {
6 | M flatMap(Function.F1 super A, ? extends M> f);
7 | }
8 |
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/Tuple.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad;
2 |
3 | public class Tuple {
4 | public final A _1;
5 | public final B _2;
6 |
7 | @Override
8 | public String toString() {
9 | return "Tuple(" + _1 + ", " + _2 + ")";
10 | }
11 |
12 | private Tuple(A _1, B _2) {
13 | this._1 = _1;
14 | this._2 = _2;
15 | }
16 |
17 | public static Tuple of(A fst, B snd) {
18 | return new Tuple<>(fst, snd);
19 | }
20 | }
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/func/Function.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad.func;
2 |
3 | public interface Function {
4 | interface F extends Function {
5 | void invoke(A a);
6 | }
7 |
8 | interface F0 extends Function {
9 | A invoke();
10 | }
11 |
12 | interface F1 extends Function {
13 | B invoke(A a);
14 | }
15 | interface F2 extends Function {
16 | C invoke(A a, B b);
17 | }
18 | }
19 |
20 |
21 |
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/list/ListM.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad.list;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import net.petitviolet.monad.Tuple;
6 | import net.petitviolet.monad.func.Function;
7 | import net.petitviolet.monad.maybe.Maybe;
8 |
9 | import java.util.ArrayList;
10 | import java.util.Arrays;
11 | import java.util.Collection;
12 | import java.util.Collections;
13 | import java.util.Iterator;
14 | import java.util.List;
15 | import java.util.ListIterator;
16 |
17 | public class ListM implements List {
18 | private final List mList;
19 |
20 | private ListM(List mList) {
21 | this.mList = mList;
22 | }
23 |
24 | private ListM() {
25 | this.mList = new ArrayList<>();
26 | }
27 |
28 | public static ListM unit() {
29 | return new ListM<>();
30 | }
31 |
32 | @SafeVarargs
33 | public static ListM of(A... args) {
34 | ListM listM = ListM.unit();
35 | Collections.addAll(listM, args);
36 | return listM;
37 | }
38 |
39 | public static ListM of(List list) {
40 | return new ListM<>(list);
41 | }
42 |
43 |
44 | @Override
45 | public boolean equals(Object o) {
46 | if (!(o instanceof ListM) || ((ListM) o).size() != this.size()) {
47 | return false;
48 | }
49 | for (int i = 0; i < ((ListM) o).size(); i++) {
50 | if (!((ListM) o).get(i).equals(this.get(i))) {
51 | return false;
52 | }
53 | }
54 | return true;
55 | }
56 |
57 | @Override
58 | public A get(int location) {
59 | return mList.get(location);
60 | }
61 |
62 | @Override
63 | public int hashCode() {
64 | return mList.hashCode();
65 | }
66 |
67 | @Override
68 | public int indexOf(Object object) {
69 | return mList.indexOf(object);
70 | }
71 |
72 | @Override
73 | public boolean isEmpty() {
74 | return mList.isEmpty();
75 | }
76 |
77 | @NonNull
78 | @Override
79 | public Iterator iterator() {
80 | return mList.iterator();
81 | }
82 |
83 | @Override
84 | public int lastIndexOf(Object object) {
85 | return mList.lastIndexOf(object);
86 | }
87 |
88 | @Override
89 | public ListIterator listIterator() {
90 | return mList.listIterator();
91 | }
92 |
93 | @NonNull
94 | @Override
95 | public ListIterator listIterator(int location) {
96 | return mList.listIterator(location);
97 | }
98 |
99 | @Override
100 | public A remove(int location) {
101 | return mList.remove(location);
102 | }
103 |
104 | @Override
105 | public boolean remove(Object object) {
106 | return mList.remove(object);
107 | }
108 |
109 | @Override
110 | public boolean removeAll(Collection> collection) {
111 | return mList.removeAll(collection);
112 | }
113 |
114 | @Override
115 | public boolean retainAll(Collection> collection) {
116 | return mList.retainAll(collection);
117 | }
118 |
119 | @Override
120 | public A set(int location, A object) {
121 | return mList.set(location, object);
122 | }
123 |
124 | @Override
125 | public int size() {
126 | return mList.size();
127 | }
128 |
129 | @NonNull
130 | @Override
131 | public ListM subList(int start, int end) {
132 | List sublist = mList.subList(start, end);
133 | ListM listM = ListM.unit();
134 | for (A item : sublist) {
135 | listM.add(item);
136 | }
137 | return listM;
138 | }
139 |
140 | @NonNull
141 | @Override
142 | public Object[] toArray() {
143 | return mList.toArray();
144 | }
145 |
146 | @NonNull
147 | @Override
148 | public T[] toArray(T[] array) {
149 | return mList.toArray(array);
150 | }
151 |
152 |
153 | public Maybe maybeGet(int index) {
154 | if (index >= this.size()) {
155 | return Maybe.of(null);
156 | }
157 | return Maybe.of(get(index));
158 | }
159 |
160 | public A getOrElse(int index, A defaultValue) {
161 | return maybeGet(index).getOrElse(defaultValue);
162 | }
163 |
164 | public B foldLeft(B acc, Function.F2 super B, ? super A, ? super B> func) {
165 | for (A item : this) {
166 | acc = (B) func.invoke(acc, item);
167 | }
168 | return acc;
169 | }
170 |
171 | public B foldRight(Function.F2 super A, ? super B, ? super B> func, B acc) {
172 | for (A item : this) {
173 | acc = (B) func.invoke(item, acc);
174 | }
175 | return acc;
176 | }
177 |
178 | public B foldMap(B acc, Function.F1 super A, ? extends B> converter,
179 | Function.F2 super B, ? super B, ? extends B> accumulator) {
180 | B result = acc;
181 | for (A item : this) {
182 | result = accumulator.invoke(result, converter.invoke(item));
183 | }
184 | return result;
185 | }
186 |
187 | public void foreach(Function.F super A> func) {
188 | for (A item : this) {
189 | func.invoke(item);
190 | }
191 | }
192 |
193 | public ListM map(Function.F1 super A, ? extends B> func) {
194 | ListM result = new ListM<>();
195 | for (A item : this) {
196 | result.add(func.invoke(item));
197 | }
198 | return result;
199 | }
200 |
201 | public ListM bindMaybe(Function.F1 super A, Maybe> func) {
202 | ListM result = new ListM<>();
203 | for (A item : this) {
204 | Maybe b = func.invoke(item);
205 | if (b.isPresent()) {
206 | result.add(b.get());
207 | }
208 | }
209 | return result;
210 | }
211 |
212 | public ListM flatMap(Function.F1 super A, ? extends ListM> func) {
213 | // use flatMap is not effective from the viewpoint of performance
214 | // return flatMap(new Function.F1>() {
215 | // @SuppressWarnings("unchecked")
216 | // @Override
217 | // public ListM invoke(A a) {
218 | // return ListM.of(func.invoke(a));
219 | // }
220 | // });
221 | ListM result = new ListM<>();
222 | for (A item : this) {
223 | result.addAll(func.invoke(item));
224 | }
225 | return result;
226 | }
227 |
228 | public ListM filter(Function.F1 super A, Boolean> func) {
229 | ListM result = new ListM<>();
230 | for (A item : this) {
231 | if (func.invoke(item)) {
232 | result.add(item);
233 | }
234 | }
235 | return result;
236 | }
237 |
238 | public ListM filterNot(Function.F1 super A, Boolean> func) {
239 | ListM that = this;
240 | ListM result = filter(func);
241 | that.removeAll(result);
242 | return that;
243 | }
244 |
245 | public Tuple, ListM> partition(final Function.F1 super A, Boolean> func) {
246 | ListM fst = this.filter(func);
247 | ListM snd = this.filter(new Function.F1() {
248 | @Override
249 | public Boolean invoke(A a) {
250 | return !func.invoke(a);
251 | }
252 | });
253 |
254 | return Tuple.of(fst, snd);
255 | }
256 |
257 | @Override
258 | public void add(int location, A object) {
259 | mList.add(location, object);
260 | }
261 |
262 | @Override
263 | public boolean add(A object) {
264 | return mList.add(object);
265 | }
266 |
267 | @Override
268 | public boolean addAll(int location, Collection extends A> collection) {
269 | return mList.addAll(location, collection);
270 | }
271 |
272 | @Override
273 | public boolean addAll(Collection extends A> collection) {
274 | return mList.addAll(collection);
275 | }
276 |
277 | @Override
278 | public void clear() {
279 | mList.clear();
280 | }
281 |
282 | @Override
283 | public boolean contains(Object object) {
284 | return mList.contains(object);
285 | }
286 |
287 | @Override
288 | public boolean containsAll(Collection> collection) {
289 | return mList.containsAll(collection);
290 | }
291 |
292 | @Override
293 | public String toString() {
294 | return "ListM{ " + Arrays.toString(mList.toArray()) + " }";
295 | }
296 | }
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/maybe/Just.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad.maybe;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import net.petitviolet.monad.func.Function;
6 |
7 | class Just extends Maybe {
8 | private final A mTarget;
9 |
10 | Just(@NonNull A target) {
11 | mTarget = target;
12 | }
13 |
14 | @Override
15 | public String toString() {
16 | return "Just{" + mTarget + "}";
17 | }
18 |
19 | @Override
20 | public A get() {
21 | return mTarget;
22 | }
23 |
24 | @Override
25 | public A getOrElse(A defaultValue) {
26 | return get();
27 | }
28 |
29 | @Override
30 | public void foreach(Function.F super A> func) {
31 | func.invoke(mTarget);
32 | }
33 |
34 | @Override
35 | public Maybe flatMap(Function.F1 super A, ? extends Maybe> func) {
36 | return func.invoke(mTarget);
37 | }
38 |
39 | @Override
40 | public Maybe filter(Function.F1 super A, Boolean> func) {
41 | if (func.invoke(mTarget)) {
42 | return this;
43 | } else {
44 | return new None<>();
45 | }
46 | }
47 | }
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/maybe/Maybe.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad.maybe;
2 |
3 | import android.support.annotation.Nullable;
4 |
5 | import net.petitviolet.monad.func.Function;
6 |
7 | /**
8 | * Maybe monad
9 | * null = None
10 | * some value = Just
11 | * @param
12 | */
13 | abstract public class Maybe {
14 | // abstract public class Maybe { //implements Monad> {
15 | // if implements Monad interface, type inference does not work properly...
16 |
17 | @Override
18 | public boolean equals(Object object) {
19 | if (object instanceof Just && this instanceof Just) {
20 | return ((Maybe) object).get().equals(get());
21 | } else if (object instanceof None && this instanceof None) {
22 | return true;
23 | } else {
24 | return false;
25 | }
26 | }
27 |
28 | abstract public A get();
29 |
30 | public A getOrElse(A defaultValue) {
31 | return isPresent() ? get() : defaultValue;
32 | }
33 |
34 | abstract public void foreach(Function.F super A> func);
35 |
36 | public Maybe map(final Function.F1 super A, ? extends B> func) {
37 | return flatMap(new Function.F1>() {
38 | @Override
39 | public Maybe invoke(A a) {
40 | return Maybe.of(func.invoke(getOrElse(null)));
41 | }
42 | });
43 | }
44 |
45 | abstract public Maybe flatMap(Function.F1 super A, ? extends Maybe> func);
46 |
47 | public boolean isPresent() {
48 | return this instanceof Just;
49 | }
50 |
51 | abstract public Maybe filter(final Function.F1 super A, Boolean> func);
52 |
53 | public static Maybe of(@Nullable A value) {
54 | if (value != null) {
55 | return new Just<>(value);
56 | } else {
57 | return new None<>();
58 | }
59 | }
60 |
61 | public static Maybe none() {
62 | return new None<>();
63 | }
64 | }
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/maybe/None.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad.maybe;
2 |
3 | import net.petitviolet.monad.func.Function;
4 |
5 | class None extends Maybe {
6 |
7 | None() {
8 | }
9 |
10 | @Override
11 | public String toString() {
12 | return "None{}";
13 | }
14 |
15 | @Override
16 | public A get() {
17 | return null;
18 | }
19 |
20 | @Override
21 | public A getOrElse(A defaultValue) {
22 | return defaultValue;
23 | }
24 |
25 | @Override
26 | public void foreach(Function.F super A> func) {
27 | }
28 |
29 | @Override
30 | public Maybe flatMap(Function.F1 super A, ? extends Maybe> func) {
31 | return new None<>();
32 | }
33 |
34 | @Override
35 | public Maybe filter(Function.F1 super A, Boolean> func) {
36 | return this;
37 | }
38 | }
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/state/State.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad.state;
2 |
3 | import net.petitviolet.monad.Tuple;
4 | import net.petitviolet.monad.func.Function;
5 |
6 | /**
7 | * State Monad
8 | * @param
9 | * @param
10 | */
11 | public class State {
12 | private static final String TAG = State.class.getSimpleName();
13 | // get current state, then return new value and state
14 | final Function.F1> runState;
15 |
16 | /**
17 | * use unit or init Factory
18 | * @param runState
19 | */
20 | private State(Function.F1> runState) {
21 | this.runState = runState;
22 | }
23 |
24 | /**
25 | * unit factory given by first value
26 | * @param a
27 | * @param
28 | * @param
29 | * @return
30 | */
31 | public static State unit(final A a) {
32 | return State.init(new Function.F1>() {
33 | @Override
34 | public Tuple invoke(S s) {
35 | return Tuple.of(a, s);
36 | }
37 | });
38 | }
39 |
40 | /**
41 | * init factory with runState function
42 | * @param runState
43 | * @param
44 | * @param
45 | * @return
46 | */
47 | public static State init(Function.F1> runState) {
48 | return new State<>(runState);
49 | }
50 |
51 | /**
52 | * put new state
53 | * @param newState
54 | * @return
55 | */
56 | public State put(final S newState) {
57 | return State.init(new Function.F1>() {
58 | @Override
59 | public Tuple invoke(S s) {
60 | return Tuple.of(null, newState);
61 | }
62 | });
63 | }
64 |
65 | public Tuple apply(S state) {
66 | return runState.invoke(state);
67 | }
68 |
69 | /**
70 | * get current value
71 | * @return
72 | */
73 | public State get() {
74 | return State.init(new Function.F1>() {
75 | @Override
76 | public Tuple invoke(S s) {
77 | return Tuple.of(s, s);
78 | }
79 | });
80 | }
81 |
82 | /**
83 | * monadic
84 | * @param f
85 | * @param
86 | * @return
87 | */
88 | public State flatMap(final Function.F1 super A, State> f) {
89 | Function.F1> fb = new Function.F1>() {
90 | @Override
91 | public Tuple invoke(S s) {
92 | Tuple as = runState.invoke(s);
93 | State sb = f.invoke(as._1);
94 | Tuple bs = (Tuple) sb.runState.invoke(as._2);
95 | return bs;
96 | }
97 | };
98 | return State.init(fb);
99 | }
100 |
101 | /**
102 | * map function to inner value
103 | * @param f
104 | * @param
105 | * @return
106 | */
107 | public State map(final Function.F1 super A, ? extends B> f) {
108 | return flatMap(new Function.F1>() {
109 | @Override
110 | public State invoke(A a) {
111 | return State.unit(f.invoke(a));
112 | }
113 | });
114 | }
115 |
116 | }
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/type/IntM.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad.type;
2 |
3 | public class IntM implements Monoid {
4 | private static final String TAG = IntM.class.getSimpleName();
5 | private final Integer mValue;
6 |
7 | private IntM(Integer mValue) {
8 | this.mValue = mValue;
9 | }
10 |
11 | public static IntM of(int i) {
12 | return new IntM(i);
13 | }
14 |
15 | @Override
16 | public Monoid empty() {
17 | return IntM.of(0);
18 | }
19 |
20 | @Override
21 | public Monoid add(Integer integer) {
22 | return IntM.of(mValue + integer);
23 | }
24 |
25 | @Override
26 | public Integer get() {
27 | return mValue;
28 | }
29 | }
--------------------------------------------------------------------------------
/monad/src/main/java/net/petitviolet/monad/type/Monoid.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad.type;
2 |
3 | public interface Monoid {
4 | Monoid empty();
5 |
6 | Monoid add(A a);
7 |
8 | A get();
9 |
10 | public static class TypeMismatchException extends Exception {
11 | public TypeMismatchException(String s) {
12 | super(s);
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/monad/src/test/java/net/petitviolet/monad/IdentityTest.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad;
2 |
3 | import net.petitviolet.monad.Identity;
4 | import net.petitviolet.monad.func.Function;
5 |
6 | import org.junit.Test;
7 |
8 | import java.lang.Integer;
9 | import java.lang.Override;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | public class IdentityTest {
14 |
15 | @Test
16 | public void testId() {
17 | Identity id = Identity.id(1);
18 | assert id.value == 1;
19 | }
20 |
21 | @Test
22 | public void testEquals() {
23 | Identity id1 = Identity.id(1);
24 | Identity id2 = Identity.id(1);
25 | assert id1.equals(id2);
26 | }
27 |
28 | @Test
29 | public void testFlatMap() {
30 | Identity id = Identity.id("hoge");
31 | Identity result = id.flatMap(new Function.F1>() {
32 | @Override
33 | public Identity invoke(String s) {
34 | return Identity.id(s.length());
35 | }
36 | });
37 | assert result.value.equals(4);
38 | }
39 |
40 | @Test
41 | public void testMap() {
42 | Identity id = Identity.id(1);
43 | Identity result = id.map(new Function.F1() {
44 | @Override
45 | public Integer invoke(Integer integer) {
46 | return integer * 2;
47 | }
48 | });
49 | assert result.value == 2;
50 | }
51 | }
--------------------------------------------------------------------------------
/monad/src/test/java/net/petitviolet/monad/list/ListMTest.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad;
2 |
3 | import net.petitviolet.monad.func.Function;
4 | import net.petitviolet.monad.list.ListM;
5 | import net.petitviolet.monad.maybe.Maybe;
6 |
7 | import org.junit.Test;
8 |
9 | import java.util.ArrayList;
10 | import java.util.Arrays;
11 | import java.util.List;
12 |
13 | /**
14 | * Test cases for ListM(ArrayListM)
15 | */
16 | public class ListMTest {
17 | private ListM mListM = ListM.of("a", "bb", "ccc");
18 |
19 | @Test
20 | public void testMaybeGetJust() {
21 | assert mListM.maybeGet(0).equals(Maybe.of("a"));
22 | }
23 |
24 | @Test
25 | public void testMaybeGetNone() {
26 | assert mListM.maybeGet(100).equals(Maybe.of(null));
27 | }
28 |
29 | @Test
30 | public void testGetOrElseGet() {
31 | assert mListM.getOrElse(0, "foo").equals("a");
32 | }
33 |
34 | @Test
35 | public void testGetOrElseElse() {
36 | assert mListM.getOrElse(100, "foo").equals("foo");
37 | }
38 |
39 | @Test
40 | public void testMap() {
41 | ListM result = mListM.map(new Function.F1() {
42 | @Override
43 | public Integer invoke(String s) {
44 | return s.length();
45 | }
46 | });
47 | assert result.equals(ListM.of(1, 2, 3));
48 | }
49 |
50 | @Test
51 | public void testFlatMap() {
52 | ListM result = mListM.flatMap(new Function.F1>() {
53 | @Override
54 | public ListM invoke(String s) {
55 | return ListM.of(s.length());
56 | }
57 | });
58 | assert result.equals(ListM.of(1, 2, 3));
59 | }
60 |
61 | @Test
62 | public void testForeach() {
63 | final List box = new ArrayList<>();
64 | mListM.foreach(new Function.F() {
65 | @Override
66 | public void invoke(String s) {
67 | box.add(s);
68 | }
69 | });
70 | assert box.size() == mListM.size();
71 | }
72 |
73 | @Test
74 | public void testFilter() {
75 | ListM result = mListM.filter(new Function.F1() {
76 | @Override
77 | public Boolean invoke(String s) {
78 | return s.length() % 2 == 0;
79 | }
80 | });
81 | assert result.equals(ListM.of("bb"));
82 | }
83 |
84 | @Test
85 | public void testFilterNot() {
86 | ListM result = mListM.filterNot(new Function.F1() {
87 | @Override
88 | public Boolean invoke(String s) {
89 | return s.length() % 2 == 0;
90 | }
91 | });
92 | assert result.equals(ListM.of("a", "ccc"));
93 | }
94 |
95 | @Test
96 | public void testFoldLeft() {
97 | String result = mListM.foldLeft("x", new Function.F2() {
98 | @Override
99 | public String invoke(String acc, String s2) {
100 | return acc + s2;
101 | }
102 | });
103 | assert result.equals("xabbccc");
104 | }
105 |
106 | @Test
107 | public void testFoldRight() {
108 | String result = mListM.foldRight(new Function.F2() {
109 | @Override
110 | public String invoke(String s, String acc) {
111 | return s + acc;
112 | }
113 | }, "x");
114 | assert result.equals("cccbbax");
115 | }
116 |
117 | @Test
118 | public void testEqualsTrue() {
119 | assert mListM.equals(ListM.of("a", "bb", "ccc")) == true;
120 | }
121 |
122 | @Test
123 | public void testEqualsFalseType() {
124 | assert mListM.equals(Arrays.asList("a", "bb", "ccc")) == false;
125 | }
126 |
127 | @Test
128 | public void testEqualsFalseType2() {
129 | assert mListM.equals(1) == false;
130 | }
131 |
132 | @Test
133 | public void testEqualsFalseSize() {
134 | assert mListM.equals(ListM.of("a", "bb", "ccc", "dddd")) == false;
135 | }
136 |
137 | @Test
138 | public void testEqualsFalseContents() {
139 | assert mListM.equals(ListM.of("a", "bb", "cc")) == false;
140 | }
141 |
142 | @Test
143 | public void testFoldMap() {
144 | Integer result = mListM.foldMap(0, new Function.F1() {
145 | @Override
146 | public Integer invoke(String s) {
147 | return s.length();
148 | }
149 | }, new Function.F2() {
150 | @Override
151 | public Integer invoke(Integer acc, Integer i) {
152 | return acc + i;
153 | }
154 | });
155 | assert result == 6;
156 | }
157 |
158 | @Test
159 | public void testBindMaybe() {
160 | ListM result = ListM.of(1, 2, 3, 4, 5)
161 | .map(new Function.F1() {
162 | @Override
163 | public Integer invoke(Integer integer) {
164 | return integer * 2;
165 | }
166 | }).bindMaybe(new Function.F1>() {
167 | @Override
168 | public Maybe invoke(Integer integer) {
169 | return Maybe.of(integer);
170 | }
171 | });
172 | assert result.equals(ListM.of(2, 4, 6, 8, 10)) == true;
173 | }
174 | }
--------------------------------------------------------------------------------
/monad/src/test/java/net/petitviolet/monad/maybe/MaybeTest.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad;
2 |
3 | import net.petitviolet.monad.func.Function;
4 | import net.petitviolet.monad.maybe.Maybe;
5 |
6 | import org.junit.Test;
7 |
8 | import java.util.ArrayList;
9 | import java.util.HashMap;
10 | import java.util.List;
11 | import java.util.Map;
12 |
13 | /**
14 | * Test cases for Maybe(Just/None)
15 | */
16 | public class MaybeTest {
17 | private Maybe just = Maybe.of("hoge");
18 | private Maybe none = Maybe.none();
19 |
20 | @Test
21 | public void getJust() {
22 | assert just.get() == "hoge";
23 | }
24 |
25 | @Test
26 | public void getNone() {
27 | assert none.get() == null;
28 | }
29 |
30 | @Test
31 | public void getOrElseJust() {
32 | assert just.getOrElse("foo") == "hoge";
33 | }
34 |
35 | @Test
36 | public void getOrElseNone() {
37 | assert none.getOrElse("foo") == "foo";
38 | }
39 |
40 | @Test
41 | public void equalToJust() {
42 | assert just.equals(Maybe.of("hoge")) == true;
43 | assert just.equals(Maybe.of("foo")) == false;
44 | assert just.equals(Maybe.of(1)) == false;
45 | assert just.equals(Maybe.of(null)) == false;
46 | }
47 |
48 | @Test
49 | public void equalToNone() {
50 | assert none.equals(Maybe.of("hoge")) == false;
51 | assert none.equals(Maybe.of("foo")) == false;
52 | assert none.equals(Maybe.of(1)) == false;
53 | assert none.equals(Maybe.of(null)) == true;
54 | }
55 |
56 | @Test
57 | public void foreachJust() {
58 | final List list = new ArrayList<>();
59 | just.foreach(new Function.F() {
60 | @Override
61 | public void invoke(String s) {
62 | list.add(s);
63 | }
64 | });
65 | assert list.size() == 1;
66 | }
67 |
68 | @Test
69 | public void foreachNone() {
70 | final List list = new ArrayList<>();
71 | none.foreach(new Function.F() {
72 | @Override
73 | public void invoke(String s) {
74 | list.add(s);
75 | }
76 | });
77 | assert list.size() == 0;
78 | }
79 |
80 | @Test
81 | public void mapJust() {
82 | Maybe result = just.map(new Function.F1() {
83 | @Override
84 | public String invoke(String s) {
85 | return s + "foo";
86 | }
87 | });
88 | assert result.equals(Maybe.of("hogefoo")) == true;
89 | }
90 |
91 | @Test
92 | public void mapNone() {
93 | Maybe result = none.map(new Function.F1() {
94 | @Override
95 | public String invoke(String s) {
96 | return s + "foo";
97 | }
98 | });
99 | assert result.equals(Maybe.of(null)) == true;
100 | }
101 |
102 | @Test
103 | public void flatMapJust() {
104 | Maybe resultJust = just.flatMap(new Function.F1>() {
105 | @Override
106 | public Maybe invoke(String s) {
107 | return Maybe.of(s + "bar");
108 | }
109 | });
110 | assert resultJust.equals(Maybe.of("hogebar")) == true;
111 | Maybe resultNone = just.flatMap(new Function.F1>() {
112 | @Override
113 | public Maybe invoke(String s) {
114 | return Maybe.of(null);
115 | }
116 | });
117 | assert resultNone.equals(Maybe.of(null)) == true;
118 | }
119 |
120 | @Test
121 | public void flatMapNone() {
122 | Maybe resultJust = none.flatMap(new Function.F1>() {
123 | @Override
124 | public Maybe invoke(String s) {
125 | return Maybe.of(s + "bar");
126 | }
127 | });
128 | assert resultJust.equals(Maybe.of(null)) == true;
129 | Maybe resultNone = just.flatMap(new Function.F1>() {
130 | @Override
131 | public Maybe invoke(String s) {
132 | return Maybe.of(null);
133 | }
134 | });
135 | assert resultNone.equals(Maybe.of(null)) == true;
136 | }
137 |
138 | @Test
139 | public void isPresentJust() {
140 | assert just.isPresent() == true;
141 | }
142 |
143 | @Test
144 | public void isPresentNone() {
145 | assert none.isPresent() == false;
146 | }
147 |
148 | @Test
149 | public void filterJust() {
150 | Maybe result = just.filter(new Function.F1() {
151 | @Override
152 | public Boolean invoke(String s) {
153 | return s.length() > 3;
154 | }
155 | });
156 | assert result.equals(just) == true;
157 |
158 | Maybe result2 = just.filter(new Function.F1() {
159 | @Override
160 | public Boolean invoke(String s) {
161 | return s.length() > 30;
162 | }
163 | });
164 | assert result2.equals(just) == false;
165 | }
166 |
167 | @Test
168 | public void filterNone() {
169 | Maybe result = none.filter(new Function.F1() {
170 | @Override
171 | public Boolean invoke(String s) {
172 | return s.length() > 3;
173 | }
174 | });
175 | assert result.equals(none) == true;
176 |
177 | Maybe result2 = none.filter(new Function.F1() {
178 | @Override
179 | public Boolean invoke(String s) {
180 | return s.length() > 30;
181 | }
182 | });
183 | assert result2.equals(none) == true;
184 | }
185 |
186 | private static class AwesomeObj {
187 | public Map map;
188 |
189 | public AwesomeObj() {
190 | this.map = new HashMap<>();
191 | }
192 |
193 | public Maybe getValue(int key) {
194 | return Maybe.of(map.get(key));
195 | }
196 | }
197 |
198 | @Test
199 | public void practicalCase() {
200 | final AwesomeObj obj = new AwesomeObj();
201 | Map map = new HashMap<>();
202 |
203 | assert obj.getValue(0).equals(Maybe.none()) == true;
204 |
205 | map.put(1, "good");
206 | obj.map = map;
207 |
208 | assert obj.getValue(1).equals(Maybe.of("good")) == true;
209 | assert obj.getValue(100).equals(Maybe.none()) == true;
210 |
211 | Maybe result = Maybe.of(1).flatMap(new Function.F1>() {
212 | @Override
213 | public Maybe invoke(Integer integer) {
214 | return obj.getValue(integer);
215 | }
216 | }).map(new Function.F1() {
217 | @Override
218 | public String invoke(String str) {
219 | return str + "!";
220 | }
221 | });
222 | assert result.equals(Maybe.of("good!")) == true;
223 | }
224 | }
--------------------------------------------------------------------------------
/monad/src/test/java/net/petitviolet/monad/state/StateTest.java:
--------------------------------------------------------------------------------
1 | package net.petitviolet.monad.state;
2 |
3 | import net.petitviolet.monad.Tuple;
4 | import net.petitviolet.monad.func.Function;
5 |
6 | import org.junit.Test;
7 |
8 | import java.util.ArrayList;
9 | import java.util.List;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Test cases for State monad
15 | */
16 | public class StateTest {
17 | @Test
18 | public void testInit() {
19 | System.out.println("testUnit");
20 | Tuple result = State.init(new Function.F1>() {
21 | @Override
22 | public Tuple invoke(Integer integer) {
23 | return Tuple.of(1, integer);
24 | }
25 | }).apply(100);
26 | System.out.println("testInit");
27 | System.out.println(result);
28 | assert result._1 == 1;
29 | assert result._2 == 100;
30 | }
31 |
32 | @Test
33 | public void testUnit() {
34 | Tuple result = State.unit(1).apply(100);
35 | System.out.println(result);
36 | assert result._1 == 1;
37 | assert result._2 == 100;
38 | }
39 |
40 | @Test
41 | public void testMap() {
42 | System.out.println("testMap");
43 | Tuple result = State.unit(1)
44 | .map(new Function.F1() {
45 | @Override
46 | public Integer invoke(Integer integer) {
47 | return integer * 2;
48 | }
49 | }).apply(100);
50 | System.out.println(result);
51 | assert result._1 == 2;
52 | assert result._2 == 100;
53 | }
54 |
55 | @Test
56 | public void testFlatMap() {
57 | System.out.println("testFlatMap");
58 | Tuple result = State.unit(1)
59 | .flatMap(new Function.F1>() {
60 | @Override
61 | public State invoke(Integer integer) {
62 | return State.unit(integer * 2);
63 | }
64 | }).apply(100);
65 | System.out.println(result);
66 | assert result._1 == 2;
67 | assert result._2 == 100;
68 | }
69 |
70 | @Test
71 | public void testCombined() {
72 | System.out.println("testCombined");
73 |
74 | Tuple> result = State.init(new Function.F1, Tuple>>() {
75 | @Override
76 | public Tuple> invoke(List strings) {
77 | strings.add("nice");
78 | return Tuple.of(1, strings);
79 | }
80 | }).map(new Function.F1() {
81 | @Override
82 | public Integer invoke(Integer i) {
83 | System.out.println("map: " + i);
84 | return i + 10;
85 | }
86 | }).map(new Function.F1() {
87 | @Override
88 | public Integer invoke(Integer i) {
89 | System.out.println("map: " + i);
90 | return i * 2;
91 | }
92 | }).flatMap(new Function.F1, Integer>>() {
93 | @Override
94 | public State, Integer> invoke(final Integer integer) {
95 | return State.init(new F1, Tuple>>() {
96 | @Override
97 | public Tuple> invoke(List strings) {
98 | if (integer % 2 == 0) {
99 | strings.add("awesome");
100 | return Tuple.of(integer, strings);
101 | } else {
102 | strings.add("Oops");
103 | return Tuple.of(-100, strings);
104 | }
105 | }
106 | });
107 | }
108 | }).apply(new ArrayList());
109 |
110 | System.out.println(result);
111 |
112 | assert result._1 == 22;
113 | assert result._2.size() == 2;
114 | assert result._2.get(0).equals("nice");
115 | assert result._2.get(1).equals("awesome");
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':monad'
2 |
--------------------------------------------------------------------------------