Showing posts with label Monad. Show all posts
Showing posts with label Monad. Show all posts

Tuesday, 9 October 2018

Revise Kotlin 1.3 from Scala experience perspective



Thanks to Google Kotlin is producing more and more informational noise. It's interesting to make an assessment spending less than hour to find out where the language is now and comparing it with Scala's experience. I'm not going to review feature by feature - but will try to get impression in offbeat way - choosing the most interesting/unaccustomed feature in 1.3 and trying to assist language's way of development comparing with pseudocode in Scala.

Let's look into upcoming release 1.3.  Kotlin Contracts is looking interesting and probably the biggest KEEP change in the release. Looks like something language specific (haven't seen it in other languages) that improves language itself and may bring some light to the Kotlin's "way of thinking".

Let's run through the proposal to and try to understand what it improves and why.
The first example/motivator is:

Well, it's extremely hard to get why should we write the code like that. There is some background on how Kotlin implements calls of closure blocks (there was similar SIP-21 - SPORES in Scala, but  didn't gain popularity), skipping that - for particular example it feels more natural to use functional approach:
I feel like Kotlin tries to make this code valid:
Kotlin doesn't require us to define val and initialise it immediately, but I don't feel it's nicer and better readable. There is an extra price - method run has a

contract {
    callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}

The next one example is:


As for developer with Scala experience it's hard to understand the problem's domain - but keeping in mind that Kotlin is providing safety for null references problems - there is some sugar for the cases when safety is already checked against the reference and it follows some rules (not null in the example). Looks fine and it's imperative alternative to Monad's approach (will talk about this later). But if it were the production code I would prefer to avoid throwing the exceptions and separate execution of the side effect (println). Same as in previous example there is small complexity via introducing:

Next one example is:

Looks like pattern matching customisation - I had intuitive feeling that it's the way to handle the Union Types but it isn't. As for the guy without commercial experience with Kotlin - all the examples are too artificial to evaluate the syntax sugar coming with contracts. For example the last example looks much better if the pattern matching is applied

Still it could be covered via Option/Either Monads or if there are more possibilities - better to look into Coproduct solutions. All the other examples are following the same paradigm if it were the real product's source code I would prefer to use best practices from Lambda and Categories patterns. Especially that handling nullable (empty) values has the same importance as validation/parallel validation or applying side effects in a good way. There is probably implicit advantage of Kotlin's sugar - allocate less memory and it would be great - but as we will see as soon as we require some feature like ?.let the extra memory allocation is inevitable.



Summary
Overall impression is quite positive. Kotlin is inventing some alternative to Lambda + Category solutions for specific problems.  Nullable reference is really weird solution that appears to be the centrum of all the problems/improvements in the given examples. Fortunately I haven't met NullpointerException quite some time in Scala - but should admit that one of the most used Monads is Option. Another  positive impression is: it's possible to write code in Kotlin from the first minute.

Bonus: Weird nullable types
The Null Safety is looking too noisy but we will play around this area comparing with Scala. Let's imagine we need to read (from property file)  three optional variables and build optional url object based on those. Pretty easy approach checkin all the 3 variables against null and creating the object, Scala allows to write something like:

Or not using the for-comprehensions but Applicative's mapN:

Let's find out can we do something similar. Kotlin doesn't support for comprehensions out of the box. Starting with brute-force solution for 2 params:

Let's use ?.let method:

Looks fine for the case with two params - but wouldn't for more. Let's try to play with Monad's flatMap and unit:

Looks like Maybe/Option Monad:

Looks better - but wouldn't for three and more params. Can we use mapN?

And the usage is:

Works for Pair type only - for more params we need a custom implementation per type, but idea is clean - Kotlin can support functional solutions with Categories. I'm pretty sure there should  be dozen good Functional Programming libraries in Kotlin like Arrow


Wednesday, 27 June 2012

Scala: Applicative with scalaz example


I’ve talked on Functor previously, will repeat myself that construction is very useful in the Scala's world. We covered Comonad as well, it is extending Functor and adds functionality for the extraction value or the wrapping of already wrapped.
This post is related to Applicative. Applicative is coupled with Functor, even has an alternative name: Applicative Functor. At first let look into class hierarchy for Applicative in scalaz library:

Friday, 22 June 2012

Scala: Comonad (scalaz example)

