Monad For Beginners
Monads are a fundamental concept in functional programming that represents computations that can be composed and sequenced in a specific way.
In Simple Words: A monad is like a special box or container that wraps a value. This box has some rules and operations that allow you to work with the value inside while keeping track of any side effects.
Imagine you're ordering a package online, and try to relate Monad with the following:
The Cats library provides a powerful and consistent implementation of the Monad, making it easier to work with monadic types in Scala.
Note: A monadic type is any type that, has an instance of the Monad type class from the Cats library. Some common examples of monadic types in Scala include: Option, Either, List, Future e.t.c
The Monad type class, which has three main operations:
1. pure (for creating a new monadic value:
Option.pure(42) creates a Some(42) value.
2. flatMap (for composing and sequencing monadic computations):
Some(42).flatMap(x => Some(x * 2)) results in Some(84)
3. tailRecM (for stack-safe monadic recursion).
It takes an initial value and a function that returns either a monadic value wrapped in
领英推荐
1. Left (indicating that recursion should continue)
2. Right (indicating that recursion should terminate)
Whenever you need an ETW pattern in your code, you probably need a Monad:
1. Extract: Extract the value from the context.
2. Transform: Perform some operations or transformations on the extracted value.
3. Wrap: Wrap the transformed value back into the context.
Properties of Monad: Monad has a pure and flatMap function but these two need to work in a certain way.
1. Left identity: (Monad(x).flatMap(f) === f(x))
2. Right identity: -> USELESS -> Monad(v).flatMap(x => Monad(x)) === Monad(v)
3. Associativity: -> Monad(v).flatMap(f).flatMap(g) == Monad(v).flatMap(x => f(x).flatMap(g)) It does not matter in which order you apply the functions as long as function f applied on every element before the function g applied on every element.