Thanks to visit codestin.com
Credit goes to github.com

Skip to content

How to create a Traversal for a List of arbitrary length #430

Open
@JohnMcGuinness

Description

@JohnMcGuinness

Since there's no usable documentation for this library I'll ask a question here.

I have a Cart which may have an Item in it. An Item has a Discount, which may be NoDiscount or PercentDiscount.

public record Cart(String id, Item item, int quantity)

public record Item(String sku, double price, int leftInStock, Discount discount)

sealed interface Discount permits NoDiscount, PercentDiscount

public record NoDiscount() implements Discount

public record PercentDiscount(double value) implements Discount

I have some Optics:

private static final Lens<Cart, Item> itemL = Lens.lens(Cart::item, (Item i) -> (Cart c) -> new Cart(c.id(), i, c.quantity()));

private static final Lens<Item, Discount> discountL = Lens.lens(Item::discount, d -> i -> new Item(i.sku(), i.price(), i.leftInStock(), d)); 

private static final Prism<Discount, Double> onlyPctDiscount
	= Prism.prism(
		d -> {
			if(d instanceof PercentageOff) {
				return Option.some(((PercentageOff) d).value());
			}
			else {
				return Option.none();
			}
		},
		PercentageOff::new
	);

This code recalulates the Item's Discount given a Cart:

itemL.composeLens(discountL).composePrism(onlyPctDiscount).modify(calculation).f(cart);

If I change the Cart to have a List of Item's, to recalculate the discount for each item in the cart I'm pretty sure I need to change that Prism to a Traversal.

How do I create a traversal for a list with any number of Items. From what I can make out FJ only allows Traversals for 2 to 6 items in a List.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions