Monads Everywhere - Simply get the advantage of Generics
Hi,
Here I’m going to write short notes for self-reference on how monads change the way we function the things.
(Promises will produces controllable futures? Need to write one other blog on this)
Well lets start with a general usecase basically.
I want to model thread-safe primitives that typically works with any kind of type — for instance; If I model Integer, within the scope of my application If I use particular typeclass I will/should always get the thread-safe values. If I model a String, within the scope of my application if I use the same typeclass I would end-up getting threadsafe value for that string. So, under careful modelling, we may never ended up with boiler plate. For each primitive type or custom type (like User,Student,…) I don’t ever need to write thread-safe conversions, transformations, wrappers individually.
Thread-safe Interger:
var greeting = "hello world"
// I wnated to make this greeting thread safe as
// .. I dont want to get it manipulated by more than one thread
// .. in a single time
def makeMeThreadSafe(str: String) = Synchronized {str}
// so I can use the above stuff to get threadsafe but what If
// I even want to work with Integer
// Or I wanted to transform (I want to uppercase it) the threadsafe string?
// we may need to write another call to the same method for transforming string
// here comes type classes
class ThreadSafe[T](value: T) {
def get[T] = synchronized {value}
def transformIt[S](transformer: T => ThreadSafe[S]) = synchronized {
transformer(value)
}
}
// here lets have the instance
def getThreadSafeString(str: String): ThreadSafe[String] = new ThreadSafe(str)
//Extraction part
val tSafeStr = getThreadSafeString("hello world").get
//Transormation part
val transformedThreadSafeStr = tSafeStr.toUpperCase
// Wrap
val wrappedTrans = getThreadSafeString(transformedThreadSafeStr)
// If I wanted to do the same for integer, or boolean, double I need to write
// if no typeclasses, right?
// So lets model for Ints also