February 2018
Intermediate to advanced
350 pages
7h 35m
English
State is beneficial on corecursion; we can rewrite our old examples with State:
fun <T, S> unfold(s: S, f: (S) -> Pair<T, S>?): Sequence<T> { val result = f(s) return if (result != null) { sequenceOf(result.first) + unfold(result.second, f) } else { sequenceOf() }}
Our original unfold function use a function, f: (S) -> Pair<T,S>? which is very similar to State<S, T>:
fun <T, S> unfold(s: S, state: State<S, Option<T>>): Sequence<T> { val (actualState: S, value: Option<T>) = state.run(s) return value.fold( { sequenceOf() }, { t -> sequenceOf(t) + unfold(actualState, state) })}
Instead of having a lambda (S) -> Pair<T, S>?, we use State<S, Option<T>> and we use the function fold from Option, with an empty Sequence for ...
Read now
Unlock full access