Is there a better functional way to write flatMap
?
def flatMap[A,B](list: List[A])(f: A => List[B]): List[B] =
list.map(x => f(x)).flatten
Conceptually, I understand flatMap
in terms of flatten
.
It implements the List interface to use all the methods of List Interface. It takes place in java. util package. The ArrayList class inherits the AbstractList class and implements the List Interface.
The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector.
Explanation: SessionList is not an implementation of List interface. The others are concrete classes of List.
The List class implements the ICollection<T>, IEnumerable<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IEnumerable, and IList interface. It can accept null as a valid value for reference types and also allows duplicate elements.
An alternate approach:
def flatMap[A, B](list: List[A])(f: A => List[B]): List[B] =
list.foldLeft(List[B]())(_ ++ f(_))
I don't know about “better”. (And if we start talking about efficient implementation, that's another can of worms...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With