When we were talking on Functor - we described it as a construction that can apply function to incapsulated value and return a new instance of the same container with function result value inside. Quite useful construction, it is even implemented by scala library's classes: like Option, List and others. To be honest Scala's standart library classes mixing Functor and Monad, but lets do not concentrate on this now.

Monday, 18 June 2012

Scala: Functor (scalaz example)

Function programming got a proven handy in structuring the code, from where we have common structures/classes presented in many functional languages. All this magic comes from mathematic and in the most parts aren't so easy to get for regular developers with imperative experience. I've been googling a lot to get essence and still getting a lot of "news". Looks like the best way to review FP types in Scala is using examples from scalaz library. Let try to start from the Functor.

Functor 

Functor is a something you can map over, it has only one method map (called fmap scalaz). Class diagram is very simple:

scala.Either

Even newcomers to Scala know about Option class. We are starting from it as from solution to Nullpointer errors, later we finding it as a very useful Monad implementation. It is dual natured - one is Monadic Container - value is inside - and second is Monadic Zero with no value. Actually sometimes it is useful to have some value even in Zero container. For example non breaking error handing. Errors are important and even can be accumulated into the List.

Tuesday, 5 June 2012

Scala: Lenses 2

Looks like Lenses topic should not be closed without discussing compose method. This method decreases the count of lenses we have to produce. We called it M * N size issue in previous session.
This time it's hard to not jump into function programming math mess, but we will try.

Monday, 4 June 2012

Scala: Lenses 1

If U ever had a task on updating nested immutable structures - U might found it as non-clean code task, especially it's hard to guard solution from colleges :p

There is nice fitting solution coming from function programming theory, that shines in Scala as well.

Intro 

"Lenses are bidirectional transformations between pairs of connected structures. Asymmetric lenses —where one of those two connected structures is taken to be primary —have been extensively studied. Lenses were first proposed to solve the view- update problem of tree-like data structures by Foster et. al and have also been applied to the construction of a relational database query language."

Tony Morris 

Saturday, 2 June 2012

Rework: Monads in Scala - 4


Monadic Zero


Do U remember second state of Response - Marvelous?
If we represent Marvelous via Answer with null inside - it's not enough, than we can translate Marvelous into Answer - ignoring it's Essentials - that is error:

    val box = new Answer[Any](null)
    val func:(Any)=>Int = (in) => 5
    val res = box map func // Produces Answer(5)

Expected behavior, that is described via The First Zero Law: Identity

     mzero map/flatMap f = mzero

Friday, 1 June 2012

Rework: Monads in Scala - 3

Today we will speak more about flatMap, Monadic Zero and other steps.

Let's start from the Business. Should I use Monads?

Its good to start with Scala's Option class, but while we are still don't understand the theory, lets reinvent the wheel to drive into details. Additionally we will try to follow Function and Object Oriented best practices and won't do optimizations etc, while we are not implementing library.

Tuesday, 29 May 2012

Rework: Monads in Scala - 2

During previous session we captured in mind 3 transformations/conversions. While moving out from mathematical pressure we just got 3 simple formulas:


a) (A => B ) => (M[A] => M[B]) // Monad
b) (A => M[B] ) => (M[A] => M[B]) //Functor
c) (M [A => B]) => (M[A] => M[B]) //Applicative


As an implementation we've chosen functional way:

a) Func(A => B) : M[A] => M[B] // Monad
b) Func(A => Box[B]) : Box[A] => Box[B] //Functor
c) Func(Box[A => B]) : Box[A] => Box[B] //Applicative



Monday, 28 May 2012

Rework: Monads in Scala - 1


I have to spend more time than other (smart guys) trying to get simple topics. As a profit - getting clean description for myself - using simple (clean for non math geek) vision. I've read hundred of articles/examples/... + done few presentations on the same topic. Just want to finalize it and forget:)

As a conclusion generalization of my previous self-study experience I would kindly ask James Iry:
Usually articles that start with words like "monad" and "functor" quickly devolve into soup of Greek letters. That's because both are abstract concepts in a branch of mathematics called category theory and explaining them completely is a mathematical exercise.
JAMES IRY


But there must be possibility to avoid complexity, to allow understanding the topic while reading in the bus or 3 minutes before falling asleep. U r welcome to the world of Monads in Scala.