Skip to content

Instantly share code, notes, and snippets.

@semmel
Last active September 4, 2023 14:49
Show Gist options
  • Save semmel/f9243e8d63c978ade613629f1eecbce5 to your computer and use it in GitHub Desktop.
Save semmel/f9243e8d63c978ade613629f1eecbce5 to your computer and use it in GitHub Desktop.
Rearrange (Applicative or Functor) Types with Ramda

An Applicative type (e.g. a Maybe) is also a Functor with an ap method. Thus, for the observations in the table it can be used everywhere as an example.

Purpose Function Signature Example
swap types inside out sequence(TypeRep f) t (f a) → f (t a)1 sequence(M)([Just(1)]) // -> Just [1]
apply effect + wrap inside out traverse(TypeRep f) (a → f b) → t a → f (t b)1 traverse(M)(reciprocal, [2]) // -> Just [0.5]
swap data portion type inside out lens(identity) Functor f ⇒ s → f s yLens(identity)({x: 1, y: M.Just(2)}) // -> Just {x:1,y:2}
apply effect to data portion + wrap inside out lens Functor f ⇒ (a → f a) → s a → f (s a) yLens(reciprocal)({x: 1,y: 2}) // -> Just {x:1, y: 0.5}

for the examples:

const {identity, lens, lensProp, sequence, traverse} = require('ramda');
// Applicative (also Functor) Type
const M = require('crocks/Maybe');
// Division with effect
// :: Number → Maybe Number
const reciprocal = n => n !== 0 ? M.Just(1 / n) : M.Nothing();

const yLens = lensProp("y");

Footnotes

  1. f must be an Applicative (a type with a .map method and an .ap combinator method). t is a Traversable (e.g. Array) 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment