I was surprised Kotlin stdlib doesn’t have standar...
# stdlib
i
I was surprised Kotlin stdlib doesn’t have standard function for list comprehension to get head and tail of the list:
Copy code
fun <T> List<T>.headAndTail() = Pair(first(), drop(1))
Does Kotlin offer more idiomatic approach to do this?
c
that’s a specialized use case that can be readily satisfied using existing API. btw, your example isn’t head and tail (unless the list is only two items).
Copy code
fun <T> List<T>.headAndTail() = Pair(first(), last())
i
Thank you. I still think my version is ok, because
tail
must be the remainder of the list.
c
i see. typically `tail`refers to the last item in the list. Unclear why you’d want the first item and the remainder of the list, as that’s the original list itself.
r
In FP tail normally means everything other than head
If you write some Haskell you'll get very used to writing recursive functions where you do something with head then call yourself with tail.
👍 1
c
ah, yes, all that LISP is coming back now…
i
recursive definition of list as first element (a head) and the rest of it (a tail) is very common in functional programming
c
understood. perhaps see if there are FP libraries to add onto Kotlin (it’s not a full FP language).
i
there are similar constructs (and much more) in the Arrow library, but it’s too much for my modest needs.
e
uncons makes sense when lists are fundamentally constructed with and traversed with cons cells (as in FP languages). I don't see this being a common operation in Kotlin though.