I have been using Scala as a means to learn Functional Programming and writing better code. However, I have some questions regarding some exercises or if there's a better way to approach them.
In the exercises below, I have already defined the functions
HARD - Write a function that concatenates a list of lists into a single list. Its runtime should be linear in the total length of all lists. Try to use functions we have already defined.
//concatenates list of lists in a single list def concatLists(x: List[List[Int]]):List[Int] = x.foldLeft( List[Int]() )( (x,y)=> x ++ y )
I have the feeling that the use of
foldLeft and the concatenation operator is the right way to go and the runtime feels linear because we are appending one element at a time to the result of the fold, so the time is linear in the input size, am I right? Or is the
++ operator not efficient due to the
List being implemented as a linked list? If not, how can I improve this?
EXERCISE 16: Write a function that transforms a list of integers by adding 1 to each element. (Reminder: this should be a pure function that returns a new List !)
//Adds one - exercise 16 def add1(x:List[Int]):List[Int]= for(elem <- x) yield elem+1
EXERCISE 18: Write a function map , that generalizes modifying each element in a list while maintaining the structure of the list. Here is its signature:
def map[A,B](l: List[A])(f: A => B): List[B]
//implements map - exercise 18 def map[A,B](l: List[A])(f: A => B): List[B]=for(elem <- l) yield f(elem)
I've used yield before in some "toy exercises" in sites like hackerrank and similar and from my understanding, it is used in sequence comprehensions and adds a new element to the resulting sequence, much like in Python and the sequence assumes the return type declared in the function signature, is this correct?
What I want to know is if these implementations are correct in functional terms or if there are other/better ways of writing them.