Skip to content

Commit 7d9de4f

Browse files
committed
- all lenses that interface with mutable structures use defensive copies
- unlawful lenses are explicitly documented as such - some lenses that could be made lawful via type signature changes have been made so
1 parent b598a23 commit 7d9de4f

16 files changed

Lines changed: 392 additions & 225 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](http://keepachangelog.com/).
55

66
## [Unreleased]
7+
### Changed
8+
- ***Breaking Change***: `CollectionLens#asSet` is now lawful and preserves new incoming values in the update set
9+
- ***Breaking Change***: `IterableLens#head` is now a `Lens.Simple<Iterable<A>, Maybe<A>>` and is lawful
10+
- ***Breaking Change***: `ListLens#elementAt` is now a `Lens.Simple<List<X>, Maybe<X>>` supporting defensive copies
11+
- ***Breaking Change***: `MapLens#valueAt` is now a `Lens.Simple<Map<K,V>, Maybe<V>>` supporting defensive copies
12+
- `MapLens#keys` now uses defensive copies and does not alter the focused on map
13+
- `MapLens#values` now uses defensive copies and does not alter the focused on map
14+
- `MapLens#inverted` now uses defensive copies and does not alter the focused on map
15+
- `HListLens#head` is now covariant in the tail of both `S` and `T`
16+
717
### Added
818
- `Fn3#fn3` and `Fn4#fn4` static factory methods
919
- `Fn5` through `Fn8`
@@ -15,6 +25,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/).
1525
- `Times`, for successively accumulating a result by iterating a function over a value some number of times
1626
- `Slide`, for "sliding" a window of some number of elements across an `Iterable`
1727
- `Either#filter` overload supporting a function from `R` to `L` in the failing predicate case
28+
- `CollectionLens#asSet(Function)`, a proper analog of `CollectionLens#asSet()` that uses defensive copies
29+
- `CollectionLens#asStream(Function)`, a proper analog of `CollectionLens#asStream()` that uses defensive copies
30+
- Explicitly calling attention to all unlawful lenses in their documentation
1831

1932
### Removed
2033
- `Either#toOptional`, deprecated in previous release
@@ -24,6 +37,10 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/).
2437
- `TraversableIterable`, deprecated in previous release
2538
- `Traversables`, deprecated in previous release
2639

40+
### Deprecated
41+
- `CollectionLens#asSet()` in favor of `CollectionLens#asSet(Function)`
42+
- `CollectionLens#asStream()` in favor of `CollectionLens#asStream(Function)`
43+
2744
## [2.0.0] - 2017-11-13
2845
### Changed
2946
- ***Breaking Change***: `java.util.Optional` replaced with `Maybe` across the board

