Skip to main content

Foldable Collections / Data Structures

I've never been big into functional programming, so my recent work with VAVR, which more and more seems like some kind of java port back from scala or haskell, has been very new and different for me.  Some of the things I have seen have been really exciting -- flatMap and groupBy, for example, are very simple, straight-forward, and useful tools.

And then there is folding.  Foldable data structures (here is another reference).  Geometrically, the concept of folding is straight forward, too.  Imaging turning a page in a book -- this is folding the page over.  It is a simple as that.


Functionally speaking, however, things get a lot more interesting.  If we start with a list:

A B C D

And then we fold that list in either direction, we don't visibly reflect, as folding is not quite the same as reflection.  Instead, folding results in this list:

D C B A

Of course, this is a very simple example of folding because folding can become much more complicated than that.

VAVR has an API that allows a user to foldLeft or foldRight, and then the user can provide a function to describe the result of the fold, too.  And any object that implements foldable can be folded.  A map, for example, is foldable!

Here is some code I used (including code output) to help better understand programmatic folding.

import io.vavr.Tuple2;
import io.vavr.collection.List;
import io.vavr.collection.TreeMap;

public class Vavr {

    public static void main(String... args) {
        foldingExamples();
    }

    private static void foldingExamples() {
        //Given a Foldable data structure (ex: a TreeMap), fold it!
        TreeMap<String, List<Integer>> map = TreeMap.of(
                "Even", List.of(2, 4, 6, 8, 10),
                "NAN",  List.of(),
                "Odd",  List.of(1, 3, 5, 7, 9)
        ); //TreeMap will ensure we sort these by key: Even, NAN, Odd

        //Fold left means go in sorted order.  So starting with "^" and appending afterward, it is:
        //1. ^
        //2. ^Even
        //3. ^EvenNAN
        //4. ^EvenNANOdd
        String foldLeft = map.foldLeft("^", (resultStringStaringWithCarat, mapTuple) -> resultStringStaringWithCarat + treeMapTuple2ToString(mapTuple));

        //Still sorted order because fold left.  However, we are putting the tuple on the left as we go, so it is:
        //1. !
        //2. Even!
        //3. NANEven!
        //3. OddNANEven!
        String foldLeft2 = map.foldLeft("!", (resultStringStaringWithBang, mapTuple) ->  treeMapTuple2ToString(mapTuple) + resultStringStaringWithBang);
        System.out.println(foldLeft);
        System.out.println(foldLeft2);
        /*map.foldLeft("^", new BiFunction<String, Tuple2<String, List<Integer>>, String>() {
            @Override
            public String apply(String s, Tuple2<String, List<Integer>> stringListTuple2) {
                return s + stringListTuple2.toString();
            }
        });*/  //equivalent to basic call to foldLeft above.


        //Fold right means go in REVERSE sorted order.  So starting with "^" and appending afterward, it is:
        //1. !
        //2. !Odd
        //3. !OddNAN
        //4. !OddNANEven
        String foldRight = map.foldRight("!", (mapTuple, resultStringStartingWithPound) -> resultStringStartingWithPound +  treeMapTuple2ToString(mapTuple)); //notice how the order of mapTuple and result are switched -- this is forced!

        //Still sorted in reverse order because fold right.  However, we are putting the tuple on the left as we go, so it is:
        //1. ^
        //2. Odd^
        //3. NANOdd^
        //4. EvenNANOdd^
        String foldRight2 = map.foldRight("^", (mapTuple, resultStringStartingWithSplat) ->  treeMapTuple2ToString(mapTuple) + resultStringStartingWithSplat);

        System.out.println(foldRight);
        System.out.println(foldRight2);
    }

    private static String treeMapTuple2ToString(Tuple2<String, List<Integer>> tuple2) {
        return tuple2._1+tuple2._2.mkString("(", ",", ")");
    }
}

/* Output
^Even(2,4,6,8,10)NAN()Odd(1,3,5,7,9)
Odd(1,3,5,7,9)NAN()Even(2,4,6,8,10)!
!Odd(1,3,5,7,9)NAN()Even(2,4,6,8,10)
Even(2,4,6,8,10)NAN()Odd(1,3,5,7,9)^
 */
};

Comments

Popular posts from this blog

Spring Security - Authority vs Role

I have spent a lot of time recently trying to understand the difference between Authority and Role in Spring Security.  This is a brief review of what I found. When creating a UserDetailsService or overriding configure(AuthenticationManagerBuilder auth) in the security config class that extends WebSecurityConfigurerAdapter, I basically get complete control over what I populate inside of the UserDetails that is used/returned.  This is important because the UserDetails interface really only cares about how to return one thing: Collection<? extends GrantedAuthority> getAuthorities(); A GrantedAuthority just seems like a glorified String wrapper that names some thing.  The question is... what is that thing? This is where the subtle difference between Authority and Role comes into play. I think that Role is an older thought/construct that automatically gets plugged into Authority if we just create a user with a Role.  But completely forget about the code a...

JHipster, Liquibase, MySQL, and initializing data, including booleans!

When generating a data model from JHipster JDL, we will often declare entities with Boolean fields.  I have so far abandoned H2 as a database because of liquibase issues, and both my dev and production databases will be MySQL.  This is relevant to the Boolean field desire there is a long history in software development of how to store Boolean data types in a SQL database whose standards classically do not support Boolean. In the current JHipster/Liquibase incarnation, tables in MySQL are generated for us, which is really nice.  The Boolean data types are stored as BIT  (1).  This is not a problem so far -- most developers seem to agree now that as a best practice, we should store values in databases as false = 0 and true = 1, and a BIT(1) is a great, simple way to do that. An issue arises when we try to use liquibase to set/update our database to the desired starting state.  For my project, I've chosen gradle instead of maven as a build tool, and gradle...

SQL, Booleans, JPA, and Hibernate

For a long time, SQL and Booleans have not gotten along.  Standards for SQL never really addressed the need for boolean data -- it was assumed that some other data type could easily just step in and address this need.  The result was a lot of different data models for boolean values.  Here are some examples. TRUE or FALSE T or F Y or N 1 or 0 <any value> vs NULL The internet shows the debate has gone on , even as SQL standards have changed .  Coming from a professional background with Oracle, I struggled with this across my teams because everyone had a different opinion, which led to a lot of time wasted due to debate. This said, I appreciate working with native queries in hibernate's JPA implementation against MySQL.  MySQL supports a BIT data type I recently discussed .  When we represent data in MySQL with BIT and restrict the length to just 1 (ie 1 bit), Hibernate JPA magically knows to query and return this data as a Boolean in the ...