lambda expression in c# 4.0 examples

lambda expression basics and lambda expression benefits and lambda expression anonymous function
JadenNorton Profile Pic
JadenNorton,United States,Researcher
Published Date:14-07-2017
Your Website URL(Optional)
Comment
The Road To Lambda Java 8 Day, EclipseCon 2014 Alex Buckley, Oracle lambda-devopenjdk.java.net 1 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 2 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Modernizing Java  Java SE 8 is a big step forward for the Java Language – Lambda Expressions for better abstraction – Default Methods for interface evolution  Java SE 8 is a big step forward for the Java Libraries – Bulk data operations on Collections – More library support for parallelism  Together, perhaps the biggest upgrade ever to the Java programming model  Why did we choose the features we did?  How do we evolve a mature language? 3 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. The Language 4 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. What is a Lambda Expression?  A lambda expression is an anonymous method – Has a parameter list, a return type, and a body (Object o) - o.toString() – Body can refer to effectively final variables in the enclosing lexical scope (Person p) - p.getName().equals(name)  A method reference is a reference to an existing method Object::toString  Allow you to treat code as data – Behavior can be expressed succinctly, stored in variables, and passed to methods – A huge deal because of the impact on library design 5 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. What is the Type of a Lambda Expression?  Many languages have some notion of a function type – “Function from long to int” – Seemed reasonable (at first) to consider adding them to Java  But… – JVM has no native representation of function type in VM type signatures – Obvious tool for representing function types is generics  But then function types would be erased (and boxed) – Is there a simpler alternative? 6 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Functional Interfaces  Historically we used single-method interfaces to represent functions – Runnable, Comparator, ActionListener, FileFilter, … – Let’s call them functional interfaces – And add some new ones like PredicateT, ConsumerT, SupplierT  A lambda expression evaluates to an instance of a functional interface PredicateString isEmpty = s - s.isEmpty(); PredicateString isEmpty = String::isEmpty; Runnable r = () - System.out.println(“Boo”); ;  We define functional interfaces structurally – No syntax or opt-in needed – Existing libraries are forward-compatible with lambda expressions 7 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Times Change  In 1995, most popular languages did not support lambda expressions  By 2013, Java was just about the last holdout – C added them in 2007, Objective-C in 2010, C++ in 2011 – New languages being designed today all do "In another thirty years people will laugh at anyone who tries to invent a language without closures, just as they'll laugh now at anyone who tries to invent a language without recursion." - Mark Jason Dominus 8 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas for Java – a long and winding road  1997 – Odersky / Wadler experimental “Pizza” work – “IMHO Pizza makes finally a usefull language out of java” comp.lang.java 3/6/97  1997 – Java 1.1 added inner classes – Too bulky, complex name resolution rules, many limitations  2006-2008 – vigorous community debate – Multiple proposals, including BGGA and CICE – Each had a different orientation  BGGA – facilitating control abstraction in libraries  CICE – reducing syntactic overhead of inner classes – Things ran aground at this point… 9 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas for Java – a long and winding road  2009-Dec – OpenJDK Project Lambda formed  2010-May – First prototype  2010-Nov – JSR-335 filed  2011-Nov – Early Draft Review 1  2011-Nov – Developer Preview binaries on java.net  2012-Jun – Early Draft Review 2  2013-Feb – Early Draft Review 3  2014-Jan – Proposed Final Draft 10 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Evolving a Mature Language – Key Forces  Encouraging change – Adapting to change  Everything changes: hardware, attitudes, fashions, problems, demographics – Righting what’s wrong  Inconsistencies, holes, poor user experience  Discouraging change – Maintaining compatibility  Low tolerance for change that will break anything – Preserving the “feel of Java”  Can’t alienate user base in quest for “something better”  Easy to focus on cool new stuff, but there’s lots of cool old stuff too 11 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas: Adapting to Change  In 1995, pervasive sequentiality infected programming language design – for-loops are sequential and impose a specific order  Why wouldn’t they be? Why invite nondeterminism?  Determinism is convenient – when free  This sequentiality assumption propagated into libraries (e.g., Iterator) – Pervasive mutability  Mutability is convenient – when free  Object creation was expensive and mutation was cheap  In today’s multicore world, these are the wrong defaults – Can’t just outlaw for-loops and mutability – Instead, gently encourage something better  Lambda expressions are that gentle push 12 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Problem: External Iteration  Snippet takes the red blocks and colors them blue  Uses for-each loop for (Shape s : shapes) – Loop is inherently sequential if (s.getColor() == RED) s.setColor(BLUE); – Client has to manage iteration – This is called external iteration  for-each loop hides complex interaction between library and client – Iterable, iterator(), Iterator.next(), Iterator.hasNext()  What’s the problem? Conflates the what with the how.  A language construct that is inherently sequential is a significant problem. 13 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Solution: Internal Iteration  Re-written to use lambda and Collection.forEach – Not just a syntactic change shapes.forEach(s - – Now the library is in control if (s.getColor() == RED) s.setColor(BLUE); – This is internal iteration ) – More what, less how  Library is free to use parallelism / out-of-order execution / laziness  Client passes behavior (lambda) into the API as data  Enables API designers to build more powerful, expressive APIs – Greater power to abstract over behavior 14 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas & Libraries 15 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas Enable Better APIs  Lambda expressions enable delivery of more powerful APIs  The client-library boundary is more permeable – Client can provide bits of functionality to be mixed into execution – Client determines the what – Library remains in control of the how  Safer: less state management in the client  Faster: exposes more opportunities for optimization 16 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example: Sorting  If we want to sort a List today, we’d write a Comparator Collections.sort(people, new ComparatorPerson() public int compare(Person x, Person y) return x.getLastName().compareTo(y.getLastName()); );  Could replace Comparator with a lambda, but only gets us so far  Comparator conflates extraction of sort key with ordering of that key – Better to separate the two aspects 17 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Example: Sorting  Added static method Comparator.comparing(f) – Takes a “key extractor” function from T to some Comparable key – Returns a ComparatorT – This is a higher-order function – functions in, functions out interface ComparatorT public static T, U extends Comparable? super U ComparatorT comparing(FunctionT, U f) return (x, y) - f.apply(x).compareTo(f.apply(y)); ComparatorPerson byLastName = Comparator.comparing(Person::getLastName); 18 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas Enable Better APIs  The comparing() method is one built for lambdas – Consumes an “extractor” function and produces a “comparator” function – Factors key extraction (client concern) from comparison (library concern) – Eliminates redundancy, boilerplate  Key effect on APIs is: more composability – Centralize generation of Comparators in one place – Leads to better factoring, more regular client code, more reuse  Lambdas in the language → can write better libraries → more readable, less error-prone user code 19 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas Enable Better APIs  Generally, we prefer to evolve the programming model through libraries – Time to market – can evolve libraries faster than language – Decentralized – more library designers than language designers – Risk – easier to change libraries, more practical to experiment – Impact – language changes require coordinated changes to multiple compilers, IDEs, and other tools  But sometimes we reach the limits of what is practical to express in libraries, and need a little help from the language – But a little help, in the right places, can go a long way 20 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.