Skip to content

Commit 6c91e64

Browse files
committed
Lens#toIso for converting a lens to an iso
1 parent 6312a54 commit 6c91e64

3 files changed

Lines changed: 21 additions & 0 deletions

File tree

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ 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+
### Added
8+
- `Lens#toIso`, for converting a lens to an iso
9+
710
### Fixed
811
- Deforested iterables execute in intended nesting order, where essential
912

src/main/java/com/jnape/palatable/lambda/lens/Lens.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import java.util.function.BiFunction;
1111
import java.util.function.Function;
1212

13+
import static com.jnape.palatable.lambda.lens.Iso.iso;
1314
import static com.jnape.palatable.lambda.lens.Lens.Simple.adapt;
1415
import static com.jnape.palatable.lambda.lens.functions.Over.over;
1516
import static com.jnape.palatable.lambda.lens.functions.Set.set;
@@ -209,6 +210,16 @@ default <Z> Lens<S, T, A, Z> mapB(Function<? super Z, ? extends B> fn) {
209210
return lens(view(this), (s, z) -> set(this, fn.apply(z), s));
210211
}
211212

213+
/**
214+
* Produce an {@link Iso} from this {@link Lens} by providing a default <code>S</code> value.
215+
*
216+
* @param s the default <code>S</code>
217+
* @return an {@link Iso}
218+
*/
219+
default Iso<S, T, A, B> toIso(S s) {
220+
return iso(view(this), set(this).flip().apply(s));
221+
}
222+
212223
/**
213224
* Left-to-right composition of lenses. Requires compatibility between S and T.
214225
*

src/test/java/com/jnape/palatable/lambda/lens/LensTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,4 +103,11 @@ public void bothForSimpleLenses() {
103103
assertEquals(tuple(3, '3'), view(both(stringToInt, stringToChar), "3"));
104104
assertEquals("133", set(both(stringToInt, stringToChar), tuple(3, '3'), "1"));
105105
}
106+
107+
@Test
108+
public void toIso() {
109+
Iso<List<String>, Set<Integer>, String, Integer> iso = LENS.toIso(singletonList(""));
110+
assertEquals("1", view(iso, asList("1", "2", "3")));
111+
assertEquals(singleton(1), view(iso.mirror(), 1));
112+
}
106113
}

0 commit comments

Comments
 (0)