Higher Order Functions

Total Page:16

File Type:pdf, Size:1020Kb

Higher Order Functions Overview Higher-Order List Functions The big ideas for today’s lecture and the next lecture: o In Python, functions are first-class values that can be map, filter, and reduce manipulated like other values (numbers, strings, booleans, lists, dictionaries, objects, etc.). They can be: 1. Named by variables 2. Passed as arguments to other functions 3. Returned as results from other functions 4. Stored in data structures (lists, dictionaries, objects) CS111 Computer Programming o Functions that take other functions as arguments or return functions as results are called higher-order functions. Department of Computer Science Wellesley College o Higher-order list functions like map, filter, and reduce capture common list-manipulation patterns. They are much simpler than loops for performing many list manipulation tasks. 21-2 Some num-to-num functions Function names are just variables! Here are some Python functions that take a single When we define a function, the function name is just numeric argument and return a numeric result. a variable whose value is the function object. We’ll call these num-to-num functions. In[5]: increment # no parens! Out[5]: <function __main__.increment> def increment(n): return n+1 In[6]: double def double(w): return w*2 Out[6]: <function __main__.double> def half(x): return x/2.0 In[7]: renamedDouble = double def square(y): return y*y In[8]: renamedDouble(7) Out[8]: 14 def cube(z): return z*z*z 21-3 21-4 Functions as arguments: applyTo5 Functions as arguments: leastInput We can define functions that take another function def leastInput(fcn, threshold) as a parameter. For example: '''Return the least nonnegative integer for which fcn returns an output greater than threshold''' i = 0 def applyTo5(f): Can pass a function while fcn(i) <= threshold: return f(5) as an argument! # loop until fcn output surpasses threshold i += 1 When we invoke functions like applyTo5, we pass the return i # least i for which fcn(i) > threshold function argument by using its name (without parens!) leastInput(square, 10) applyTo5(increment) leastInput(square, 100) leastInput(cube, 10) applyTo5(double) leastInput(cube, 100) applyTo5(half) leastInput(double, 10) leastInput(double, 100) applyTo5(square) leastInput(half, 10) applyTo5(cube) 21-5 leastInput(half, 100) 21-6 Functions as results: randomFunction Testing randomFunction def randomFunction(): def testRandomFunction(num): '''Returns one of five num-to-num functions''' fcn = randomNumToNumFunction() funs = [increment, double, half, square, cube] return fcn(num) # can store functions in a list! f = random.choice(funs) # can name function with a variable! In[12]: testRandomFunction(10) return f # can return function as a result! Out[12]: 20 In[9]: randomFunction() In[13]: testRandomFunction(10) Out[9]: <function __main__.cube> Out[13]: 1000 In[10]: randomFunction() Out[10]: <function __main__.increment> In[14]: testRandomFunction(10) Out[14]: 11 In[11]: randomFunction() Out[11]: <function __main__.double> 21-7 21-8 Simplifying randomFunction Higher-order functions def randomFunction2(): A function is higher-order if it takes another function return random.choice([increment, double, as an argument or returns another function as a result. half, square, cube]) def testRandomFunction2(num): Here are examples of higher-order functions we’ve seen: return (randomFunction2())(num) o applyTo5 o leastInput o randomFunction 21-9 21-10 Functions are first-class values! The map function captures the mapping A first-class value is an entity with these properties: pattern 1. It can be named by a variable; Previously, we saw examples of the list mapping 2. It can be passed as an argument to a function; pattern, in which the output list is the same length as the input list, and each element of the output list 3. It can be returned as the result from a function; is the result of applying some function to the 4. It can be stored in a data structure corresponding element of the input list. (e.g., list, tuple, dictionary, object) We already knew the following were first-class values mapDouble( [8, 3, 6, 7, 2, 4] ) in Python: numbers, strings, booleans, None, *2 *2 *2 *2 *2 *2 lists, tuples, dictionaries, objects [16, 6, 12, 14, 4, 8] Today we learned functions are first-class values, too! 21-11 21-12 The map function captures the mapping The map function captures the mapping pattern pattern Previously, we saw examples of the list mapping Python provides a map function that captures this pattern, in which the output list is the same length pattern. When invoked as map(function, as the input list, and each element of the output list inlist), it returns a new output list that’s the is the result of applying some function to the same length as inlist in which every element is the corresponding element of the input list. result of applying function to the corresponding element of inlist. mapPluralize( [‘donut’, ‘muffin’, ‘bagel’] ) map(f, [e1, e2, …, en] ) +s +s +s f f f [‘donuts’, ‘muffins’, ‘bagels’] [f(e1), f(e2), …, f(en)] 21-13 21-14 map examples map examples Suppose we define the following functions: In[15]: map(double, [8,3,6,7,2,4]) Out[15]: [16, 6, 12, 14, 4, 8] def double(n): def pluralize(st): In[16]: map(pluralize, [‘donut’,‘muffin’,‘bagel’]) return 2*n return st+’s’ Out[16]: [‘donuts’, ‘muffins’, ‘bagels’] Note that the first argument to map in these examples Then we can use map to apply these functions to is a one-argument function. It is just the function itself each element of a list: and not the result of applying the function to anything. In[15]: map(double, [8,3,6,7,2,4]) There’s a big difference between these two situations: Out[15]: [16, 6, 12, 14, 4, 8] In[17]: pluralize # just the function itself Out[17]: <function __main__.pluralize> In[16]: map(pluralize, [‘donut’,‘muffin’,‘bagel’]) Out[16]: [‘donuts’, ‘muffins’, ‘bagels’] In[18]: pluralize(‘donut’) # result of applying function 21-15 Out[18]: ‘donuts’ 21-16 mapDouble and mapPluralize without loops Customized map function def mapDouble(nums): return map(double, nums) How does map work? To illustrate, we can define our own version of Python's map function as follows: def mapPluralize(strings): return map(pluralize, strings) def myMap(f, elts): result = [] for e in elts: In[19]: mapDouble([8,3,6,7,2,4]) result.append(f(e)) Out[19]: [16, 6, 12, 14, 4, 8] return result In[20]: mapPluralize([‘donut’,‘muffin’,‘bagel’]) Out[20]: [‘donuts’, ‘muffins’, ‘bagels’] In[21]: myMap(double, [8,3,6,7,2,4]) Out[21]: [16,6,12,14,4,8] 21-17 21-18 Customized map function Customized map function def myMap(f, elts): def myMap(f, elts): result = [] result = [] for e in elts: for e in elts: result.append(f(e)) result.append(f(e)) return result return result All myMap does is capture the mapping pattern we've The definition of myMap depends critically on being seen before in one function so that we don't have to able to pass a function as a parameter. Not all repeat it over and over again. We write a standard programming languages permit this, but Python does. loop that accumulates a list result in myMap exactly Functions that take other functions as parameters once, and then we never need to write this loop again or return them as results are called higher-order for the mapping pattern. functions. Thus, map is an example of a higher- order list function, i.e., a higher order function that 21-19 manipulates lists. 21-20 Exercise Defining local functions to use with map Using the map function, define a mapSquare In the previous examples, we defined a global function that takes a list of numbers and returns a function double to use within the mapDouble list of its squares: function definition. It would be nicer to define everything within one function, and Python lets us do In[22]: mapSquare([8,3,5]) this by defining the double function inside the Out[22]: [64,9,25] mapDouble function: Using the map function, define a mapUpper function that takes a list of strings and returns the result of def mapDouble(nums): uppercasing each string. Use the string .upper() # Locally define double function within mapDouble. method to uppercase strings. # Can only be used inside mapDouble and not outside def double(n): In[23]: mapUpper(['ant','bat','cat']) return 2*n return map(double, nums) Out[23]: ['ANT','BAT','CAT'] 21-21 21-22 Defining local functions to use with map Defining local functions to use with map Sometimes we must define the function used by map Sometimes we must define the function used by map locally within another function because it needs to locally within another function because it needs to refer to a parameter or some other piece of refer to a parameter or some other piece of information that is local to the enclosing function. information that is local to the enclosing function. def mapScale(factor,nums): def mapPrefixes(string): # Can't define this outside of mapScale, because # Can't define this outside of mapPrefixes, because # it needs to refer to parameter named "factor" # it needs to refer to parameter named "string" def scale(n): def prefix(i): return factor*n return string[:i] return map(scale, nums) return map(prefix, range(len(string)+1)) In[24]: mapScale(3, [8,3,6,7,2,4]) Out[24]: [24,9,18,21,6,12] In[26]: mapPrefixes('program') Out[26]: In[25]: mapScale(10, [8,3,6,7,2,4]) [‘’,'p','pr','pro','prog','progr','progra','program'] Out[25]: [80,30,60,70,20,40] 21-23 21-24 Exercise The Filtering Pattern Using the map function, define a mapPreConcat function that takes a string pre and a list of strings We've seen examples of the filtering pattern, in which and returns the result of concatenating pre in front an output list includes only those input elements for of every string in the list.
Recommended publications
  • From Perl to Python
    From Perl to Python Fernando Pineda 140.636 Oct. 11, 2017 version 0.1 3. Strong/Weak Dynamic typing The notion of strong and weak typing is a little murky, but I will provide some examples that provide insight most. Strong vs Weak typing To be strongly typed means that the type of data that a variable can hold is fixed and cannot be changed. To be weakly typed means that a variable can hold different types of data, e.g. at one point in the code it might hold an int at another point in the code it might hold a float . Static vs Dynamic typing To be statically typed means that the type of a variable is determined at compile time . Type checking is done by the compiler prior to execution of any code. To be dynamically typed means that the type of variable is determined at run-time. Type checking (if there is any) is done when the statement is executed. C is a strongly and statically language. float x; int y; # you can define your own types with the typedef statement typedef mytype int; mytype z; typedef struct Books { int book_id; char book_name[256] } Perl is a weakly and dynamically typed language. The type of a variable is set when it's value is first set Type checking is performed at run-time. Here is an example from stackoverflow.com that shows how the type of a variable is set to 'integer' at run-time (hence dynamically typed). $value is subsequently cast back and forth between string and a numeric types (hence weakly typed).
    [Show full text]
  • Declare New Function Javascript
    Declare New Function Javascript Piggy or embowed, Levon never stalemating any punctuality! Bipartite Amory wets no blackcurrants flagged anes after Hercules supinate methodically, quite aspirant. Estival Stanleigh bettings, his perspicaciousness exfoliating sopped enforcedly. How a javascript objects for mistakes to retain the closure syntax and maintainability of course, written by reading our customers and line? Everything looks very useful. These values or at first things without warranty that which to declare new function javascript? You declare a new class and news to a function expressions? Explore an implementation defined in new row with a function has a gas range. If it allows you probably work, regular expression evaluation but mostly warszawa, and to retain the explanation of. Reimagine your namespaces alone relate to declare new function javascript objects for arrow functions should be governed by programmers avoid purity. Js library in the different product topic and zip archives are. Why is selected, and declare a superclass method decorators need them into functions defined by allocating local time. It makes more sense to handle work in which support optional, only people want to preserve type to be very short term, but easier to! String type variable side effects and declarations take a more situations than or leading white list of merchantability or a way as explicit. You declare many types to prevent any ecmascript program is not have two categories by any of parameters the ecmascript is one argument we expect. It often derived from the new knowledge within the string, news and error if the function expression that their prototype.
    [Show full text]
  • Scala by Example (2009)
    Scala By Example DRAFT January 13, 2009 Martin Odersky PROGRAMMING METHODS LABORATORY EPFL SWITZERLAND Contents 1 Introduction1 2 A First Example3 3 Programming with Actors and Messages7 4 Expressions and Simple Functions 11 4.1 Expressions And Simple Functions...................... 11 4.2 Parameters.................................... 12 4.3 Conditional Expressions............................ 15 4.4 Example: Square Roots by Newton’s Method................ 15 4.5 Nested Functions................................ 16 4.6 Tail Recursion.................................. 18 5 First-Class Functions 21 5.1 Anonymous Functions............................. 22 5.2 Currying..................................... 23 5.3 Example: Finding Fixed Points of Functions................ 25 5.4 Summary..................................... 28 5.5 Language Elements Seen So Far....................... 28 6 Classes and Objects 31 7 Case Classes and Pattern Matching 43 7.1 Case Classes and Case Objects........................ 46 7.2 Pattern Matching................................ 47 8 Generic Types and Methods 51 8.1 Type Parameter Bounds............................ 53 8.2 Variance Annotations.............................. 56 iv CONTENTS 8.3 Lower Bounds.................................. 58 8.4 Least Types.................................... 58 8.5 Tuples....................................... 60 8.6 Functions.................................... 61 9 Lists 63 9.1 Using Lists.................................... 63 9.2 Definition of class List I: First Order Methods..............
    [Show full text]
  • Lambda Expressions
    Back to Basics Lambda Expressions Barbara Geller & Ansel Sermersheim CppCon September 2020 Introduction ● Prologue ● History ● Function Pointer ● Function Object ● Definition of a Lambda Expression ● Capture Clause ● Generalized Capture ● This ● Full Syntax as of C++20 ● What is the Big Deal ● Generic Lambda 2 Prologue ● Credentials ○ every library and application is open source ○ development using cutting edge C++ technology ○ source code hosted on github ○ prebuilt binaries are available on our download site ○ all documentation is generated by DoxyPress ○ youtube channel with over 50 videos ○ frequent speakers at multiple conferences ■ CppCon, CppNow, emBO++, MeetingC++, code::dive ○ numerous presentations for C++ user groups ■ United States, Germany, Netherlands, England 3 Prologue ● Maintainers and Co-Founders ○ CopperSpice ■ cross platform C++ libraries ○ DoxyPress ■ documentation generator for C++ and other languages ○ CsString ■ support for UTF-8 and UTF-16, extensible to other encodings ○ CsSignal ■ thread aware signal / slot library ○ CsLibGuarded ■ library for managing access to data shared between threads 4 Lambda Expressions ● History ○ lambda calculus is a branch of mathematics ■ introduced in the 1930’s to prove if “something” can be solved ■ used to construct a model where all functions are anonymous ■ some of the first items lambda calculus was used to address ● if a sequence of steps can be defined which solves a problem, then can a program be written which implements the steps ○ yes, always ● can any computer hardware
    [Show full text]
  • PHP Advanced and Object-Oriented Programming
    VISUAL QUICKPRO GUIDE PHP Advanced and Object-Oriented Programming LARRY ULLMAN Peachpit Press Visual QuickPro Guide PHP Advanced and Object-Oriented Programming Larry Ullman Peachpit Press 1249 Eighth Street Berkeley, CA 94710 Find us on the Web at: www.peachpit.com To report errors, please send a note to: [email protected] Peachpit Press is a division of Pearson Education. Copyright © 2013 by Larry Ullman Acquisitions Editor: Rebecca Gulick Production Coordinator: Myrna Vladic Copy Editor: Liz Welch Technical Reviewer: Alan Solis Compositor: Danielle Foster Proofreader: Patricia Pane Indexer: Valerie Haynes Perry Cover Design: RHDG / Riezebos Holzbaur Design Group, Peachpit Press Interior Design: Peachpit Press Logo Design: MINE™ www.minesf.com Notice of Rights All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contact [email protected]. Notice of Liability The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of the book, neither the author nor Peachpit Press shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described in it. Trademarks Visual QuickPro Guide is a registered trademark of Peachpit Press, a division of Pearson Education. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks.
    [Show full text]
  • Chapter 15. Javascript 4: Objects and Arrays
    Chapter 15. JavaScript 4: Objects and Arrays Table of Contents Objectives .............................................................................................................................................. 2 15.1 Introduction .............................................................................................................................. 2 15.2 Arrays ....................................................................................................................................... 2 15.2.1 Introduction to arrays ..................................................................................................... 2 15.2.2 Indexing of array elements ............................................................................................ 3 15.2.3 Creating arrays and assigning values to their elements ................................................. 3 15.2.4 Creating and initialising arrays in a single statement ..................................................... 4 15.2.5 Displaying the contents of arrays ................................................................................. 4 15.2.6 Array length ................................................................................................................... 4 15.2.7 Types of values in array elements .................................................................................. 6 15.2.8 Strings are NOT arrays .................................................................................................. 7 15.2.9 Variables — primitive
    [Show full text]
  • Steps-In-Scala.Pdf
    This page intentionally left blank STEPS IN SCALA An Introduction to Object-Functional Programming Object-functional programming is already here. Scala is the most prominent rep- resentative of this exciting approach to programming, both in the small and in the large. In this book we show how Scala proves to be a highly expressive, concise, and scalable language, which grows with the needs of the programmer, whether professional or hobbyist. Read the book to see how to: • leverage the full power of the industry-proven JVM technology with a language that could have come from the future; • learn Scala step-by-step, following our complete introduction and then dive into spe- cially chosen design challenges and implementation problems, inspired by the real-world, software engineering battlefield; • embrace the power of static typing and automatic type inference; • use the dual object and functional oriented natures combined at Scala’s core, to see how to write code that is less “boilerplate” and to witness a real increase in productivity. Use Scala for fun, for professional projects, for research ideas. We guarantee the experience will be rewarding. Christos K. K. Loverdos is a research inclined computer software profes- sional. He holds a B.Sc. and an M.Sc. in Computer Science. He has been working in the software industry for more than ten years, designing and implementing flex- ible, enterprise-level systems and making strategic technical decisions. He has also published research papers on topics including digital typography, service-oriented architectures, and highly available distributed systems. Last but not least, he is an advocate of open source software.
    [Show full text]
  • FUNCTORS (FUNCTION OBJECTS) Functors (Function Objects) Let's Start with a Very Simple Usage of Functor
    C++ TUTORIAL – FUNCTORS (FUNCTION OBJECTS) Functors (Function Objects) Let's start with a very simple usage of functor: #include <iostream> #include <string> class A { public: void operator()(std::string str) { std::cout << "functor A " << str << std::endl; } }; int main() { A aObj; aObj("Hello"); } We have a class A which has an operator() defined. In main(), we create an instance and passing in a string argument to that object. Note that we're using an instance as if it's a function. This is the core idea of functors. A functors' claim: "Anything behaves like a function is a function. In this case, A behaves like a function. So, A is a function even though it's a class." We counters with a question: Why do we need you, functor? We can just use a regular function. We do not need you. Functor explains the benefits of using it: "We're not simple plain functions. We're smart. We feature more than operator(). We can have states. For example, the class A can have its member for the state. Also, we can have types as well. We can differentiate function by their signature. We have more than just the signature." Functor is a parameterized function A functor is a parameterized function. #include <iostream> #include <string> class A { public: A(int i) : id(i) {} void operator()(std::string str) { std::cout << "functor A " << str << std::endl; } private: int id; }; int main() { A(2014)("Hello"); } Now, the class A is taking two parameters. Why do we want like that. Can we just use a regular function that takes the two parameters? Let's look at the following example: #include <iostream> #include <vector> #include <algorithm> using namespace std; void add10(int n) { cout << n+10 << " "; } int main() { std::vector<int> v = { 1, 2, 3, 4, 5 }; for_each(v.begin(), v.end(), add10); //{11 12 13 14 15} } In main(), the function add10 will be invoked for each element of the vector v, and prints out one by one after adding 10.
    [Show full text]
  • Functional Programming Patterns in Scala and Clojure Write Lean Programs for the JVM
    Early Praise for Functional Programming Patterns This book is an absolute gem and should be required reading for anybody looking to transition from OO to FP. It is an extremely well-built safety rope for those crossing the bridge between two very different worlds. Consider this mandatory reading. ➤ Colin Yates, technical team leader at QFI Consulting, LLP This book sticks to the meat and potatoes of what functional programming can do for the object-oriented JVM programmer. The functional patterns are sectioned in the back of the book separate from the functional replacements of the object-oriented patterns, making the book handy reference material. As a Scala programmer, I even picked up some new tricks along the read. ➤ Justin James, developer with Full Stack Apps This book is good for those who have dabbled a bit in Clojure or Scala but are not really comfortable with it; the ideal audience is seasoned OO programmers looking to adopt a functional style, as it gives those programmers a guide for transitioning away from the patterns they are comfortable with. ➤ Rod Hilton, Java developer and PhD candidate at the University of Colorado Functional Programming Patterns in Scala and Clojure Write Lean Programs for the JVM Michael Bevilacqua-Linn The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals.
    [Show full text]
  • Modeling Data with Functional Programming in R 2 Preface
    Brian Lee Yung Rowe Modeling Data With Functional Programming In R 2 Preface This book is about programming. Not just any programming, but program- ming for data science and numerical systems. This type of programming usually starts as a mathematical modeling problem that needs to be trans- lated into computer code. With functional programming, the same reasoning used for the mathematical model can be used for the software model. This not only reduces the impedance mismatch between model and code, it also makes code easier to understand, maintain, change, and reuse. Functional program- ming is the conceptual force that binds the these two models together. Most books that cover numerical and/or quantitative methods focus primarily on the mathematics of the model. Once this model is established the computa- tional algorithms are presented without fanfare as imperative, step-by-step, algorithms. These detailed steps are designed for machines. It is often difficult to reason about the algorithm in a way that can meaningfully leverage the properties of the mathematical model. This is a shame because mathematical models are often quite beautiful and elegant yet are transformed into ugly and cumbersome software. This unfortunate outcome is exacerbated by the real world, which is messy: data does not always behave as desired; data sources change; computational power is not always as great as we wish; re- porting and validation workflows complicate model implementations. Most theoretical books ignore the practical aspects of working in thefield. The need for a theoretical and structured bridge from the quantitative methods to programming has grown as data science and the computational sciences become more pervasive.
    [Show full text]
  • Function Programming in Python
    Functional Programming in Python David Mertz Additional Resources 4 Easy Ways to Learn More and Stay Current Programming Newsletter Get programming related news and content delivered weekly to your inbox. oreilly.com/programming/newsletter Free Webcast Series Learn about popular programming topics from experts live, online. webcasts.oreilly.com O’Reilly Radar Read more insight and analysis about emerging technologies. radar.oreilly.com Conferences Immerse yourself in learning at an upcoming O’Reilly conference. conferences.oreilly.com ©2015 O’Reilly Media, Inc. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. #15305 Functional Programming in Python David Mertz Functional Programming in Python by David Mertz Copyright © 2015 O’Reilly Media, Inc. All rights reserved. Attribution-ShareAlike 4.0 International (CC BY-SA 4.0). See: http://creativecommons.org/licenses/by-sa/4.0/ Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Editor: Meghan Blanchette Interior Designer: David Futato Production Editor: Shiny Kalapurakkel Cover Designer: Karen Montgomery Proofreader: Charles Roumeliotis May 2015: First Edition Revision History for the First Edition 2015-05-27: First Release The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Functional Pro‐ gramming in Python, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
    [Show full text]
  • Building Your Own Function Objects
    Building your own function objects An article from Scala in Action EARLY ACCESS EDITION Nilanjan Raychaudhuri MEAP Release: March 2010 Softbound print: Spring 2011 | 525 pages ISBN: 9781935182757 This article is taken from the book Scala in Action. The author explains using objects as functions. Tweet this button! (instructions here) Get 35% off any version of Scala in Action with the checkout code fcc35. Offer is only valid through www.manning.com. A function object is an object that you can use as a function. That doesn’t help you much, so why don’t I show you an example? Here, we create a function object that wraps a foldLeft method: object foldl { def apply[A, B](xs: Traversable[A], defaultValue: B)(op: (B, A) => B) = (defaultValue /: xs)(op) } Now we can use our foldl function object like any function: scala> foldl(List("1", "2", "3"), "0") { _ + _ } res0: java.lang.String = 0123 scala> foldl(IndexedSeq("1", "2", "3"), "0") { _ + _ } res24: java.lang.String = 0123 scala> foldl(Set("1", "2", "3"), "0") { _ + _ } res25: java.lang.String = 0123 To treat an object as a function object, all you have to do is declare an apply method. In Scala, <object>(<arguments>) is syntactic sugar for <object>.apply(<arguments>). Now, because we defined the first parameter as Traversable, we can pass IndexedSeq, Set, or any type of collection to our function. The expression (defaultValue /: xs)(op) might look a little cryptic, but the idea isn’t to confuse you but to demonstrate the alternative syntax for foldLeft, /:. When an operator ends with :, then the right- associativity kicks in.
    [Show full text]