Shubham Posted on May 30 • Originally published at shubhkumar.in Demystifying the Trinity: Functor, Applicative, and Monad in PureScript # functional When diving into pure functional programming, you are immediately confronted with three abstract terms that sound more like advanced physics concepts than software engineering patterns: Functors , Applicatives , and Monads . For a long time, the internet has tried to explain them using metaphors like "burrito boxes" or "spaceships." Based on my experience and everyday usage, it is much better to look at them for what they truly are: elegant design patterns for managing data flow, context, and computation with mathematical certainty. Let’s break down this holy trinity of functional programming using clean, practical PureScript examples. The Core Concept: Values in a Context Before writing code, let’s establish a visual mental model. In PureScript, we often deal with values wrapped inside a context (or container). Maybe a represents a value of type a that might be missing (handling null safely). Either e a represents a computation that might fail with an error of type e . Effect a represents a synchronous side-effect (like logging to the console or interacting with the DOM). The Trinity—Functor, Applicative, and Monad—are simply a progressive set of tools that allow us to manipulate these wrapped values without manually unwrapping and re-wrapping them at every single step. 1. Functor: Mapping over a Context The simplest abstraction is the Functor . A Functor allows you to apply a normal, pure function to a value that is sitting inside a context. The Definition To be a Functor, a type constructor f must implement the map function (often written as the infix operator <$> ). Code snippet class Functor f where map :: forall a b . ( a -> b ) -> f a -> f b Enter fullscreen mode Exit fullscreen mode Usage Example Imagine you are processing a transaction payload where the payment amount might be missing ( May
Back to Home

Demystifying the Trinity: Functor, Applicative, and Monad in PureScript
B
Blizine Admin
·2 min read·0 views
📰Dev.to — dev.to
B
Blizine Admin
View Profile Staff Writer