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:

Monday 25 June 2012

Scala: constant in pattern matching or always do a Unit testing!

Every Scala coder should remember the difference between Constant and Variable patterns in
pattern matching. Short refresh from this topic: if pattern starts from low case letter: it is counted as a variable. We can still use a lowercase name for a pattern constant, using one of two tricks:
1). If the constant is a field of any object, we can prefix it with a qualifier. For example, name is a variable pattern, but this.name or objInstance.name

2) Second workaround is enclosing the variable name with back ticks. For instance, `name` would again be interpreted as a constant, not as a variable.

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.

Thursday 21 June 2012

Scala: Polymorphism rework

As dude came from C# and Java to Function Programming I'm thinking on polymorphism in therms of OOP only. I was believing in: Polymorphism is coming only as a monolithic bundle based on Inheritance. But look into this:
This is the method that is accepting ... type T, which should be any type, and this is good example of ... Polymorphism. Method second is getting a list of T and should return extracted T (we can try to guess that the best fit logic here is returning second element). Doesn't matter which T is inside - method declared to work with All types: Int, String, List[List[String]], AnyRef, whatever. This part for OOP world dudes is unnatural, then let's move to a new: Ad-hoc Polymorphism.

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.

When I told ...

This post is free style translation from russian blogger. But according to my feelings it is applicable to the most from European market. Bellow I should be You as well, I hope so)



Thursday 14 June 2012

Scala: undocumented

There are interesting undocumented classes which are helping to restrict applicability for the methods coming with Generics Types. They are useful to restrain the type parameter in therms of single method. Lets review them in details and compare with Type Parameterization.

Monday 11 June 2012

Scala: Monoid

One of the simplest constructions in function programming is Monoid. Thanks to simple nature we are using it even without knowledge how it is named. Despite on this it's very interesting to review this in details. By the way this magic comes from Category Theory - which should be known by sophisticated developers;)

Comes from Semigroup:

In Function Programming Semigroup is set (presented by type T) and binary associative operation. Fast drop to both binary and associative:

Binary

Binary operation is any operation that requires two operands, for example
    2 * 2
    5 / 10
    list1 ::: list2

Associative

Formally, a binary operation on a set S is called associative if it satisfies the associative law:
(x * y) * z=x * (y * z)\qquad\mbox{for all }x,y,z\in S.
Still not easy to refresh basic algebra, here are examples for associative operations:
     (1 + 3) + 9 = 1 + (3 + 9)
     (2 * 5) * 10 = 2 * (5 * 10)
And non associative operations:
     (5 - 1) - 1 ≠ 5 - (1 - 1)
     (6 / 3) / 3 ≠ 6 / (3 / 3)

As we can feel associative is simple property, but if your are implementing new business types, you should determine on design phase is your operation in type is associative or not.

Groovy under Eclipse

Spent some time during configuration Java projects to be tested via Groovy (just adding Groovy nature to Eclipse projects). Sure everything should be done in Maven and Eclipse must get Groovy nature via plugins.
My problem like in the most cases was reading fast (throw 3 lines) documentation, where each line is very important. After installing Groovy for eclipse and groovy m2e configuration for Eclipse eclipse started to work well and sync faceds from pom.xml plugin.

Sunday 10 June 2012

Validation: Non-breaking Error Handling

Non-breaking error handling was covered in few nice articles and presentations. Was reading one from Tony Morris. Solution for validation is looking little bit overcomplicated for me. 

Thursday 7 June 2012

Scala: return from closures


"Funny" code


Functions are first class citizens in Scala. JVM, that doesn't know anything on Functions. All the magic is coming from the Scala Library and compiler. Sometimes we should know about "workarounds" were applied to support rich language features.

Wednesday 6 June 2012

Clean code: exceptions for Scala?

At the junction of OOP and FP Scala contributors are doing great things. While reading librarie's code I finding a lot of places where author's ignoring gode coding style for the name of performance or interface presentation. Can understand this, they are doing library.
Today found some interesting example called "my mother would kill me for this":

Clean Code again

Sometimes I have a time for code review... I run these sessions with my team.
It was popular trend to read a hundred books on legacy code or clean code and other Zen of programming. I did a lot as well. I'm lazy programmer, even more than other guys, but I can't stop refactoring if something smells.

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 

Sunday 3 June 2012

Scala: Type Classes

Type classes were originally developed in Haskell as a disciplined alternative to ad-hoc polymorphism. Type classes have been shown to provide a type-safe solution to important challenges in software engineering and programming languages such as, for example, retroactive extension of programs. They are also recognized as a good mechanism for concept-based generic programming and, more recently, have evolved into a mechanism for type-level computation. Rephrasing in simple words: if U got conception of Context Bound in Scala U almost get type classes implementation in Scala.

Scala: View Bound and Context Bounds

View Bound


A view bound is Scala's mechanism to enable the use of some type A as if it were some type T (Real type). The typical syntax is this:

    def func[A <% T](a: A) = a.methodFromT

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.