![]() The ::: operator will however correctly enforce both the inner type and collection type. The ++ introduced in Scala 2.8 allows you do add any 2 collections together, which can lead to very interesting things. x ::: y ::: z is parsed as x ::: (y ::: z), which is algorithmically faster than (x ::: y) ::: z, as the latter variant requires O(|x|) more steps). X ::: y ::: z is faster than x ++ y ++ z, because ::: is right associative. There are two reasons: efficiency and type safety around the collection type. You can now add all collections with ++, including Iterator, however they bear a small problem. List is one of the few collections who got to keeps its original functionally oriented ::: operator after Scala 2.8. To improve your code, it may be useful to know that there are 2 variants of concatenation operations, one of which is specific to List. ![]() What I want to know is if these implementations are correct in functional terms or if there are other/better ways of writing them.ĮDIT: Already "defined" functions in previous exercises were: foldLeft, foldRight,append, sum, product, head and tailĪ foldLeft is indeed the right solution. 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? Here is its signature: def map(l: List)(f: A => B): List //Adds one - exercise 16ĭef add1(x:List):List= for(elem B): List=for(elem <- l) yield f(elem) (Reminder: this should be a pure function that returns a newĮXERCISE 18: Write a function map, that generalizes modifying each element in a list while maintaining the structure of the list. 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?ĮXERCISE 16: Write a function that transforms a list of integers by adding 1 My sol: //concatenates list of lists in a single listĭef concatLists(x: List]):List = x.foldLeft( List() )( (x,y)=> x ++ y ) ![]() Try to use functions we have already defined. Its runtime should be linear in the total length of all lists. HARD - Write a function that concatenates a list of lists into a single list. However, I have some questions regarding some exercises or if there's a better way to approach them.īelow are some exercises and my solutions/insights/doubts: I have been using Scala as a means to learn Functional Programming and writing better code.
0 Comments
Leave a Reply. |