Skip to main content

Lenses

A lens is a composable dyad of getter and setter routines that allows for interactions with fields inside list structures. The lens routines in the bingo-functional library - those described in the text to follow - are inspired by the artifacts in RamdaJS.

lens#

lens(getter, setter)

lens :: (s -> a) -> ((a, s) -> s) -> Lens s a

Builds a lens out of getter and setter functions.

Since:

  • bingo-functional - v2.0.0

Argument(s):

  • getter - An arbitrary getter function
  • setter - An arbitrary setter function
use Chemem\Bingo\Functional as f;use function Chemem\Bingo\Functional\Functors\Lens\lens;
$lens = lens(f\curry(f\pluck)('x'), f\curry(f\assoc)('x'));

lensKey#

lensKey(key)

lensKey :: b -> Lens s a

Creates a lens whose focus is an arbitrary list key.

Since:

  • bingo-functional - v2.0.0

Argument(s):

  • key - An arbitrary key from which to create the lens
use function Chemem\Bingo\Functional\Functors\Lens\lensKey;
$lens = lensKey('foo');

view#

view(lens, store)

view :: Lens s a -> [a] -> a

Extracts the focus of a lens.

Since:

  • bingo-functional - v2.0.0

Argument(s):

  • lens - A lens object
  • store - A store whose focus is to be extracted
use Chemem\Bingo\Functional as f;use function Chemem\Bingo\Functional\Functors\Lens\{lens, view};
$lens   = lens(f\curryRight(f\pluck)('x'), f\curry(f\assoc)('x'));$result = view($lens, [  'y' => range(1, 5),  'z' => 'foo',  'x' => 'baz',]);

set#

set(lens, value, store)

set :: Lens s a -> b -> [a] -> [b]

Updates an entity associated with the focus of a lens.

Since:

  • bingo-functional - v2.0.0

Argument(s):

  • lens - A lens object
  • value - An arbitrary value to replace the focal point of the lens
  • store - A store (list) whose focal point is to be overwritten
use function Chemem\Bingo\Functional\Functors\Lens\{lensKey, set};
$lens   = lensKey(0);$result = set($lens, ['bar', 'baz'], [  'bar' => range(1, 3),  ['foo', 'bar'],]);

over#

over(lens, operation, store)

over :: Lens s a -> (a -> b) -> [a] -> [b]

Applies a function to the focus of a lens.

Since:

  • bingo-functional - v2.0.0

Argument(s):

  • lens - A lens object
  • operation - An arbitrary function with which to transform the focus of a lens
  • store - A store (list) whose focal point is to be transformed
use function Chemem\Bingo\Functional\Functors\Lens\{lensKey, over};
$lens   = lensKey('foo');$result = over($lens, fn ($x) => $x ** 2, [  'foo' => 4,  'bar' => 3,  'baz' => 90,]);

lensPath#

lensPath(...fragments)

lensPath :: [b] -> Lens s a

Creates a lens from a discernible list path.

Since:

  • bingo-functional - v2.0.0

Argument(s):

  • fragments - List path fragments
use function Chemem\Bingo\Functional\Functors\Lens\{lensPath, set};
$lens   = lensPath('foo', 'x', 1);$result = set($lens, 'github', (object) [  'bar' => range(1, 3),  'foo' => (object) [    'x' => ['twitter', 'instagram'],    'y' => 2,  ],]);