Igor Kolomiets

    Igor Kolomiets

    4 months ago
    I was surprised Kotlin stdlib doesn’t have standard function for list comprehension to get head and tail of the list:
    fun <T> List<T>.headAndTail() = Pair(first(), drop(1))
    Does Kotlin offer more idiomatic approach to do this?
    c

    Chris Lee

    4 months ago
    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).
    fun <T> List<T>.headAndTail() = Pair(first(), last())
    Igor Kolomiets

    Igor Kolomiets

    4 months ago
    Thank you. I still think my version is ok, because
    tail
    must be the remainder of the list.
    c

    Chris Lee

    4 months ago
    i see. typically tailrefers 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.
    Rob Elliot

    Rob Elliot

    4 months ago
    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.
    c

    Chris Lee

    4 months ago
    ah, yes, all that LISP is coming back now…
    Igor Kolomiets

    Igor Kolomiets

    4 months ago
    recursive definition of list as first element (a head) and the rest of it (a tail) is very common in functional programming
    c

    Chris Lee

    4 months ago
    understood. perhaps see if there are FP libraries to add onto Kotlin (it’s not a full FP language).
    Igor Kolomiets

    Igor Kolomiets

    4 months ago
    there are similar constructs (and much more) in the Arrow library, but it’s too much for my modest needs.
    e

    ephemient

    4 months ago
    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.