![]() As with map, the general syntax takes a function, but that function must return a Boolean: val someFunction: (a) > Boolean collection.filter (someFunction) You can provide an anonymous function directly: collection.filter ( (x: T) > /Do. Although so much of what I've learned has been about speed, this is a concept where the runtime speed is not decreased (or increased for that matter), but it does make the code more legible to the next person having to read it. filter is used when you want to exclude or filter out certain elements of a collection. We also see the concept 'expressivity', allowing us to more easily convey an idea to the reader of the code what we are trying to accomplish without necessitating a 'for' loop. return a list of only even elements using filterĪs can be seen, foldLeft, map, and filter are more about making our code more readable. Here we have our list, we are using filter, using element 'a' and applying the modulo 2 in order to keep the even elements of the list. filter takes a list and a function, and the function takes an element from the list and returns a boolean. adding one to each element of a list using map Here, 'a' is an element of the list, and 'a+1' is our operation. Looking at map, on the other hand, we see that it takes a list and a function, and returns another list made up from the result of the function applied to each element. Return a list w/ only even numbers using fold Here I show how can we return a list containing only even numbers using foldLeft: In another example, here I show how can we add 1 to a list using foldLeft: Let's start with foldLeft, it is a useful method that takes a list, a function and a starting point and uses the function to operate on the list element by element.įor example, how can we get the sum of a list using foldLeft? Note that 'a' here is what we are folding into, whereas the 'b' is the next element from the list. But, with these higher order functions, we are still thinking about what we want to do with each element in a list, and even though this method is not any faster, it's about 'expressivity' and can simplify what we want to say with our code. These are a way of NOT writing loops, we don't need to think about the implementation of the loop. What exactly are foldLeft, map, and filter in Scala? They are higher order functions, they operate on lists by taking in functions and applying these functions to a list(s).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |