Code Monkey home page Code Monkey logo

lemonoid's Introduction

LeMonoid

A while ago, I attended a functional programming workshop by @LukaJCB. One part of the workshop was to use monad transformers in Scala to to perform all kinds of aggregations on lists or maps.

One example that really impressed me was a foldMap operation on a list of strings, that could extract number of words, the number of characters and the number of occurrences of each word all in one (once you've gotten used to it) simple and elegant operation.

Since I am a Java guy and the workshop was in Scala, I wanted to do something similar in Java. So here it is: number of words, the number of characters and the number of occurrences of each word in a short Java snippet using monad transformers!

List<String> words = Arrays.asList("abcde", "xyz", "lala", "xyz");

Tuple3Monoid<Integer, Integer, Map<String, Integer>> tuple3Monoid = 
Tuple3Monoid.of(sumInt(), maxInt(), map(sumInt()));

Tuple3<Integer, Integer, Map<String, Integer>> result =
foldMap(words, tuple3Monoid, word -> Tuples.of(1, word.length(), mapOf(word, 1)));

System.out.println(result._1); // 4
System.out.println(result._2); // 5
System.out.println(result._3); // {abcde=1, xyz=2, lala=1}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.