Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing List#flatMap

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.

like image 778
Kevin Meredith Avatar asked Dec 07 '13 01:12

Kevin Meredith


People also ask

Does array implement List?

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.

What are the classes implementing List interface?

The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector.

Which are not List implementations?

Explanation: SessionList is not an implementation of List interface. The others are concrete classes of List.

How are C# lists implemented?

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.


1 Answers

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...)

like image 91
Seth Tisue Avatar answered Oct 17 '22 20:10

Seth Tisue