https://kotlinlang.org logo
#functional
Title
# functional
j

Jakub Pi

05/11/2020, 2:45 PM
If I'm implementing take via unfold, what's the difference between encoding the remaining n as part of the state vs a recursive call?
Copy code
fun <A> Stream<A>.take(n: Int): Stream<A> = 
    unfold(Pair(this, n)) { (s, n) -> 
        if (s is Cons && n > 0) Some(Pair(s.h(), Pair(s.t(), n-1)))
        else None
    }
Copy code
fun <A> Stream<A>.take(n: Int): Stream<A> =
    unfold(this) { s ->
        if (s is Cons && n > 0) Some(Pair(s.h(), s.t().take(n-1)))
        else None
    }
Are they both equally viable, and are there some hidden costs associated with one of them?
2 Views