Why no tail() or head() method in List to get last or first element?

前端 未结 8 896
死守一世寂寞
死守一世寂寞 2020-12-29 04:45

I recently had a discussion with a collegue why the List interface in Java doesn\'t have a head() and tail() method.

In order to implement

8条回答
  •  情话喂你
    2020-12-29 05:19

    In my humble opinion, tail and head are more familiar with people with a functional background. When you start passing functions around, they are incredible useful, that's why most functional languages have them implemented and even have shortcut notation to refer to them, like in haskell or even in scala (even if it's not THAT functional, I know)
    In the "(almost) everything is an object but methods are made in a procedural way" java world, when passing around functions is at least hard and always awkward, head/tail methods are not so useful.
    For example, check this haskell implementation of quicksort:

    quicksort :: Ord a => [a] -> [a]
    quicksort []     = []
    quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
        where
            lesser  = filter (< p) xs
            greater = filter (>= p) xs
    

    It relies, among other things, on the ability to easily separate head and tail, but also on being able to filter a collection using a predicate. A java implementation (check http://www.vogella.de/articles/JavaAlgorithmsQuicksort/article.html) looks totally different, it is way lower level, and doesn't rely on separating head and tail.
    Note: The next sentence is totally subjective and based on my personal experience and may be proven wrong, but I think it's true:
    Most algorithms in functional programming rely on head/tail, in procedural programming you rely on accessing an element in a given position

提交回复
热议问题