|
| 1 | +--- |
| 2 | +layout: docs-core |
| 3 | +title: Traverse |
| 4 | +permalink: /arrow/typeclasses/traverse/ |
| 5 | +--- |
| 6 | + |
| 7 | +## Traverse |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | + |
| 12 | +The `Traverse` typeclass is allowing to commute types from `F<G<A>>` to `G<F<A>>` over sequential execution of code. |
| 13 | +The main use of this is traversal over a structure with an effect. |
| 14 | +This doc focuses on the methods provided by the typeclass. |
| 15 | + |
| 16 | +### Main Combinators |
| 17 | + |
| 18 | +`Traverse` includes all combinators present in [`Functor`]({{ '/arrow/typeclasses/functor/' | relative_url }}) |
| 19 | +and [`Foldable`]({{ '/arrow/typeclasses/foldable/' | relative_url }}). |
| 20 | + |
| 21 | +#### Kind<F, A>#traverse |
| 22 | + |
| 23 | +Given a function which returns a `G` effect, thread this effect through the running of this function on all the values |
| 24 | +in `F`, returning an `F<B>` in a `G` context. |
| 25 | + |
| 26 | +```kotlin:ank |
| 27 | +import arrow.core.* |
| 28 | +import arrow.core.extensions.id.applicative.applicative |
| 29 | +import arrow.core.extensions.traverse |
| 30 | +
|
| 31 | +Some(1).traverse(Id.applicative()) { Id.just(it * 2) } |
| 32 | +``` |
| 33 | + |
| 34 | +#### Kind<F, Kind<G, A>>#sequence |
| 35 | + |
| 36 | +Thread all the `G` effects through the `F` structure to invert the structure from `F<G<A>>` to `G<F<A>>`. |
| 37 | + |
| 38 | +```kotlin:ank |
| 39 | +import arrow.core.* |
| 40 | +import arrow.core.extensions.id.applicative.applicative |
| 41 | +
|
| 42 | +Const<Int, Nothing>(1).sequence<Nothing, Int, ForId>(Id.applicative()) |
| 43 | +``` |
| 44 | + |
| 45 | +### Laws |
| 46 | + |
| 47 | +Arrow provides [`TraverseLaws`][travers_laws_source]{:target="_blank"} in the form of test cases for internal verification of lawful instances and third party apps creating their own `Traverse` instances. |
| 48 | + |
| 49 | +#### Creating your own `Traverse` instances |
| 50 | + |
| 51 | +Arrow already provides `Traverse` instances for most common datatypes both in Arrow and the Kotlin stdlib. |
| 52 | +Oftentimes, you may find the need to provide your own for unsupported datatypes. |
| 53 | + |
| 54 | +See [Deriving and creating custom typeclass]({{ '/patterns/glossary' | relative_url }}) |
| 55 | + |
| 56 | +### Data types |
| 57 | + |
| 58 | +```kotlin:ank:replace |
| 59 | +import arrow.reflect.* |
| 60 | +import arrow.typeclasses.Traverse |
| 61 | +
|
| 62 | +TypeClass(Traverse::class).dtMarkdownList() |
| 63 | +``` |
| 64 | + |
| 65 | +ank_macro_hierarchy(arrow.typeclasses.Traverse) |
| 66 | + |
| 67 | +[travers_laws_source]: https://github.com/arrow-kt/arrow-core/blob/master/arrow-core-test/src/main/kotlin/arrow/core/test/laws/TraverseLaws.kt |
0 commit comments