Function Parameters5:12 with andi mitre
In this video we’ll learn how to create our own higher order functions in Scala. We will create our own example function, which will take another function as a parameter.
Scala provides us with a wide array of built in, higher order functions. 0:00 Most of the time, we'll make use of these built in functions. 0:05 However, there may be times where we want to create our own higher order function. 0:08 Let's take a look at how to do that. 0:13 In an earlier video, we created a map which holds the name and 0:17 ranking of our avengers. 0:21 Let's create a higher order function which takes three avengers and 0:23 compares their ranking by finding the men and the mask. 0:27 Let's copy the avengers map we have created earlier. 0:31 Now let's take out the rankings from these and store them into variables. 0:54 Awesome. 1:38 Now we have the three rankings. 1:39 Let's use them in our function. 1:40 Great. 2:19 We've created a function called compare, 2:20 which takes three arguments that are integers and has a function noted by f: 2:22 that takes these three arguments and combines them to one. 2:27 There are several ways we can invoke such a function. 2:31 Passing the values of the rankings for 2:34 each Avenger, along with the function we would like to use to compare the three. 2:36 First, let's get an idea of which one of our avengers has the best ranking. 2:41 In this example, 3:05 we're comparing the three arguments passed in by finding the minimum between them. 3:05 Remember our compare function takes a function parameter 3:10 which accepts a three arguments. 3:14 The function we pass to compare is the min function with underscores as wildcards 3:16 which represent avenger1, avenger2 and avenger3. 3:21 Let's recompile our code and check out our results. 3:25 As expected, 3:36 we get eight as a result, which is the minimum ranking between our Avengers. 3:37 A ranking of eight belongs to Captain America. 3:43 Captain America is our best ranked Avenger, as his value is closest to one. 3:46 Similarly, we can pass another function and find out the worst ranked Avenger. 3:52 In this case, 4:27 we compared the three arguments passed by finding the maximum between them. 4:28 Remember, our compare function takes a function parameter 4:33 which accepts three arguments. 4:36 The function we passed to compare is the max function with underscores as 4:38 wildcards which represent avenger one, avenger two, and avenger three. 4:43 Let's check out the results. 4:48 Awesome, as expected we got the ranking that's furthest away from one between our 4:54 three avengers. 4:59 Cool. 5:01 Not only did we learn about how to use higher-order functions, but 5:02 we also learned how to create our own. 5:05 In the next video, we'll discuss another topic, closures. 5:08 See you there. 5:11
You need to sign up for Treehouse in order to download course files.Sign up