Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/0.0.3 #11

Merged
merged 13 commits into from
Nov 26, 2022
5 changes: 5 additions & 0 deletions .changeset/cool-spies-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fp-ts/optic": patch
---

rename key to at
5 changes: 5 additions & 0 deletions .changeset/heavy-lobsters-try.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fp-ts/optic": patch
---

add findFirst
5 changes: 5 additions & 0 deletions .changeset/lazy-pens-poke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fp-ts/optic": patch
---

rename nullable to nonNullable
5 changes: 5 additions & 0 deletions .changeset/little-snails-move.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fp-ts/optic": patch
---

rename at to index
5 changes: 5 additions & 0 deletions .changeset/nine-flowers-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fp-ts/optic": patch
---

add modifyApplicative
5 changes: 5 additions & 0 deletions .changeset/purple-dragons-relate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fp-ts/optic": patch
---

add data/Chunk
5 changes: 5 additions & 0 deletions .changeset/rude-moles-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fp-ts/optic": patch
---

add /data/Boolean
5 changes: 5 additions & 0 deletions .changeset/shaggy-flies-glow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fp-ts/optic": patch
---

add /data/string
5 changes: 5 additions & 0 deletions .changeset/thick-goats-trade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fp-ts/optic": patch
---

add filter
157 changes: 132 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,39 @@ A porting of <a href="https://github.com/zio/zio-optics">zio-optics</a> to TypeS
</a>
</p>

`@fp-ts/optic` is a library that makes it easy to modify parts of larger data structures based on a single representation of an optic as a combination of a getter and setter.

`@fp-ts/optic` features a unified representation of optics, deep `@fp-ts/data` integration, helpful error messages,

# Features

- **Unified Representation Of Optics**. All optics compose the same way because they are all instances of the same data type (`Optic`)
- **Integration**. Built-in optics for `@fp-ts/data` data structures, like `List` and `Chunk`

# Optics

```mermaid
flowchart TD
Optic --> Iso
Iso --> Lens
Iso --> Prism
Lens --> Optional
Prism --> Optional
Optional --> Getter
Optional --> Setter
Getter --> Optic
Setter --> Optic
```

# Example
# Summary

Let's say we have an employee and we need to upper case the first character of his company street name.

```ts
import * as O from "@fp-ts/data/Option";

interface Street {
num: number;
name: string;
name: O.Option<string>;
}
interface Address {
city: string;
Expand All @@ -50,59 +60,156 @@ interface Employee {
name: string;
company: Company;
}
```

Let's say we have an employee and we need to upper case the first character of his company street name. Here is how we could write it in vanilla TypeScript

```ts
const employee: Employee = {
const from: Employee = {
name: "john",
company: {
name: "awesome inc",
address: {
city: "london",
street: {
num: 23,
name: "high street",
name: O.some("high street"),
},
},
},
};

const capitalize = (s: string): string =>
s.substring(0, 1).toUpperCase() + s.substring(1);

const employeeCapitalized = {
...employee,
const to: Employee = {
name: "john",
company: {
...employee.company,
name: "awesome inc",
address: {
...employee.company.address,
city: "london",
street: {
...employee.company.address.street,
name: capitalize(employee.company.address.street.name),
num: 23,
name: O.some("High street"),
},
},
},
};
```

As we can see copy is not convenient to update nested objects because we need to repeat ourselves. Let's see what could we do with `@fp-ts/optic`
Let's see what could we do with `@fp-ts/optic`

```ts
import * as Optic from "@fp-ts/optic";
import * as OptionOptic from "@fp-ts/optic/data/Option";
import * as StringOptic from "@fp-ts/optic/data/string";

const _name: Optic.Optional<Employee, string> = Optic.id<Employee>()
.compose(Optic.at("company")) // Lens<Employee, Company>
.compose(Optic.at("address")) // Lens<Employee, Company>
.compose(Optic.at("street")) // Lens<<Employee, Company>
.compose(Optic.at("name")) // Lens<Street, O.Option<string>>
.compose(OptionOptic.some()) // Prism<O.Option<string>, string>
.compose(StringOptic.index(0)); // Optional<string, string>

const _name = Optic.id<Employee>()
.compose(Optic.key("company"))
.compose(Optic.key("address"))
.compose(Optic.key("street"))
.compose(Optic.key("name"));
const capitalize = (s: string): string => s.toUpperCase();

const capitalizeName = Optic.modify(_name)(capitalize);

expect(capitalizeName(employee)).toEqual(employeeCapitalized);
expect(capitalizeName(from)).toEqual(to);
```

