archive-cr.com » CR » I » INFORMATECH.CR

Total: 292

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Review of Programming Languages Course from Coursera | Informatech CR Blog
    week 8 the students take an online exam consisting in questions with multiple selection answers The questions are based on the topics covered in previous weeks Some of the questions could be based on understanding of the theoretical concepts and some question consist in practical applications of those concepts Once the student starts the exam there is a time limit to complete it I think something around 90 minutes The following is detailed outline of the topics covered every week Week 1 SML ML Expressions and Variable Bindings Variables are Immutable Function Bindings Pairs and Other Tuples Lists Let Expressions Options Some Other Expressions and Operators Lack of Mutation and Benefits Thereof The Pieces of a Programming Language The homework consisted in the development of series of functions to deal with dates Week 2 SML Conceptual Ways to Build New Types Records By Name vs By Position Syntactic Sugar and the Truth about Tuples Datatype Bindings How ML Does Not Provide Access to Data Type Values How ML Provides Access to Datatype Values Case Expressions Type Synonyms Lists and Options Are Datatypes Polymorphic Datatypes Pattern Matching Type Inference Polymorphic Types and Equality Types Nested Patterns Exceptions Tail Recursion and Accumulators The homework consisted in a series of exercises related to a card game a variation of solitaire Week 3 SML Functions as Arguments Polymorphic Types and Functions as Arguments Anonymous Functions Unnecessary Function Wrapping Maps and Filters Returning Functions Lexical Scope Environments and Closures Fold Combining Functions Currying and Partial Application The Value Restriction Mutation via ML References Callbacks Abstract Datatypes Closures in Other Languages The homework consisted in a series of exercises related to the implementation of pattern matching and type inference Week 4 SML What is Type Inference Overview of ML Type Inference Mutual Recursion Modules for Namespace Management Signatures Hiding Things Equivalent Implementations Benefits of Side Effect Free Programming Standard Equivalences There was not homework because this week was the week of the midterm exam Week 5 Racket Racket vs Scheme Functions Lists Syntax and Parentheses Dynamic Typing Local Bindings Top Level Definitions Mutability Immutability Delayed Evaluation with Thunks Lazy Evaluation Streams Memoization Macros The homework consisted in the implementation of exercises related to streams and the challenge was about defining macros Week 6 Racket Datatype Programming without Datatypes Recursive Datatypes via Racket Lists Recursive Datatypes via Racket s struc Implementing Programming Languages Interpreters and Compilers Implementing Closures Defining Macros via Functions in the Metalanguage ML versus Racket What Is Static Checking Correctness Soundness Completeness Undecidability Weak Typing Advantages and Disadvantages of Static Checking The homework consisted in the implementation of an interpreter for small programming language called MUPL Made Up Programming Language Week 7 Ruby Objects Classes Methods Variables Visibility and Getters Setters Everything is an Object Duck Typing Arrays Blocks Hashes and Ranges Subclassing and Inheritance Overriding and Dynamic Dispatch Method Lookup Definition Dynamic Dispatch versus Closures The homework consisted in the implementation of a tetris game Week 8 Ruby OOP Versus Functional Decomposition Multimethods

    Original URL path: http://blog.informatech.cr/2013/03/25/review-of-programming-languages-course-from-coursera/ (2015-08-19)
    Open archived version from archive


  • coursera | Informatech CR Blog
    students are required to submit their homework for peer reviews And they are required to peer review other students homework This exercise is intended to give a broader perspective to the students by means of reading someone else s code This way the student can find better solutions created by others or spot problems in their own solutions etc Also during the peer review process the right best solutions for the exercises were shared with all students participating in the reviews Therefore doing the reviews was the best way to find out the answers to all exercises in the homework On week 4 and week 8 the students take an online exam consisting in questions with multiple selection answers The questions are based on the topics covered in previous weeks Some of the questions could be based on understanding of the theoretical concepts and some question consist in practical applications of those concepts Once the student starts the exam there is a time limit to complete it I think something around 90 minutes The following is detailed outline of the topics covered every week Week 1 SML ML Expressions and Variable Bindings Variables are Immutable Function Bindings Pairs and Other Tuples Lists Let Expressions Options Some Other Expressions and Operators Lack of Mutation and Benefits Thereof The Pieces of a Programming Language The homework consisted in the development of series of functions to deal with dates Week 2 SML Conceptual Ways to Build New Types Records By Name vs By Position Syntactic Sugar and the Truth about Tuples Datatype Bindings How ML Does Not Provide Access to Data Type Values How ML Provides Access to Datatype Values Case Expressions Type Synonyms Lists and Options Are Datatypes Polymorphic Datatypes Pattern Matching Type Inference Polymorphic Types and Equality Types Nested Patterns Exceptions Tail Recursion and Accumulators The homework consisted in a series of exercises related to a card game a variation of solitaire Week 3 SML Functions as Arguments Polymorphic Types and Functions as Arguments Anonymous Functions Unnecessary Function Wrapping Maps and Filters Returning Functions Lexical Scope Environments and Closures Fold Combining Functions Currying and Partial Application The Value Restriction Mutation via ML References Callbacks Abstract Datatypes Closures in Other Languages The homework consisted in a series of exercises related to the implementation of pattern matching and type inference Week 4 SML What is Type Inference Overview of ML Type Inference Mutual Recursion Modules for Namespace Management Signatures Hiding Things Equivalent Implementations Benefits of Side Effect Free Programming Standard Equivalences There was not homework because this week was the week of the midterm exam Week 5 Racket Racket vs Scheme Functions Lists Syntax and Parentheses Dynamic Typing Local Bindings Top Level Definitions Mutability Immutability Delayed Evaluation with Thunks Lazy Evaluation Streams Memoization Macros The homework consisted in the implementation of exercises related to streams and the challenge was about defining macros Week 6 Racket Datatype Programming without Datatypes Recursive Datatypes via Racket Lists Recursive Datatypes via Racket s struc Implementing Programming Languages

    Original URL path: http://blog.informatech.cr/tag/coursera/ (2015-08-19)
    Open archived version from archive

  • jdk8 | Informatech CR Blog
    of method reference is that the method getName is an instance method Therefore the target of its invocation must be an instance which in this case is an arbitrary object being provided as the argument for the method apply in the Function interface definition Instance Method Reference to a Specific Object Let s consider the existence of functional interface named Consumer as follows public interface Consumer T public void accept T t And let s define a method capable of using a consumer to consume all the elements of a given list like this static void forEach Consumer T consumer List T source for T item source consumer accept item Imagine that now we would like to print all the elements contained in a list and for that purpose we could define a consumer using a lambda expressions List Integer numbers asList 1 2 3 4 5 6 7 8 9 forEach n System out println n numbers However we could also make the observation that the method println has the same signature that our Consumer has it receives an integer and does something with it in this case it prints it to the main output However we cannot specify that this is an arbitrary instance method reference by saying PrintStream println because in this case the Consumer interface method accept does not receive as one of its arguments the PrintStream object on which we may want to invoke the method println Conversely we already know which is the target object on which we would like to invoke the method we can see that every time we would like to invoke it on a specific reference in this case the object System out So we could implement our functional interface using an instance method reference to a specific object as follows List Integer numbers asList 1 2 3 4 5 6 7 8 9 forEach System out println numbers In summary there are circumstances in which we would like to use some preexisting code as the implementation for a functional interface in those case we could use one of several variants of method references instead of a more verbose lambda expression Share this Email Facebook Twitter Like this Like Loading March 15 2013 by Edwin Dalorzo Categories Java Programming Tags functional interfaces java jdk8 lambda method references 4 Comments Getting Rid of Boilerplate Code with Java Lambda Expressions As I have mentioned in a previous post there is nothing we can do with lambda expressions that we could not do without them Basically because we can implement a similar idiom in Java using anonymous classes The problem is that anonymous classes require a lot of boilerplate code To demonstrate the value of lambda expressions as a tool to achieve more succinct code in this post I will develop some classical high order functions from scratch Filtering Let s consider the existence of an interface called Predicate defined as follows interface Predicate T public boolean test T t And now let s say we would like to use the Predicate interface to filter the elements of any given list based on a given predicate So we could define something as follows static T List T filter Predicate T predicate List T source List T destiny new ArrayList for T item source if predicate test item destiny add item return destiny Now consider that we had a list of numbers and we would like to filter only those that are odd Traditionally in Java we would use an anonymous class to define the predicate something like this List Integer numbers asList 1 2 3 4 5 6 7 8 9 List Integer onlyOdds filter new Predicate Integer Override public boolean test Integer n return n 2 0 numbers But consider all the boilerplate code that was necessary here to simply say that we would like to take a value n and check if it is an odd number Clearly this does not look good In Java 8 we could get rid of all this mess by simply implementing our predicate using a lambda expression as follows List Integer numbers asList 1 2 3 4 5 6 7 8 9 List Integer onlyOdds filter n n 2 0 numbers Here the lambda expression will be evaluated to an instance of the type Predicate its argument n corresponds to the argument expected by its method test and the body of the expressions represents the implementation of the method Mapping Let s consider now the existence of an interface Function defined as follows interface Function T R public R apply T t And now let s say we would like to use this functional interface to transform the elements of a list from one value to another So we could define a method as follows static T R List R map Function T R function List T source List R destiny new ArrayList for T item source R value function apply item destiny add value return destiny Now consider that we had a list of strings representing numbers and we would like to convert them to their corresponding integer values Once again in the traditional model we could use Java anonymous classes for this like so List String digits asList 1 2 3 4 5 6 7 8 9 List Integer numbers map new Function String Integer Override public Integer apply String digit return Integer valueOf digit digits Once again consider all the boilerplate code necessary for something as simple as converting a string to an integer We could get rid of all that using a lambda expression as follows List String digits asList 1 2 3 4 5 6 7 8 9 List Integer numbers map s Integer valueOf s digits This is clearly much better Once again the lambda expression evaluates to an instance of the type Function String Integer where s represents the argument for its function apply and the body of the lambda expression represents what the function would return in its body Reducing Let s consider now the existence of an interface BinaryOperator defined as follows interface BinaryOperator T public T apply T left T right And now we would like to use this functional interface to reduce the values from a list to a single value So we could use it as follows static T T reduce BinaryOperator T operator T seed List T source for T item source seed operator apply seed item return seed Consider now that we have a list of numbers and we would like to obtain to summation of them all Once more if we intend to use this code as we traditionally have done before the release of Java 8 we would be forced to to following verbose definition as follows List Integer numbers asList 1 2 3 4 5 Integer sum reduce new BinaryOperator Integer Override public Integer apply Integer left Integer right return left right 0 numbers This code can be greatly simplified by the use of a lambda expression as follows List Integer numbers asList 1 2 3 4 5 Integer sum reduce x y x y 0 numbers Where x y correspond to the two arguments left and right that the function apply receives and the body of the expressions would be what it would return Notice that since in this case we have to specify two arguments the lambda expressions is required to specify them within parenthesis otherwise the compiler could determine which arguments are for the lambda expression and which are for the reduce method Consuming Let s consider now the existence of a functional interface Consumer defined as follows interface Consumer T public void accept T t Now we could use implementations of this interface to consume the elements of a list and do something with them like printing them to the main output or sending them over the network or whatever we could consider appropriate For this example let s just print them to the output static T void forEach Consumer T consumer List T source for T item source consumer accept item Look at all the boilerplate code necessary to create a consumer to simply print all the elements of a list List Integer numbers asList 1 2 3 4 5 forEach new Consumer Integer Override public void accept Integer n System out println n numbers However now we could use a simple lambda expression to implement equivalent functionality as follows List Integer numbers asList 1 2 3 4 5 forEach n System out println n numbers The syntax differs a bit from the previous cases because in this case the method we intend to implement through the lambda expression returns void and that is why we use a code block to signify that the type of the lambda expression is also void Producing Let s consider now the existence of a functional interface Supplier as follows interface Supplier T public T get A classical idiom is to use this type of interface to encapsulate an expensive calculation and differ its evaluation until needed something typically known as lazy evaluation For example public static int generateX return 0 public static int generateY some expensive calculation here return 1 public static int calculate Supplier Integer thunkOfX Supplier Integer thunkOfY int x thunkOfX get if x 0 return 0 else return x thunkOfY get By means of passing two suppliers here we defer the evaluation of x and y until needed As you can see if x is equal to 0 y is never needed So by using this idiom we avoid spending a lot of time in a expensive calculation unnecessarily Before lambda expressions the invocation of calculation would have implied a lot of boilerplate code as follows calculate new Supplier Integer Override public Integer get return generateX new Supplier Integer Override public Integer get return generateY However using lambda expressions this a one liner calculate generateX generateY Clearly this is much better Summary of Lambda Syntax So these are different ways to define lambda expressions Predicate Integer isOdd n n 2 0 Function String Integer atoi s Integer valueOf s BinaryOperator Integer product x y x y Comparator Integer maxInt x y x y x y Consumer String printer s System out println s Supplier String producer Hello World Runnable task System out println I am a runnable task In summary lambda expressions are a great tool to get rid of all the boilerplate required by the clunky Java syntax of anonymous classes The new API for Streams makes extensive use of this new syntax int oddSum asList 1 2 3 4 5 stream map n Integer valueOf n filter n n 2 0 reduce 0 x y x y 9 Share this Email Facebook Twitter Like this Like Loading March 12 2013 by Edwin Dalorzo Categories Java Programming Tags java jdk jdk8 lambda programming Leave a comment Java Infinite Streams The following examples make extensive use of the new features in Java 8 to implement the concept of a stream a classical data structure similar to a list that uses lazy evaluation This is not exactly how they have defined the new streams API in Java 8 you can find other articles I have written about this at the end but for me it worked as an excellent exercise to understand important concepts like lazy evaluation the creation of closures through lambda expressions and the value of the new features like default methods and static methods in interfaces The concept is based on the same idea of a stream developed in Lisp by Abelson and Gerald and Julie Sussman in their book Structure and Interpretation of Computer Programs In this article I will develop several examples of infinite streams with Java particularly an infinite stream of natural numbers and on top of that an infinite stream of prime numbers using the sieve of Eratosthenes and finally an infinite stream of Fibonacci numbers The Stream Type Let s start by defining an interface for our streams I will base my design on a classical definition of an algebraic data type for lists A list can be conceived as a simple node composed of two items the first one contains a value and the second one contains a reference that points to the next node When a given list does not have any more nodes then the second item can point to null or to another object that represents the absence of a value i e an object representing an empty list This simple definition works fine for lists but not for streams because in a stream we count on the lazy evaluation of the nodes that is a node is not evaluated until the program actually requires it So in this case we introduce a variant so that the second element of the node is a parameterless closure a k a thunk that when evaluated would provide a reference to the next node In other words the next node is not created until required Let s start with something simple and we ll make it more complex as we go public interface Stream T public T head public Stream T tail public boolean isEmpty Clearly by invoking the method head we can gain access to the value being held within a given node and by invoking tail we can trigger the evaluation of the next node which is itself another Stream node Now the realization of the fact that a stream is nothing but a simple cell with two items is of paramount importance in order to understand the evolution of this concept in the coming paragraphs Stream Implementation Let s now delve into the implementation of a couple of stream nodes There are basically two type of stream nodes the ones that contain nothing and the ones that contain something It is better to start with the simpler of them The following is the definition of what we call an empty stream node Null or Nil are also common names for this type of node public class Empty T implements Stream T public T head throw new UnsupportedOperationException Empty stream public Stream T tail throw new UnsupportedOperationException Empty stream public boolean isEmpty return true This node contains nothing so clearly the empty stream node is just a placeholder to indicate the absence of a value It can be useful to indicate the end of a non empty stream as we ll see later Let s now proceed to the definition of a non empty stream node which is where the magic really happens public class Cons T implements Stream T private final T head stream thunk private final Supplier Stream T tail public Cons T head Supplier Stream T tail this head head this tail tail public T head return this head public Stream T tail triggers closure evaluation return this tail get public boolean isEmpty return false The important thing to notice here is that we do not pass a stream to be assigned directly to the tail of our Cons cell instead we pass a Supplier This interface Supplier is one of the new functional interfaces in Java 8 and it is really appropriate for our definition here because it only contains a nullary method named get that can return any parameterized value that we want So we can use a lambda expression to implement this interface on the fly this would be a closure to generate the next stream node This is where the lazy evaluation magic can happen by means of using this parameterless closure to define the next stream cell Notice as well how the method tail triggers the evaluation of the closure and generates a new stream cell An Infinite Stream of Numbers Let s see how this can be used by writing a small piece of code that creates an infinite stream of numbers starting from n public static Stream Integer from int n return new Cons n from n 1 As we promised the stream node is composed by two values The first one is the value of n and the second one is a thunk or parameterless closure which interestingly when evaluated invokes the method again to generate yet another stream node but this time composed by the value of n 1 and another thunk to the next node and so on and so on Here my definition deviated a bit from Abelson and Sussman who would have returned a supplier closure encapsulating the initial stream node For simplicity I return the initial stream cell instead The important realization here is the fact that the thunk will not be evaluated in the moment we invoke the from method but until we eventually call the tail method of a stream cell returned by our from method here That is why I left a comment in the tail method above saying triggers closure evaluation So we can see how the closure here is helping us to implement the lazy evaluation feature of the stream by delaying the time when the new stream cell is created Now our stream created by the from method above is infinite conceptually speaking Therefore if we try to evaluate it we could loop forever if it weren t because of the limitations in memory resources or the fact that integers in Java are bound to 31 bits 1 bit is reserved for the sign and that they wrap around when an overflow occurs A Finite Stream Based on a Predicate Now the question is how can we possibly extract values from this stream The problem is that if we try to extract anything from an infinite stream in any kind of loop we could go forever So what we need is a way to limit the number of elements in the stream to a discrete amount One way to do this is to create another stream but this time a finite stream based on the first one and that it only

    Original URL path: http://blog.informatech.cr/tag/jdk8/ (2015-08-19)
    Open archived version from archive

  • lambda | Informatech CR Blog
    7 8 9 List Integer odds filter IntPredicates isOdd numbers List Integer evens filter IntPredicates isEven numbers So as we can see we could implement the functional interfaces in this case using both lambda expressions and method references but the syntax with the static method references was more succinct Constructor Method References Let s consider now the existence of a functional interface named Function as follows public interface Function T R public R apply T t Based on it we could define a method map that converts the elements from a source list from certain value T to certain value R as follows static T R List R map Function T R function List T source List R destiny new ArrayList for T item source R value function apply item destiny add value return destiny Now imagine that we had a list of strings containing numbers that we would like to transform to integer values We could do it using a lambda expression to provide an implementation for the Function interface more or less like this List String digits asList 1 2 3 4 5 List Integer numbers map s new Integer s digits However we can clearly infer that the constructor Integer String has the same signature as the apply method in the Function reference required here namely it receives a string as argument and returns an integer So in this case we simplify the implementation of the functional interface by means of using a constructor reference as follows List String digits asList 1 2 3 4 5 List Integer numbers map Integer new digits This conveys the same meaning take a string and make me an integer out of it It is the perfect task for our Integer String constructor Instance Method Reference to Arbitrary Objects Consider now the existence of a class named Jedi defined as follows public class Jedi private String name private int power public Jedi String name int power this name name this power power public String getName return name public int getPower return power equals hashCode toString Now consider that we had a list of jedis and we would like to use our previous function map to extract the name from every jedi and generate a list of names out of the list of jedis Somewhat like this using lambda expressions List Jedi jedis asList new Jedi Obi wan 80 new Jedi Anakin 25 new Jedi Yoda 500 List String names map jedi jedi getName jedis The interesting observation here is that the parameter jedi is the argument for the apply method in the Function reference And we use that reference to a jedi to invoke on it the method getName In other words we invoke a method on the reference we receive as argument So we could simplify this implementation by using an instance method reference as follows List Jedi jedi asList new Jedi Obi wan 80 new Jedi Anakin 25 new Jedi Yoda 500 List String names map Jedi getName jedi Again the interesting aspect of this type of method reference is that the method getName is an instance method Therefore the target of its invocation must be an instance which in this case is an arbitrary object being provided as the argument for the method apply in the Function interface definition Instance Method Reference to a Specific Object Let s consider the existence of functional interface named Consumer as follows public interface Consumer T public void accept T t And let s define a method capable of using a consumer to consume all the elements of a given list like this static void forEach Consumer T consumer List T source for T item source consumer accept item Imagine that now we would like to print all the elements contained in a list and for that purpose we could define a consumer using a lambda expressions List Integer numbers asList 1 2 3 4 5 6 7 8 9 forEach n System out println n numbers However we could also make the observation that the method println has the same signature that our Consumer has it receives an integer and does something with it in this case it prints it to the main output However we cannot specify that this is an arbitrary instance method reference by saying PrintStream println because in this case the Consumer interface method accept does not receive as one of its arguments the PrintStream object on which we may want to invoke the method println Conversely we already know which is the target object on which we would like to invoke the method we can see that every time we would like to invoke it on a specific reference in this case the object System out So we could implement our functional interface using an instance method reference to a specific object as follows List Integer numbers asList 1 2 3 4 5 6 7 8 9 forEach System out println numbers In summary there are circumstances in which we would like to use some preexisting code as the implementation for a functional interface in those case we could use one of several variants of method references instead of a more verbose lambda expression Share this Email Facebook Twitter Like this Like Loading March 15 2013 by Edwin Dalorzo Categories Java Programming Tags functional interfaces java jdk8 lambda method references 4 Comments Getting Rid of Boilerplate Code with Java Lambda Expressions As I have mentioned in a previous post there is nothing we can do with lambda expressions that we could not do without them Basically because we can implement a similar idiom in Java using anonymous classes The problem is that anonymous classes require a lot of boilerplate code To demonstrate the value of lambda expressions as a tool to achieve more succinct code in this post I will develop some classical high order functions from scratch Filtering Let s consider the existence of an interface called Predicate defined as follows interface Predicate T public boolean test T t And now let s say we would like to use the Predicate interface to filter the elements of any given list based on a given predicate So we could define something as follows static T List T filter Predicate T predicate List T source List T destiny new ArrayList for T item source if predicate test item destiny add item return destiny Now consider that we had a list of numbers and we would like to filter only those that are odd Traditionally in Java we would use an anonymous class to define the predicate something like this List Integer numbers asList 1 2 3 4 5 6 7 8 9 List Integer onlyOdds filter new Predicate Integer Override public boolean test Integer n return n 2 0 numbers But consider all the boilerplate code that was necessary here to simply say that we would like to take a value n and check if it is an odd number Clearly this does not look good In Java 8 we could get rid of all this mess by simply implementing our predicate using a lambda expression as follows List Integer numbers asList 1 2 3 4 5 6 7 8 9 List Integer onlyOdds filter n n 2 0 numbers Here the lambda expression will be evaluated to an instance of the type Predicate its argument n corresponds to the argument expected by its method test and the body of the expressions represents the implementation of the method Mapping Let s consider now the existence of an interface Function defined as follows interface Function T R public R apply T t And now let s say we would like to use this functional interface to transform the elements of a list from one value to another So we could define a method as follows static T R List R map Function T R function List T source List R destiny new ArrayList for T item source R value function apply item destiny add value return destiny Now consider that we had a list of strings representing numbers and we would like to convert them to their corresponding integer values Once again in the traditional model we could use Java anonymous classes for this like so List String digits asList 1 2 3 4 5 6 7 8 9 List Integer numbers map new Function String Integer Override public Integer apply String digit return Integer valueOf digit digits Once again consider all the boilerplate code necessary for something as simple as converting a string to an integer We could get rid of all that using a lambda expression as follows List String digits asList 1 2 3 4 5 6 7 8 9 List Integer numbers map s Integer valueOf s digits This is clearly much better Once again the lambda expression evaluates to an instance of the type Function String Integer where s represents the argument for its function apply and the body of the lambda expression represents what the function would return in its body Reducing Let s consider now the existence of an interface BinaryOperator defined as follows interface BinaryOperator T public T apply T left T right And now we would like to use this functional interface to reduce the values from a list to a single value So we could use it as follows static T T reduce BinaryOperator T operator T seed List T source for T item source seed operator apply seed item return seed Consider now that we have a list of numbers and we would like to obtain to summation of them all Once more if we intend to use this code as we traditionally have done before the release of Java 8 we would be forced to to following verbose definition as follows List Integer numbers asList 1 2 3 4 5 Integer sum reduce new BinaryOperator Integer Override public Integer apply Integer left Integer right return left right 0 numbers This code can be greatly simplified by the use of a lambda expression as follows List Integer numbers asList 1 2 3 4 5 Integer sum reduce x y x y 0 numbers Where x y correspond to the two arguments left and right that the function apply receives and the body of the expressions would be what it would return Notice that since in this case we have to specify two arguments the lambda expressions is required to specify them within parenthesis otherwise the compiler could determine which arguments are for the lambda expression and which are for the reduce method Consuming Let s consider now the existence of a functional interface Consumer defined as follows interface Consumer T public void accept T t Now we could use implementations of this interface to consume the elements of a list and do something with them like printing them to the main output or sending them over the network or whatever we could consider appropriate For this example let s just print them to the output static T void forEach Consumer T consumer List T source for T item source consumer accept item Look at all the boilerplate code necessary to create a consumer to simply print all the elements of a list List Integer numbers asList 1 2 3 4 5 forEach new Consumer Integer Override public void accept Integer n System out println n numbers However now we could use a simple lambda expression to implement equivalent functionality as follows List Integer numbers asList 1 2 3 4 5 forEach n System out println n numbers The syntax differs a bit from the previous cases because in this case the method we intend to implement through the lambda expression returns void and that is why we use a code block to signify that the type of the lambda expression is also void Producing Let s consider now the existence of a functional interface Supplier as follows interface Supplier T public T get A classical idiom is to use this type of interface to encapsulate an expensive calculation and differ its evaluation until needed something typically known as lazy evaluation For example public static int generateX return 0 public static int generateY some expensive calculation here return 1 public static int calculate Supplier Integer thunkOfX Supplier Integer thunkOfY int x thunkOfX get if x 0 return 0 else return x thunkOfY get By means of passing two suppliers here we defer the evaluation of x and y until needed As you can see if x is equal to 0 y is never needed So by using this idiom we avoid spending a lot of time in a expensive calculation unnecessarily Before lambda expressions the invocation of calculation would have implied a lot of boilerplate code as follows calculate new Supplier Integer Override public Integer get return generateX new Supplier Integer Override public Integer get return generateY However using lambda expressions this a one liner calculate generateX generateY Clearly this is much better Summary of Lambda Syntax So these are different ways to define lambda expressions Predicate Integer isOdd n n 2 0 Function String Integer atoi s Integer valueOf s BinaryOperator Integer product x y x y Comparator Integer maxInt x y x y x y Consumer String printer s System out println s Supplier String producer Hello World Runnable task System out println I am a runnable task In summary lambda expressions are a great tool to get rid of all the boilerplate required by the clunky Java syntax of anonymous classes The new API for Streams makes extensive use of this new syntax int oddSum asList 1 2 3 4 5 stream map n Integer valueOf n filter n n 2 0 reduce 0 x y x y 9 Share this Email Facebook Twitter Like this Like Loading March 12 2013 by Edwin Dalorzo Categories Java Programming Tags java jdk jdk8 lambda programming Leave a comment Java Infinite Streams The following examples make extensive use of the new features in Java 8 to implement the concept of a stream a classical data structure similar to a list that uses lazy evaluation This is not exactly how they have defined the new streams API in Java 8 you can find other articles I have written about this at the end but for me it worked as an excellent exercise to understand important concepts like lazy evaluation the creation of closures through lambda expressions and the value of the new features like default methods and static methods in interfaces The concept is based on the same idea of a stream developed in Lisp by Abelson and Gerald and Julie Sussman in their book Structure and Interpretation of Computer Programs In this article I will develop several examples of infinite streams with Java particularly an infinite stream of natural numbers and on top of that an infinite stream of prime numbers using the sieve of Eratosthenes and finally an infinite stream of Fibonacci numbers The Stream Type Let s start by defining an interface for our streams I will base my design on a classical definition of an algebraic data type for lists A list can be conceived as a simple node composed of two items the first one contains a value and the second one contains a reference that points to the next node When a given list does not have any more nodes then the second item can point to null or to another object that represents the absence of a value i e an object representing an empty list This simple definition works fine for lists but not for streams because in a stream we count on the lazy evaluation of the nodes that is a node is not evaluated until the program actually requires it So in this case we introduce a variant so that the second element of the node is a parameterless closure a k a thunk that when evaluated would provide a reference to the next node In other words the next node is not created until required Let s start with something simple and we ll make it more complex as we go public interface Stream T public T head public Stream T tail public boolean isEmpty Clearly by invoking the method head we can gain access to the value being held within a given node and by invoking tail we can trigger the evaluation of the next node which is itself another Stream node Now the realization of the fact that a stream is nothing but a simple cell with two items is of paramount importance in order to understand the evolution of this concept in the coming paragraphs Stream Implementation Let s now delve into the implementation of a couple of stream nodes There are basically two type of stream nodes the ones that contain nothing and the ones that contain something It is better to start with the simpler of them The following is the definition of what we call an empty stream node Null or Nil are also common names for this type of node public class Empty T implements Stream T public T head throw new UnsupportedOperationException Empty stream public Stream T tail throw new UnsupportedOperationException Empty stream public boolean isEmpty return true This node contains nothing so clearly the empty stream node is just a placeholder to indicate the absence of a value It can be useful to indicate the end of a non empty stream as we ll see later Let s now proceed to the definition of a non empty stream node which is where the magic really happens public class Cons T implements Stream T private final T head stream thunk private final Supplier Stream T tail public Cons T head Supplier Stream T tail this head head this tail tail public T head return this head public Stream T tail triggers closure evaluation return this tail get public boolean isEmpty return false The important thing to notice here is that

    Original URL path: http://blog.informatech.cr/tag/lambda/ (2015-08-19)
    Open archived version from archive

  • Why There Is Interface Pollution in Java 8 | Informatech CR Blog
    arithmetic on boxed ops sucks and having no story for reducing over ints would be terrible So we re in a tough corner and we re trying to not make it worse Trick 1 for not making it worse is we re not doing all eight primitive types We re doing int long and double all the others could be simulated by these Arguably we could get rid of int too but we don t think most Java developers are ready for that Yes there will be calls for Character and the answer is stick it in an int Each specialization is projected to 100K to the JRE footprint Trick 2 is we re using primitive streams to expose things that are best done in the primitive domain sorting reduction but not trying to duplicate everything you can do in the boxed domain For example there s no IntStream into as Aleksey points out If there were the next question s would be Where is IntCollection IntArrayList IntConcurrentSkipListMap The intention is many streams may start as reference streams and end up as primitive streams but not vice versa That s OK and that reduces the number of conversions needed e g no overload of map for int T no specialization of Function for int T etc We can see that this was a difficult decision for the expert group I think few would agree that this is cool and most of us would most likely agree it was necessary The Checked Exceptions Issue There was a third driving force that could have made things even worse and it is the fact that Java supports two type of exceptions checked and unchecked The compiler requires that we handle or explicitly declare checked exceptions but it requires nothing for unchecked ones So this creates an interesting problem because the method signatures of most of the functional interfaces do not declare to throw any exceptions So for instance this is not possible Writer out new StringWriter Consumer String printer s out write s oops compiler error It cannot be done because the write operation throws a checked exception i e IOException but the signature of the Consumer method does not declare it throws any exception at all So the only solution to this problem would have been to create even more interfaces some declaring exceptions and some not or come up with yet another mechanism at the language level for exception transparency Again to make things less worse the expert group decided to do nothing in this case In the words of Brian Goetz in the lambda mailing list Yes you d have to provide your own exceptional SAMs But then lambda conversion would work fine with them The EG discussed additional language and library support for this problem and in the end felt that this was a bad cost benefit tradeoff Library based solutions cause a 2x explosion in SAM types exceptional vs not which interact badly with existing combinatorial explosions for

    Original URL path: http://blog.informatech.cr/2014/04/04/jdk-8-interface-pollution/?replytocom=2419 (2015-08-19)
    Open archived version from archive

  • Why There Is Interface Pollution in Java 8 | Informatech CR Blog
    ops sucks and having no story for reducing over ints would be terrible So we re in a tough corner and we re trying to not make it worse Trick 1 for not making it worse is we re not doing all eight primitive types We re doing int long and double all the others could be simulated by these Arguably we could get rid of int too but we don t think most Java developers are ready for that Yes there will be calls for Character and the answer is stick it in an int Each specialization is projected to 100K to the JRE footprint Trick 2 is we re using primitive streams to expose things that are best done in the primitive domain sorting reduction but not trying to duplicate everything you can do in the boxed domain For example there s no IntStream into as Aleksey points out If there were the next question s would be Where is IntCollection IntArrayList IntConcurrentSkipListMap The intention is many streams may start as reference streams and end up as primitive streams but not vice versa That s OK and that reduces the number of conversions needed e g no overload of map for int T no specialization of Function for int T etc We can see that this was a difficult decision for the expert group I think few would agree that this is cool and most of us would most likely agree it was necessary The Checked Exceptions Issue There was a third driving force that could have made things even worse and it is the fact that Java supports two type of exceptions checked and unchecked The compiler requires that we handle or explicitly declare checked exceptions but it requires nothing for unchecked ones So this creates an interesting problem because the method signatures of most of the functional interfaces do not declare to throw any exceptions So for instance this is not possible Writer out new StringWriter Consumer String printer s out write s oops compiler error It cannot be done because the write operation throws a checked exception i e IOException but the signature of the Consumer method does not declare it throws any exception at all So the only solution to this problem would have been to create even more interfaces some declaring exceptions and some not or come up with yet another mechanism at the language level for exception transparency Again to make things less worse the expert group decided to do nothing in this case In the words of Brian Goetz in the lambda mailing list Yes you d have to provide your own exceptional SAMs But then lambda conversion would work fine with them The EG discussed additional language and library support for this problem and in the end felt that this was a bad cost benefit tradeoff Library based solutions cause a 2x explosion in SAM types exceptional vs not which interact badly with existing combinatorial explosions for primitive specialization The

    Original URL path: http://blog.informatech.cr/2014/04/04/jdk-8-interface-pollution/?replytocom=2420 (2015-08-19)
    Open archived version from archive

  • Why There Is Interface Pollution in Java 8 | Informatech CR Blog
    boxed ops sucks and having no story for reducing over ints would be terrible So we re in a tough corner and we re trying to not make it worse Trick 1 for not making it worse is we re not doing all eight primitive types We re doing int long and double all the others could be simulated by these Arguably we could get rid of int too but we don t think most Java developers are ready for that Yes there will be calls for Character and the answer is stick it in an int Each specialization is projected to 100K to the JRE footprint Trick 2 is we re using primitive streams to expose things that are best done in the primitive domain sorting reduction but not trying to duplicate everything you can do in the boxed domain For example there s no IntStream into as Aleksey points out If there were the next question s would be Where is IntCollection IntArrayList IntConcurrentSkipListMap The intention is many streams may start as reference streams and end up as primitive streams but not vice versa That s OK and that reduces the number of conversions needed e g no overload of map for int T no specialization of Function for int T etc We can see that this was a difficult decision for the expert group I think few would agree that this is cool and most of us would most likely agree it was necessary The Checked Exceptions Issue There was a third driving force that could have made things even worse and it is the fact that Java supports two type of exceptions checked and unchecked The compiler requires that we handle or explicitly declare checked exceptions but it requires nothing for unchecked ones So this creates an interesting problem because the method signatures of most of the functional interfaces do not declare to throw any exceptions So for instance this is not possible Writer out new StringWriter Consumer String printer s out write s oops compiler error It cannot be done because the write operation throws a checked exception i e IOException but the signature of the Consumer method does not declare it throws any exception at all So the only solution to this problem would have been to create even more interfaces some declaring exceptions and some not or come up with yet another mechanism at the language level for exception transparency Again to make things less worse the expert group decided to do nothing in this case In the words of Brian Goetz in the lambda mailing list Yes you d have to provide your own exceptional SAMs But then lambda conversion would work fine with them The EG discussed additional language and library support for this problem and in the end felt that this was a bad cost benefit tradeoff Library based solutions cause a 2x explosion in SAM types exceptional vs not which interact badly with existing combinatorial explosions for primitive specialization

    Original URL path: http://blog.informatech.cr/2014/04/04/jdk-8-interface-pollution/?replytocom=2508 (2015-08-19)
    Open archived version from archive

  • Why There Is Interface Pollution in Java 8 | Informatech CR Blog
    ops sucks and having no story for reducing over ints would be terrible So we re in a tough corner and we re trying to not make it worse Trick 1 for not making it worse is we re not doing all eight primitive types We re doing int long and double all the others could be simulated by these Arguably we could get rid of int too but we don t think most Java developers are ready for that Yes there will be calls for Character and the answer is stick it in an int Each specialization is projected to 100K to the JRE footprint Trick 2 is we re using primitive streams to expose things that are best done in the primitive domain sorting reduction but not trying to duplicate everything you can do in the boxed domain For example there s no IntStream into as Aleksey points out If there were the next question s would be Where is IntCollection IntArrayList IntConcurrentSkipListMap The intention is many streams may start as reference streams and end up as primitive streams but not vice versa That s OK and that reduces the number of conversions needed e g no overload of map for int T no specialization of Function for int T etc We can see that this was a difficult decision for the expert group I think few would agree that this is cool and most of us would most likely agree it was necessary The Checked Exceptions Issue There was a third driving force that could have made things even worse and it is the fact that Java supports two type of exceptions checked and unchecked The compiler requires that we handle or explicitly declare checked exceptions but it requires nothing for unchecked ones So this creates an interesting problem because the method signatures of most of the functional interfaces do not declare to throw any exceptions So for instance this is not possible Writer out new StringWriter Consumer String printer s out write s oops compiler error It cannot be done because the write operation throws a checked exception i e IOException but the signature of the Consumer method does not declare it throws any exception at all So the only solution to this problem would have been to create even more interfaces some declaring exceptions and some not or come up with yet another mechanism at the language level for exception transparency Again to make things less worse the expert group decided to do nothing in this case In the words of Brian Goetz in the lambda mailing list Yes you d have to provide your own exceptional SAMs But then lambda conversion would work fine with them The EG discussed additional language and library support for this problem and in the end felt that this was a bad cost benefit tradeoff Library based solutions cause a 2x explosion in SAM types exceptional vs not which interact badly with existing combinatorial explosions for primitive specialization The

    Original URL path: http://blog.informatech.cr/2014/04/04/jdk-8-interface-pollution/?replytocom=2535 (2015-08-19)
    Open archived version from archive