‎src/main/java/com/jnape/palatable/lambda/lens/lenses/CollectionLens.java‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,26 +38,72 @@ public static <X, CX extends Collection<X>> Lens.Simple<CX, CX> asCopy(Function<
3838
* @param <X> the collection element type
3939
* @param <CX> the type of the collection
4040
* @return a lens that focuses on a Collection as a Set
41+
* @deprecated in favor of lawful {@link CollectionLens#asSet(Function)}
4142
*/
43+
@Deprecated
4244
public static <X, CX extends Collection<X>> Lens.Simple<CX, Set<X>> asSet() {
4345
return simpleLens(HashSet::new, (xsL, xsS) -> {
4446
xsL.retainAll(xsS);
4547
return xsL;
4648
});
4749
}
4850

51+
/**
52+
* Convenience static factory method for creating a lens that focuses on an arbitrary {@link Collection} as a
53+
* {@link Set}.
54+
*
55+
* @param copyFn the copying function
56+
* @param <X> the collection element type
57+
* @param <CX> the type of the collection
58+
* @return a lens that focuses on a Collection as a Set
59+
*/
60+
public static <X, CX extends Collection<X>> Lens.Simple<CX, Set<X>> asSet(
61+
Function<? super CX, ? extends CX> copyFn) {
62+
return simpleLens(HashSet::new, (xsL, xsS) -> {
63+
Set<X> missing = new HashSet<>(xsS);
64+
missing.removeAll(xsL);
65+
CX updated = copyFn.apply(xsL);
66+
updated.addAll(missing);
67+
updated.retainAll(xsS);
68+
return updated;
69+
});
70+
}
71+
4972
/**
5073
* Convenience static factory method for creating a lens that focuses on a Collection as a Stream.
5174
*
5275
* @param <X> the collection element type
5376
* @param <CX> the type of the collection
5477
* @return a lens that focuses on a Collection as a stream.
78+
* @deprecated in favor of lawful {@link CollectionLens#asStream(Function)}
5579
*/
80+
@Deprecated
5681
public static <X, CX extends Collection<X>> Lens.Simple<CX, Stream<X>> asStream() {
5782
return simpleLens(Collection::stream, (xsL, xsS) -> {
5883
xsL.clear();
5984
xsS.forEach(xsL::add);
6085
return xsL;
6186
});
6287
}
88+
89+
/**
90+
* Convenience static factory method for creating a lens that focuses on a Collection as a Stream.
91+
* <p>
92+
* Note that this lens is effectively lawful, though difficult to prove given the intrinsically
93+
* stateful and inequitable nature of {@link Stream}.
94+
*
95+
* @param copyFn the copying function
96+
* @param <X> the collection element type
97+
* @param <CX> the type of the collection
98+
* @return a lens that focuses on a Collection as a stream.
99+
*/
100+
public static <X, CX extends Collection<X>> Lens.Simple<CX, Stream<X>> asStream(
101+
Function<? super CX, ? extends CX> copyFn) {
102+
return simpleLens(Collection::stream, (xsL, xsS) -> {
103+
CX updated = copyFn.apply(xsL);
104+
updated.clear();
105+
xsS.forEach(updated::add);
106+
return updated;
107+
});
108+
}
63109
}

‎src/main/java/com/jnape/palatable/lambda/lens/lenses/EitherLens.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ private EitherLens() {
1919
* Convenience static factory method for creating a lens over right values, wrapping them in a {@link Maybe}. When
2020
* setting, a {@link Maybe#nothing()} value means to leave the {@link Either} unaltered, where as a
2121
* {@link Maybe#just} value replaces the either with a right over the {@link Maybe}.
22+
* <p>
23+
* Note that this lens is NOT lawful, since "you get back what you put in" fails for {@link Maybe#nothing()}.
2224
*
2325
* @param <L> the left parameter type
2426
* @param <R> the right parameter type
@@ -32,6 +34,8 @@ public static <L, R> Lens.Simple<Either<L, R>, Maybe<R>> right() {
3234
* Convenience static factory method for creating a lens over left values, wrapping them in a {@link Maybe}. When
3335
* setting, a {@link Maybe#nothing()} value means to leave the {@link Either} unaltered, where as a
3436
* {@link Maybe#just} value replaces the either with a left over the {@link Maybe}.
37+
* <p>
38+
* Note that this lens is NOT lawful, since "you get back what you put in" fails for {@link Maybe#nothing()}.
3539
*
3640
* @param <L> the left parameter type
3741
* @param <R> the right parameter type

‎src/main/java/com/jnape/palatable/lambda/lens/lenses/HListLens.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public final class HListLens {
3232
* @param <Tail> the tail HList type
3333
* @return a lens that focuses on the head of an HList
3434
*/
35-
public static <Head, Tail extends HList> Lens.Simple<HCons<Head, Tail>, Head> head() {
35+
public static <Head, Tail extends HList> Lens.Simple<HCons<Head, ? extends Tail>, Head> head() {
3636
return simpleLens(HCons::head, (hCons, newHead) -> cons(newHead, hCons.tail()));
3737
}
3838

‎src/main/java/com/jnape/palatable/lambda/lens/lenses/IterableLens.java‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,11 @@
33
import com.jnape.palatable.lambda.adt.Maybe;
44
import com.jnape.palatable.lambda.functions.builtin.fn1.Head;
55
import com.jnape.palatable.lambda.functions.builtin.fn1.Tail;
6-
import com.jnape.palatable.lambda.functions.builtin.fn2.Cons;
76
import com.jnape.palatable.lambda.lens.Lens;
87

98
import static com.jnape.palatable.lambda.functions.Fn2.fn2;
109
import static com.jnape.palatable.lambda.functions.builtin.fn1.Id.id;
1110
import static com.jnape.palatable.lambda.functions.builtin.fn2.Cons.cons;
12-
import static com.jnape.palatable.lambda.lens.Lens.lens;
1311
import static com.jnape.palatable.lambda.lens.Lens.simpleLens;
1412

1513
/**
@@ -22,12 +20,18 @@ private IterableLens() {
2220

2321
/**
2422
* A lens focusing on the head of a given {@link Iterable}.
23+
* <p>
24+
* Note that this lens is effectively lawful, though difficult to prove since there is no
25+
* useful equality implementation for {@link Iterable}.
2526
*
2627
* @param <A> the Iterable element type
2728
* @return a lens focusing on the head element of an {@link Iterable}
2829
*/
29-
public static <A> Lens<Iterable<A>, Iterable<A>, Maybe<A>, A> head() {
30-
return lens(Head::head, Cons.<A>cons().flip().compose(Tail.tail()).toBiFunction());
30+
public static <A> Lens.Simple<Iterable<A>, Maybe<A>> head() {
31+
return simpleLens(Head::head, (s, maybeB) -> {
32+
Iterable<A> tail = Tail.tail(s);
33+
return maybeB.fmap(b -> cons(b, tail)).orElse(tail);
34+
});
3135
}
3236

3337
/**

‎src/main/java/com/jnape/palatable/lambda/lens/lenses/ListLens.java‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,12 @@
77
import java.util.List;
88

99
import static com.jnape.palatable.lambda.adt.Maybe.maybe;
10-
import static com.jnape.palatable.lambda.lens.Lens.lens;
10+
import static com.jnape.palatable.lambda.functions.builtin.fn1.Repeat.repeat;
11+
import static com.jnape.palatable.lambda.functions.builtin.fn2.Take.take;
1112
import static com.jnape.palatable.lambda.lens.Lens.simpleLens;
1213
import static com.jnape.palatable.lambda.lens.lenses.MaybeLens.unLiftA;
14+
import static com.jnape.palatable.lambda.lens.lenses.MaybeLens.unLiftB;
15+
import static java.lang.Math.abs;
1316

1417
/**
1518
* Lenses that operate on {@link List}s.
@@ -38,18 +41,32 @@ public static <X> Lens.Simple<List<X>, List<X>> asCopy() {
3841
* @param <X> the list element type
3942
* @return Maybe the element at the index
4043
*/
41-
public static <X> Lens<List<X>, List<X>, Maybe<X>, X> elementAt(int index) {
42-
return lens(xs -> maybe(xs.size() > index ? xs.get(index) : null),
43-
(xs, x) -> {
44-
if (xs.size() > index)
45-
xs.set(index, x);
46-
return xs;
47-
});
44+
public static <X> Lens.Simple<List<X>, Maybe<X>> elementAt(int index) {
45+
return simpleLens(xs -> maybe(xs.size() > index ? xs.get(index) : null),
46+
(xs, maybeX) -> {
47+
List<X> updated = new ArrayList<>(xs);
48+
return maybeX.fmap(x -> {
49+
int minimumSize = index + 1;
50+
if (minimumSize > xs.size()) {
51+
take(abs(updated.size() - minimumSize), repeat((X) null)).forEach(updated::add);
52+
}
53+
updated.set(index, x);
54+
return updated;
55+
}).orElseGet(() -> {
56+
if (updated.size() > index) {
57+
updated.set(index, null);
58+
}
59+
return updated;
60+
});
61+
});
4862
}
4963

5064
/**
5165
* Convenience static factory method for creating a lens that focuses on an element in a list at a particular index,
5266
* returning <code>defaultValue</code> if there is no value at that index.
67+
* <p>
68+
* Note that this lens is NOT lawful, since "putting back what you got changes nothing" fails for any value
69+
* <code>B</code> where <code>S</code> is the empty list
5370
*
5471
* @param index the index to focus on
5572
* @param defaultValue the value to use if there is no element at index
@@ -58,6 +75,6 @@ public static <X> Lens<List<X>, List<X>, Maybe<X>, X> elementAt(int index) {
5875
*/
5976
@SuppressWarnings("unchecked")
6077
public static <X> Lens.Simple<List<X>, X> elementAt(int index, X defaultValue) {
61-
return unLiftA(elementAt(index), defaultValue)::apply;
78+
return unLiftB(unLiftA(elementAt(index), defaultValue))::apply;
6279
}
6380
}

‎src/main/java/com/jnape/palatable/lambda/lens/lenses/MapLens.java‎

Lines changed: 45 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import com.jnape.palatable.lambda.functions.builtin.fn2.Filter;
66
import com.jnape.palatable.lambda.lens.Lens;
77

8+
import java.util.ArrayList;
89
import java.util.Collection;
910
import java.util.HashMap;
1011
import java.util.HashSet;
@@ -17,11 +18,10 @@
1718
import static com.jnape.palatable.lambda.functions.builtin.fn2.Map.map;
1819
import static com.jnape.palatable.lambda.functions.builtin.fn2.ToCollection.toCollection;
1920
import static com.jnape.palatable.lambda.functions.builtin.fn2.ToMap.toMap;
20-
import static com.jnape.palatable.lambda.lens.Lens.lens;
2121
import static com.jnape.palatable.lambda.lens.Lens.simpleLens;
2222
import static com.jnape.palatable.lambda.lens.functions.View.view;
2323
import static com.jnape.palatable.lambda.lens.lenses.MaybeLens.unLiftA;
24-
import static java.util.stream.Collectors.toSet;
24+
import static com.jnape.palatable.lambda.lens.lenses.MaybeLens.unLiftB;
2525

2626
/**
2727
* Lenses that operate on {@link Map}s.
@@ -45,20 +45,29 @@ public static <K, V> Lens.Simple<Map<K, V>, Map<K, V>> asCopy() {
4545
/**
4646
* A lens that focuses on a value at a key in a map, as a {@link Maybe}.
4747
*
48-
* @param k the key to focus on
4948
* @param <K> the key type
5049
* @param <V> the value type
50+
* @param k the key to focus on
5151
* @return a lens that focuses on the value at key, as a {@link Maybe}
5252
*/
53-
public static <K, V> Lens<Map<K, V>, Map<K, V>, Maybe<V>, V> valueAt(K k) {
54-
return lens(m -> maybe(m.get(k)), (m, v) -> {
55-
m.put(k, v);
56-
return m;
53+
public static <K, V> Lens.Simple<Map<K, V>, Maybe<V>> valueAt(K k) {
54+
return simpleLens(m -> maybe(m.get(k)), (m, maybeV) -> {
55+
Map<K, V> updated = new HashMap<>(m);
56+
return maybeV.fmap(v -> {
57+
updated.put(k, v);
58+
return updated;
59+
}).orElseGet(() -> {
60+
updated.remove(k);
61+
return updated;
62+
});
5763
});
5864
}
5965

6066
/**
6167
* A lens that focuses on a value at a key in a map, falling back to <code>defaultV</code> if the value is missing.
68+
* <p>
69+
* Note that this lens is NOT lawful, since "putting back what you got changes nothing" fails for any value
70+
* <code>B</code> where <code>S</code> is the empty map
6271
*
6372
* @param k the key to focus on
6473
* @param defaultValue the default value to use in case of a missing value at key
@@ -68,7 +77,7 @@ public static <K, V> Lens<Map<K, V>, Map<K, V>, Maybe<V>, V> valueAt(K k) {
6877
*/
6978
@SuppressWarnings("unchecked")
7079
public static <K, V> Lens.Simple<Map<K, V>, V> valueAt(K k, V defaultValue) {
71-
return unLiftA(valueAt(k), defaultValue)::apply;
80+
return unLiftB(unLiftA(valueAt(k), defaultValue))::apply;
7281
}
7382

7483
/**
@@ -79,32 +88,38 @@ public static <K, V> Lens.Simple<Map<K, V>, V> valueAt(K k, V defaultValue) {
7988
* @return a lens that focuses on the keys of a map
8089
*/
8190
public static <K, V> Lens.Simple<Map<K, V>, Set<K>> keys() {
82-
return simpleLens(Map::keySet, (m, ks) -> {
83-
Set<K> keys = m.keySet();
84-
keys.retainAll(ks);
85-
ks.removeAll(keys);
86-
ks.forEach(k -> m.put(k, null));
87-
return m;
91+
return simpleLens(m -> new HashSet<>(m.keySet()), (m, ks) -> {
92+
HashSet<K> ksCopy = new HashSet<>(ks);
93+
Map<K, V> updated = new HashMap<>(m);
94+
Set<K> keys = updated.keySet();
95+
keys.retainAll(ksCopy);
96+
ksCopy.removeAll(keys);
97+
ksCopy.forEach(k -> updated.put(k, null));
98+
return updated;
8899
});
89100
}
90101

91102
/**
92103
* A lens that focuses on the values of a map. In the case of updating the map, only the entries with a value listed
93104
* in the update collection of values are kept.
105+
* <p>
106+
* Note that this lens is NOT lawful, since "you get back what you put in" fails for all values <code>B</code> that
107+
* represent a non-surjective superset of the existing values in <code>S</code>.
94108
*
95109
* @param <K> the key type
96110
* @param <V> the value type
97111
* @return a lens that focuses on the values of a map
98112
*/
99113
public static <K, V> Lens.Simple<Map<K, V>, Collection<V>> values() {
100-
return simpleLens(Map::values, (m, vs) -> {
114+
return simpleLens(m -> new ArrayList<>(m.values()), (m, vs) -> {
115+
Map<K, V> updated = new HashMap<>(m);
101116
Set<V> valueSet = new HashSet<>(vs);
102-
Set<K> matchingKeys = m.entrySet().stream()
103-
.filter(kv -> valueSet.contains(kv.getValue()))
104-
.map(Map.Entry::getKey)
105-
.collect(toSet());
106-
m.keySet().retainAll(matchingKeys);
107-
return m;
117+
Set<K> matchingKeys = Filter.<Map.Entry<K, V>>filter(kv -> valueSet.contains(kv.getValue()))
118+
.andThen(map(Map.Entry::getKey))
119+
.andThen(toCollection(HashSet::new))
120+
.apply(updated.entrySet());
121+
updated.keySet().retainAll(matchingKeys);
122+
return updated;
108123
});
109124
}
110125

@@ -122,19 +137,24 @@ public static <K, V> Lens.Simple<Map<K, V>, Map<V, K>> inverted() {
122137
m.forEach((key, value) -> inverted.put(value, key));
123138
return inverted;
124139
}, (m, im) -> {
125-
m.clear();
126-
m.putAll(view(inverted(), im));
127-
return m;
140+
Map<K, V> updated = new HashMap<>(m);
141+
updated.clear();
142+
updated.putAll(view(inverted(), im));
143+
return updated;
128144
});
129145
}
130146

131147
/**
132148
* A lens that focuses on a map while mapping its values with the mapping function.
149+
* <p>
150+
* Note that this lens is NOT lawful, since "you get back what you put in" fails for all values <code>B</code> that
151+
* do not map from the current values in <code>S</code> (new mappings cannot be preserved as the inversion of
152+
* <code>fn</code> is not known).
133153
*
134154
* @param fn the mapping function
135155
* @param <K> the key type
136156
* @param <V> the unfocused map value type
137-
* @param <V2> the focused map value type
157+
* @param <V2> the focused map value types
138158
* @return a lens that focuses on a map while mapping its values
139159
*/
140160
public static <K, V, V2> Lens.Simple<Map<K, V>, Map<K, V2>> mappingValues(Function<? super V, ? extends V2> fn) {

0 commit comments

Comments
 (0)