# Understanding Optics

`@fp-ts/optic` is based on a single representation of an optic as a combination of a getter and a setter.

```ts
export interface Optic<
in GetWhole,
in SetWholeBefore,
in SetPiece,
out GetError,
out SetError,
out GetPiece,
out SetWholeAfter
> {
readonly getOptic: (
GetWhole: GetWhole
) => Either<readonly [GetError, SetWholeAfter], GetPiece>;
readonly setOptic: (
SetPiece: SetPiece
) => (
SetWholeBefore: SetWholeBefore
) => Either<readonly [SetError, SetWholeAfter], SetWholeAfter>;
}
```

The getter can take some larger structure of type `GetWhole` and get a part of it of type `GetPiece`. It can potentially fail with an error of type `GetError` because the part we are trying to get might not exist in the larger structure.

The setter has the ability, given some piece of type `SetPiece` and an original structure of type `SetWholeBefore`, to return a new structure of type `SetWholeAfter`. Setting can fail with an error of type `SetError` because the piece we are trying to set might not exist in the structure.

## Lens

A `Lens` is an optic that accesses a field of a product type, such as a tuple or a struct.

The `GetError` type of a `Lens` is `never` because we can always get a field of a product type. The `SetError` type is also `never` because we can always set the field of a product type to a new value.

In this case the `GetWhole`, `SetWholeBefore`, and `SetWholeAfter` types are the same and represent the product type. The `GetPiece` and `SetPiece` types are also the same and represent the field.

Thus, we have:

```ts
export interface Lens<in out S, in out A>
extends Optic<S, S, A, never, never, A, S> {}
```

The simplified signature is:

```ts
export interface Lens<in out S, in out A> {
readonly getOptic: (s: S) => Either<never, A>;
readonly setOptic: (a: A) => (s: S) => Either<never, S>;
}
```

This conforms exactly to our description above. A lens is an optic where we can always get part of the larger structure and given an original structure we can always set a new value in that structure.

## Prism

A `Prism` is an optic that accesses a case of a sum type, such as the `Left` or `Right` cases of an `Either`.

Getting part of a larger data structure with a prism can fail because the case we are trying to access might not exist. For example, we might be trying to access the right side of an `Either` but the either is actually a `Left`.

We use the data type `Error` to model the different ways that getting or setting with an optic can fail. So the `GetError` type of a prism will be `Error`.

The `SetError` type of a prism will be `never` because given one of the cases of a product type we can always return a new value of the product type since each case of the product type is an instance of the product type.

A prism also differs from a lens in that we do not need any original structure to set. A product type consists of nothing but its cases so if we have a new value of the case we want to set we can just use that value and don't need the original structure.

We represent this by using `unknown` for the `SetWholeBefore` type, indicating that we do not need any original structure to set a new value.

Thus, the definition of a prism is:

```ts
export interface Prism<in out S, in out A>
extends Optic<S, unknown, A, Error, never, A, S> {}
```

And the simplified signature is:

```ts
export interface Prism<in out S, in out A> {
readonly getOptic: (s: S) => Either<Error, A>;
readonly setOptic: (a: A) => (s: unknown) => Either<never, S>;
}
```

Again this conforms exactly to our description. A prism is an optic where we might not be able to get a value but can always set a value and in fact do not require any original structure to set.

## Other

`@fp-ts/optic` supports a wide variety of other optics:

- **Optional**. An `Optional` is an optic that accesses part of a larger structure where the part being accessed may not exist and the structure contains more than just that part. Both the `GetError` and `SetError` types are `Error` because the part may not exist in the structure and setting does require the original structure since it consists of more than just this one part.
- **Iso**. An `Iso` is an optic that accesses a part of a structure where the structure consists of nothing but the part. Both the `GetError` and `SetError` types are `never` and the `SetWholeBefore` type is `unknown`.
- **Getter**. A `Getter` is an optic that only allows getting a value. The `SetWholeBefore` and `SetPiece` types are `never` because it is impossible to ever set.
- **Setter**. A `Setter` is an optic that only allows setting a value. The `GetWhole` type is `never` because it is impossible to ever get.

