Skip to content

Instantly share code, notes, and snippets.

@aappddeevv
aappddeevv / misc-scala-1
Created September 11, 2013 22:42
scala monoids and for comprehensions examples
// Define functions that return an Option
def f1(x: Int): Option[Int] = Some(x*30)
def f2(x: Int): Option[Int] = Some(x+3)
def f3(x: Int): Option[Int] = Some(x*2)
// Sequence the computation, it will be successful
var answer = for {
x <- f1(30)
y <- f2(x)
@aappddeevv
aappddeevv / misc-scala-state-monad
Last active December 22, 2015 22:59
There's no free lunch when using the State monad
// Requires scalaz to be on the classpath
import scalaz._
import scalaz.State._
// The State monad was hard for me to understand because it
// seems as if you never actually store a value in the state and
// manipulate it inside of a method like you would in java.
// There are really two types of methods in the scalaz library
import scalaz._
import scalaz.State._
case class Session(version: Int = 0)
// Create a new output string and increment session version.
def func1(arg: String) = State((x: Session) => (x.copy(version = x.version + 1), arg + "-" + x.version))
val composedFunction1: State[Session, String] = for {
// Because we gave this val an explicit type, init does not need the type specification

As a follow up to my last post about no free lunch I wanted to show more state monad usage and recognize that you can change function return types in the middle of a for-comprehension. This allows each function to return different types of values from the computation along the way.

In the code below, you compose a function by using the for-comprehension. The yield part of the for-comprehension is a State object. When that state object is called, it returns a tuple of (state, value). You can use ._1 or ._2 to obtain the value of interest.

The last composed function shows an example of changing the state type (instead of changing the returned value type mentioned above) in the middle of the for-comprehension using scalaz IndexedState's iPut and iModify. This allows you to change the type of state as you go to adapt to different function's API needs.

import scalaz._
import scalaz.State._

##The Reader and State Monad The Reader and State monads are very similar in that they both wrap a function.

As we have seen in past posts, the State monad allows you to define a wrapper around a function that takes a current state and produces a tuple of the new state and a value. Returning a new state allows you to modify the state object for the next function that gets called. The state object used is immutable so when you return a new state object it is typically a copy of the incoming state with some type of adjustment e.g. increment a counter.

The Reader monad also wraps a function. However, it is designed to be a read-only mechanism in that the return value of the function it wraps is just a value. The reader uses a "context" concept instead of a "state" concept but they are essentially the same thing--an object of some type. However, since you only return a value from the wrapped reader function, the Reader communicates the concept that the context is immutable and not be changed. That's why its ter

As I was working through some content on the Reader monoid, I realized I wanted to lift a function to use it. If you read the Scala In Depth book, which as a really great book, you know that lifting a function to be monoidal could be useful.

The classic example is to lift the function so that the arguments as well as the return value are all Option types. Then, if any of the parameters to the new lifted function are None, the function returns None. Otherwise it would return Some.

The key thought is that you do not have to write your own, scalaz already supports lift.

It turns out that scalaz has support for lifting functions using your monoid of choice. Below is a transcript using scala REPL with a -cp set to the scalaz core library.

The easiest approach is to use optionInstance.lift(func2) where func2 takes 2 arguments.

@aappddeevv
aappddeevv / cake-pattern.md
Last active August 17, 2017 03:54
Discussing the different versions of the cake pattern and its relation to dependency injection.

##Cake Pattern and Why Cake Patterns Sometimes Look Different The cake pattern is typically described as a way to use small layers of functionality to create a larger, more complex program. This area of application design is typically designed with application scalability not in the pure performance sense, but in the sense of scaling the application up to more complex functionality and maintainability over time.

There have been many papers and blogs on this aspect, but a few especially helpful blogs include:

@aappddeevv
aappddeevv / scalaz Validation.md
Last active December 31, 2015 10:29
scala code showing scalaz's Validation inside a for-comprehension with complex dependencies

###The Problem I have an app that uses neo4j as the underlying database. Similar to all database applications, I also have a data access layer that helps abstract out the use of neo4j.

The data access layer takes in string parameters, mostly, finds the neo4j nodes or relationships then manipulates the those objects to create a new object.

In this access layer, I must gather several different objects together to process. For example, the start node, the end node, another node that holds my dynamic type system, and various other objects.

When assembling these nodes, I typically find the pattern to go something like this:

  • Check the input parameters

This is a URL handler I needed for my javafx application in order to allow WebView (WebEngine) find my classpath resources and use relative resources for images, scripts, etc. If you only use WebEngine.loadContent, you cannot use relative resources and your web pages become much less flexible when changing later.

/**
 * Handler factory different types of URL handling.
 */
class ConfigurableStreamHandlerFactory extends URLStreamHandlerFactory {

  private var handlers = Map[String, URLStreamHandler]()

#scala, Map[String, Any] and scalaz Validation

#The Problem

I seem to encounter alot of Map[String, Any] in my programming probably because I am using graph databases alot that store key-value pairs in the nodes and relationships (think neo4j).

Because of this, I encounter alot of map-like processing. Being able to fluently handle these map structures fluently during data import processing or just general processing is very important.

The classic problem I ran into a lot was how to use the Map object more fluently and easily in my data import or query-like processing. I usually have a UI with my application and the UI needs to be able almost any data structure, so it is usually setup to be fairly robust to not knowing the exact types of values in the map or deriving those from the data itself. However, for data import processing as well as querying, I typically do need to know and count on a few well known types for values that are guaranteed to be in my objects like a name (a String) or some other proper