summaryrefslogtreecommitdiff
path: root/base/src/main/java/bjc/utils/patterns/FunctionalPattern.java
blob: e4b4a3df97dc93877b574282e5333444b2ea3f93 (plain)
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
47
package bjc.utils.patterns;

import java.util.*;
import java.util.function.*;

import bjc.data.*;

class FunctionalPattern<ReturnType, PredType, InputType>
	implements ComplexPattern<ReturnType, PredType, InputType> {
	private final Function<InputType, IPair<Boolean, PredType>> matcher;
	private final BiFunction<InputType, PredType, ReturnType> accepter;

	FunctionalPattern(
			Function<InputType, IPair<Boolean, PredType>> matcher,
			BiFunction<InputType, PredType, ReturnType> accepter) {
		super();
		this.matcher = matcher;
		this.accepter = accepter;
	}

	@Override
	public IPair<Boolean, PredType> matches(InputType input) {
		return matcher.apply(input);
	}
	
	@Override
	public ReturnType apply(InputType input, PredType state) {
		return accepter.apply(input, state);
	}

	@Override
	public int hashCode() {
		return Objects.hash(accepter, matcher);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)                  return true;
		if (obj == null)                  return false;
		if (getClass() != obj.getClass()) return false;
		
		FunctionalPattern<?, ?, ?> other = (FunctionalPattern<?, ?, ?>) obj;
		
		return Objects.equals(accepter, other.accepter)
				&& Objects.equals(matcher, other.matcher);
	}
}