There are also more polymorphic versions of each optic that allow the types of the data structure and part before and after to differ. For example, a `PolyPrism` could allow us to access the right case of an `Either<A, B>` and set a `C` value to return an `Either<A, C>`.

# Installation

To install the **alpha** version:
Expand Down
38 changes: 31 additions & 7 deletions dtslint/ts4.7/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,47 @@ type ST = readonly [string, number]
type TT = readonly [boolean, number]

//
// key
// at
//

// $ExpectType Lens<S, string>
Optic.id<S>().compose(Optic.key('a'))
Optic.id<S>().compose(Optic.at('a'))

// $ExpectType PolyLens<S, T, string, boolean>
Optic.id<S, T>().compose(Optic.key<S, 'a', boolean>('a'))
Optic.id<S, T>().compose(Optic.at<S, 'a', boolean>('a'))

// $ExpectType Lens<ST, string>
Optic.id<ST>().compose(Optic.key('0'))
Optic.id<ST>().compose(Optic.at('0'))

// $ExpectType PolyLens<ST, TT, string, boolean>
Optic.id<ST, TT>().compose(Optic.key<ST, '0', boolean>('0'))
Optic.id<ST, TT>().compose(Optic.at<ST, '0', boolean>('0'))

// $ExpectType PolyLens<S, { readonly a: boolean; readonly b: number; }, string, boolean>
Optic.key<S, 'a', boolean>('a')
Optic.at<S, 'a', boolean>('a')

// $ExpectType PolyLens<ST, readonly [boolean, number], string, boolean>
Optic.key<ST, '0', boolean>('0')
Optic.at<ST, '0', boolean>('0')

//
// filter
//

declare const isString: (u: unknown) => u is string

// $ExpectType Prism<string | number, string>
Optic.id<string | number>().compose(Optic.filter(isString))

declare const predicate: (u: string | number | boolean) => boolean

// $ExpectType Prism<string | number, string | number>
Optic.id<string | number>().compose(Optic.filter(predicate))

//
// findFirst
//

// $ExpectType Optional<readonly (string | number)[], string>
Optic.id<ReadonlyArray<string | number>>().compose(Optic.findFirst(isString))

// $ExpectType Optional<readonly (string | number)[], string | number>
Optic.id<ReadonlyArray<string | number>>().compose(Optic.findFirst(predicate))
11 changes: 11 additions & 0 deletions src/data/Boolean.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* @since 1.0.0
*/

import type { Optional } from "@fp-ts/optic"
import { modify } from "@fp-ts/optic"

/**
* @since 1.0.0
*/
export const toggle = <S>(optic: Optional<S, boolean>): (s: S) => S => modify(optic)((a) => !a)
31 changes: 31 additions & 0 deletions src/data/Chunk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @since 1.0.0
*/
import type { Chunk } from "@fp-ts/data/Chunk"
import * as C from "@fp-ts/data/Chunk"
import * as E from "@fp-ts/data/Either"
import { pipe } from "@fp-ts/data/Function"
import * as O from "@fp-ts/data/Option"
import type { PolyPrism, Prism } from "@fp-ts/optic"
import { polyPrism } from "@fp-ts/optic"

/**
* An optic that accesses the `Cons` case of a `Chunk`.
*
* @since 1.0.0
*/
export const cons: {
<A>(): Prism<Chunk<A>, readonly [A, Chunk<A>]>
<A, B>(): PolyPrism<Chunk<A>, Chunk<B>, readonly [A, Chunk<A>], readonly [B, Chunk<B>]>
} = <A, B>(): PolyPrism<Chunk<A>, Chunk<B>, readonly [A, Chunk<A>], readonly [B, Chunk<B>]> =>
polyPrism(
(s) =>
pipe(
C.tail(s),
O.match(
() => E.left([Error(`Nil did not satisfy isCons`), C.empty]),
(tail) => E.right([C.unsafeHead(s), tail])
)
),
([head, tail]): Chunk<B> => C.prepend(head)(tail)
)
Loading