Pythonic Encoding Through Functional Style: Iterable Monad

Python is a powerful language that is ideal for scripting and rapid application development. Python supports functional-style programming, as functions are treated as first-order values. It allows writing more concise and expressive Python code, or more "Pythonic code." In this article, we introduce Iterable Monad in Python. Through the implementation of making Iterable Python collections monadic, we demonstrate the power of functional features in Python and the elegance that monad can bring to Python encoding. We also prove that the Iterable Monad satisfies the Monad law. Given that iterables are heavily used and monadic encoding is not supported in native Python, this mechanism can obtain significant improvement in Python programming.

Monad

In functional programming, a monad is a structure that combines program fragments (functions) and wraps their return values in a type with additional computation. In addition to defining a wrapping monadic type, monads define two operators: one to wrap a value in the monad type and another to compose together functions that output values of the monad type (these are known as monadic functions).

Validation With Tagless Final

In one of our previous articles, Validation for Free in Scala, we discussed a validation framework by lifting validators to monad “for free”. In this article, we will discuss a validation framework with Tagless Final. Through examples, we demonstrate how the proposed validation framework can improve the quality of encoding.

Validation

Validation falls into two categories: Fail Fast and Error Accumulation. In Fail Fast scenario, validators return monadic validation results; a for-comprehension can be used to complete the validation. The following code returns the first error it encounters without executing the rest of the validation:

Predicate Composition in Scala

Function composition is a term used to define a process of a function mixing with other functions. During the composition one function holds the reference to another function. 

Scala language has two native ways to compose functions:

Better Encoding With Monoids in Scala

Monoid has its root in abstract algebra. It is a semigroup with an identity; in other words, it has an associative binary operation and an identity element. In Scala, we can define it as follows:

Scala
 




xxxxxxxxxx
1


 
1
trait Monoid[A] {
2
  def id: A
3
  def op(a1: A, a2: A): A
4
}
5