📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Monads
  • Implementing the just monad
  • The maybe monad
  • More on Monads
  1. Javascript
  2. Functional Light Javascript

Data Structure Operations

We're now going to take map, filter, and reduce and think about them at the more general data structure level (not just arrays).

Monads

Monads are functional-friendly data structures.

As data structures, monads hold one discrete value. The point of doing this is to wrap behaviour around that value, making that value easier to inter-operate with other monads.

Specifically, monads turn values into functors: values that you can transform (map), include (filter), and combine (reduce).

Implementing the just monad

High-level, a monad in implementation is just a function that is passed a value and returns these methods (and more): map, chain, and ap. These methods can then be used to access and work with the closed-over value passed in.

function Just(val) {
  return { map, chain, ap };

  // - Applies function to value
  // - Returns another monad
  // - Just like how mapping over an array,
  // returns an array, mapping over a monad returns a monad
  function map(fn) {
    return Just(fn(val));
  }

  // - Sometimes called bind or flatMap
  // - Flattens a monad
  // - For simplicity, we return mapped value without wrapping monad
  function chain(fn) {
    return fn(val);
  }

  // - Calls the map of another monad
  // - Requires the value passed in to be a function
  function ap(anotherMonad) {
    return anotherMonad.map(val);
  }
}

These monadic behaviours obey 3 monadic rules. (We won't go into the rules though.)

Here's some use cases to wrap your head around how it works:

const ten = Just(10);
const eleven = ten.map(x => x + 1);

ten.chain(x => x); // 10
eleven.chain(x => x); // 11

// -----

const user1 = Just('Dan');
const user2 = Just('John');

const tuple = curry(2, (x, y) => [x, y]);

// The map method returns a monad with the curried tuple waiting for 1 more input
// The ap method takes that curried tuple and passes the last input via user2.map
const users = user1.map(tuple).ap(user2);

users.chain(x => x); // ["Dan", "John"]

Note: We are cheating when we pass the identity function to chain. The only acceptable function for a chain is a function that returns a monad. That's because returning the value inside the monad is considered a side effect.

The maybe monad

One of the most common use cases for monads is the maybe monad. This monad solves the problem of accessing deeply nested object properties where you don't know if you'll get back undefined for any of those properties.

To start, you need a Nothing monad that continually returns back more Nothing monads. We'll use this monad if we hit undefined.

function Nothing() {
  return { map: Nothing, chain: Nothing, ap: Nothing };
}

Now we want to create our Maybe monad and our prop helper function.

const Maybe = { Nothing, of: Just };

// Returns either a Nothing or a Just monad
function fromNullable(val) {
  if (val === null || val === undefined) return Maybe.Nothing();
  return Maybe.of(val);
}

// Passes property value to fromNullable
const prop = curry(2, function (key, obj) {
  return fromNullable(obj[key]);
});

Finally, we can access our deeply nested property by chaining chain.

Maybe.of(obj)
  .chain(prop('someProp'))
  .chain(prop('thatIsNested'))
  .chain(prop('prettyDeeply'));

Note: This works because prop is curried, so it's waiting for an object to be passed into it before it is invoked. And chain passes that object. Then the Just monad returned with that property value closed over it calls chain again.

If at any point fromNullable finds a property that returns undefined or null, it returns a Nothing monad, making all future chains return a Nothing monad as well.

More on Monads

Here are some kinds of monads:

  • Just

  • Nothing

  • Maybe

  • Either

  • IO

PreviousTransductionNextAsync

Last updated 3 years ago