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".
  • funny jokes | Informatech CR Blog
    s so fat she get an ArrayIndexOutOfBoundException Yo mama s so po she does garbage collection for a living Yo mama s so ugly her java lang reflect took down the mirror site A bonus one Your mama s so fat that not even Dijkstra is able to find a shortest path around her When your hammer is C everything begins to look like a thumb A Cobol programmer made so much money doing Y2K remediation that he was able to have himself cryogenically frozen when he died One day in the future he was unexpectedly resurrected When he asked why he was unfrozen he was told It s the year 9999 and you know Cobol A geologist and a Java programmer are sitting next to each other on a long flight from LA to NY The geologist leans over to the programmer and asks if he would like to play a fun game The programmer just wants to take a nap so he politely declines and rolls over to the window to catch a few winks The geologist persists and explains that the game is real easy and a lotta fun He explains I ask you a question and if you don t know the answer you pay me 5 Then you ask me a question and if I don t know the answer I ll pay you 5 Again the programmer politely declines and tries to get to sleep The geologist now somewhat agitated says OK if you don t know the answer you pay me 5 and if I don t know the answer I ll pay you 50 This catches the programmer s attention and he sees no end to this torment unless he plays so he agrees to the game The geologist asks the first question What s the distance from the Earth to the moon The programmer doesn t say a word but reaches into his wallet pulls out a five dollar bill and hands it to the geologist Now it s the programmer s turn He asks the Geologist What goes up a hill with three legs and comes down on four The geologist looks up at him with a puzzled look He takes out his laptop computer and searches all of his references He taps into the Airphone with his modem and searches the net and the Library of Congress Frustrated he sends e mail to his co workers all to no avail After about an hour he wakes the programmer and hands him 50 The programmer politely takes the 50 and turns away to try to get back to sleep The Geologist is more than a little miffed shakes the programmer and asks Well so what s the answer Without a word the programmer reaches into his wallet hands the geologist 5 and turns away to get back to sleep Once upon a time there was a shepherd looking after his sheep on the side of a deserted road Suddenly a

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


  • jokes | Informatech CR Blog
    so fat she get an ArrayIndexOutOfBoundException Yo mama s so po she does garbage collection for a living Yo mama s so ugly her java lang reflect took down the mirror site A bonus one Your mama s so fat that not even Dijkstra is able to find a shortest path around her When your hammer is C everything begins to look like a thumb A Cobol programmer made so much money doing Y2K remediation that he was able to have himself cryogenically frozen when he died One day in the future he was unexpectedly resurrected When he asked why he was unfrozen he was told It s the year 9999 and you know Cobol A geologist and a Java programmer are sitting next to each other on a long flight from LA to NY The geologist leans over to the programmer and asks if he would like to play a fun game The programmer just wants to take a nap so he politely declines and rolls over to the window to catch a few winks The geologist persists and explains that the game is real easy and a lotta fun He explains I ask you a question and if you don t know the answer you pay me 5 Then you ask me a question and if I don t know the answer I ll pay you 5 Again the programmer politely declines and tries to get to sleep The geologist now somewhat agitated says OK if you don t know the answer you pay me 5 and if I don t know the answer I ll pay you 50 This catches the programmer s attention and he sees no end to this torment unless he plays so he agrees to the game The geologist asks the first question What s the distance from the Earth to the moon The programmer doesn t say a word but reaches into his wallet pulls out a five dollar bill and hands it to the geologist Now it s the programmer s turn He asks the Geologist What goes up a hill with three legs and comes down on four The geologist looks up at him with a puzzled look He takes out his laptop computer and searches all of his references He taps into the Airphone with his modem and searches the net and the Library of Congress Frustrated he sends e mail to his co workers all to no avail After about an hour he wakes the programmer and hands him 50 The programmer politely takes the 50 and turns away to try to get back to sleep The Geologist is more than a little miffed shakes the programmer and asks Well so what s the answer Without a word the programmer reaches into his wallet hands the geologist 5 and turns away to get back to sleep Once upon a time there was a shepherd looking after his sheep on the side of a deserted road Suddenly a brand

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

  • Java Lambda Expressions Basics | Informatech CR Blog
    code block or void if nothing is returned What is a Java Functional Interface In Java a functional interface is basically an interface with a single abstract method This kind of interfaces are also known as SAM Single Abstract Method types Before Java 8 there were already several interfaces compatible with this idea public interface Comparator T int compare T o1 T o2 public interface Callable V V call throws Exception public interface ActionListener extends EventListener public void actionPerformed ActionEvent e public interface Runnable public void run Java 8 Examples Many new functional interfaces are being defined in the Java 8 among the most popular those found in the new java util function package The following are some examples of new functional interfaces in Java public interface Predicate T boolean test T t public interface Function T R R apply T t public interface BinaryOperator T T apply T left T right public interface Consumer T void accept T t public interface Supplier T T get Starting with Java 8 these functional interfaces can be implemented by means of lambda expressions and method references What is the Type of Lambda Expression In languages that support first class functions the type of the lambda expression would be a function but in Java the lambda expressions are represented as objects and so they must be bound to a particular object type known as a functional interface This is called the target type Since a functional interface can only have a single abstract method the types of the lambda expression parameters must correspond to the parameters in that method and the type of the lambda body must correspond to the return type of this method Additionally any exceptions thrown in the lambda body must be allowed by the throws clause of this method in the functional interface The following are examples of lambda expressions bound to a target type Predicate Integer isOdd n n 2 0 BinaryOperator Integer sum x y x y Callable Integer callMe 42 Block String printer String s System out println s Runnable runner System out println Hello World See the Java documentation for the new java util function package to get more details on these functional interfaces and their corresponding abstract methods Notice that the type of the lambda expression is determined by the compiler from the context based on the target type This implies that two apparently equal lambda expressions may have different types simply because they are bound to a different target type as demonstrated in the following code Callable String callMe Hello PrivilegedAction String action Hello Example Supposing we had a functional interface named Predicate declared as follows public interface Predicate T boolean test T input Now imagine that we had a method capable of filtering the contents of a Collection based on a provided Predicate as follows public static T Collection T filter Predicate T predicate Collection T items Collection T result new ArrayList T for T item items if predicate test item result

    Original URL path: http://blog.informatech.cr/2013/03/22/java-lambda-expressions-basics/ (2015-08-19)
    Open archived version from archive

  • Getting Rid of Boilerplate Code with Java Lambda Expressions | Informatech CR Blog
    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

    Original URL path: http://blog.informatech.cr/2013/03/12/getting-rid-of-boilerplate-code-with-java-lambda-expressions/ (2015-08-19)
    Open archived version from archive

  • Java Lambda Expressions vs Method References | Informatech CR Blog
    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

    Original URL path: http://blog.informatech.cr/2013/03/15/java-lambda-expressions-vs-method-references/ (2015-08-19)
    Open archived version from archive

  • jdk | Informatech CR Blog
    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 contains a discrete amount of elements from the infinite stream We could define the number of elements that we want based on a predicate And this is quite appropriate because one of the new functional interfaces in Java 8 is precisely Predicate Even better now that Java has extension methods and now that interfaces support the definition of static methods we could define the following methods in the stream interface itself public interface Stream T public default Stream T takeWhile Predicate super T return takeWhile this predicate public static T Stream T takeWhile Stream extends T source Predicate super T predicate if source isEmpty predicate test source head return new Empty creates new cons cell and a closure for the rest return new Cons source head takeWhile source tail predicate Now I have to admit that I defined these methods here because I thought it would be a good way to demonstrate these new features in Java 8 but I have not pondered the implications of my design That been said I also believe that having defined these methods directly in the interface avoids the need to define an implementation for them in the Empty and Cons classes themselves since they can consume this default implementation by inheritance Notice how the method takeWhile creates a new stream but as you can see in the moment that one of the stream nodes does not satisfy the predicate we return an empty stream node so this indicates the end of the stream and the end of the evaluation of the infinite stream By this we can generate a finite stream out of our infinite stream using a predicate to restrict the number of items we want to get out of the infinite stream We could do something like the following to obtain a new stream containing only the first 10 natural numbers Stream Integer tenNats from 0 takeWhile n n 10 Consuming the Stream In the next step what we would like to do is to provide a way to print the contents of a finite stream or do any other kind of tasks with the values in it i e serialize them send them over network etc Once again using Java 8 extension methods we can add a forEach method to the stream interface so that we can provide a Consumer to do something with the values within the stream The Consumer functional interface is also one of those new interfaces in the JDK 8 public interface Stream T public default void forEach Consumer super T consumer forEach this consumer public static T void

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

  • programming | Informatech CR Blog | Page 2
    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

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

  • Overview Of The Task Parallel Library (TPL) | Informatech CR Blog
    of the first code example Tasks Continuations OK we now have knowledge of how all this thing about tasks goes But let s assume you don t want to block the calling thread execution until the task finishes but have it call another task after it finishes that will do something with the result later on For such scenario we have task continuations The Task Parallel Library allows us to chain tasks together so they are executed one after another Even better code to achieve this is completely fluent and verbose Console WriteLine Loading user Create tasks to be executed in fluent manner Task Factory StartNew User DataContext Users FindByName luis aguilar First task ContinueWith previousTask This will execute after the first task finishes First task s result is passed as the first argument of this lambda expression var user previousTask Result Console WriteLine User loaded Name is user Name Tasks will start running asynchronously You can do more things here As verbose as it gets you can read the previous code like Start new task to find a user by name and continue by printing the user name on console Is important to notice that the first parameter of the ContinueWith method is the previously executed task which allows us to access its return value through its Result property Async And Await The Task Parallel Library means so much for the Microsoft NET Framework that new keywords were added to all its languages specifications to deal with asynchronous tasks These new keywords are async and await The async keyword is a method modifier that specifies that it is to be run in parallel with the caller method Then we have the await keyword which tells the runtime to wait for a task result before assigning it to a local variable in the case of tasks which return values or simply wait for the task to finish in the case of those with no return value Here is how it works 1 Awaiting For Tasks With Result async void LoadAndPrintUserNameAsync Create start and wait for the task to finish then assign the result to a local variable var user await Task Factory StartNew User DataContext Users FindByName luis aguilar At this point we can use the loaded user Console WriteLine User loaded Name is user Name 2 Awaiting For Task With No Result async void PrintRandomMessage Create start and wait for the task to finish await Task Factory StartNew Console WriteLine Not doing anything really 3 Usage void RunTasks Load user and print its name LoadAndPrintUserNameAsync Do something else PrintRandomMessage As you can see asynchronous methods are now marked with a neat async modifier As I mentioned before that means they are going to run asynchronously better said in a separate thread Is important to clarify that asynchronous methods can contain multiple child tasks inside them which are going to run in any order but by marking the method as asynchronous means that when it is called in traditional fashion

    Original URL path: http://blog.informatech.cr/2013/04/05/overview-of-the-task-parallel-library/?shared=email&msg=fail (2015-08-19)
    Open archived version from archive