#functional #functional-programming #lens #data-structures

pl-lens

Provides support for lenses, which are a mechanism in functional programming for focusing on a part of a complex data structure

2 stable releases

1.0.1 Sep 4, 2020
1.0.0 Jun 28, 2020

#4 in #lens

MIT license

21KB
336 lines

pl-lens

Build Status Crates.io Docs.rs MIT licensed

This Rust library provides support for lenses, which are a mechanism in functional programming for focusing on a part of a complex data structure.

Usage

Add a dependency to your Cargo.toml:

[dependencies]
pl-lens = "1.0"

Then, in your crate:

// To use the `derive(Lenses)` macro
use pl_lens::Lenses;

// To use the `lens!` macro
use pl_lens::lens;

// To bring trait methods like `get_ref` and `set` into scope
use pl_lens::{Lens, RefLens};

Examples

A Lens can be used to transform a conceptually-immutable data structure by changing only a portion of the data. Let's demonstrate with an example:

#[derive(Lenses)]
struct Address {
    street: String,
    city: String,
    postcode: String
}

#[derive(Lenses)]
struct Person {
    name: String,
    age: u8,
    address: Address
}

let p0 = Person {
    name: "Pop Zeus".to_string(),
    age: 58,
    address: Address {
        street: "123 Needmore Rd".to_string(),
        city: "Dayton".to_string(),
        postcode: "99999".to_string()
    }
};
assert_eq!(lens!(Person.name).get_ref(&p0), "Pop Zeus");
assert_eq!(lens!(Person.address.street).get_ref(&p0), "123 Needmore Rd");

let p1 = lens!(Person.address.street).set(p0, "666 Titus Ave".to_string());
assert_eq!(lens!(Person.name).get_ref(&p1), "Pop Zeus");
assert_eq!(lens!(Person.address.street).get_ref(&p1), "666 Titus Ave");

License

pl-lens is distributed under an MIT license. See LICENSE for more details.

Dependencies

~1.5MB
~36K SLoC