Giter VIP home page Giter VIP logo

lens's Introduction

Lens

Build Status Hex.pm Hex.pm

A utility for working with nested data structures. Take a look at Nested data structures with functional lenses for a gentler introduction. Note that the blogpost was written using version 0.3.1 and there have been some API changes since then - see Upgrading for details.

Installation

The package can be installed by adding lens to your list of dependencies in mix.exs:

def deps do
  [
    {:lens, "~> 1.0.0"}
  ]
end

Upgrading

From pre-0.6.0

In 0.6.0 the function Lens.get got removed. The reason was that it was very easy to create a bug where a list was treated as a single element or vice-versa. Wherever you used Lens.get you now should either use Lens.one! if the invocation should always return exactly one element (this will crash if there is any other number of elements) or Lens.to_list and match on the result if you want to behave differently for different numbers of elements.

From pre-0.5.0

In 0.5.0 the function satisfy got renamed to filter while the previous version of filter was removed. The reason was that with the new arrangement there is a matching pair of filter/reject functions, and this should be more intuitive. Wherever you used Lens.filter(predicate) you can now use Lens.filter(Lens.all(), predicate).

Example

Lens allows you to separate which parts of a complex data structure need to be processed from the actual processing. Take the following:

data = %{
  main_widget: %{size: 200.5, subwidgets: [%{size: 120, subwidgets: [%{size: 200, subwidgets: []}]}]},
  other_widgets: [
    %{size: 16.5, subwidgets: [%{size: 120, subwidgets: []}]},
    %{size: 160.5, subwidgets: []},
    %{size: 121.9, subwidgets: []},
  ]
}

Let's say we're interested in the sizes of all widgets (be they the main widget or other widgets) that are larger than 100. We can construct a Lens object that describes these locations in the datastructure the following way:

lens = Lens.both(
  Lens.key(:main_widget),
  Lens.key(:other_widgets) |> Lens.all
)
|> Lens.seq_both(Lens.recur(Lens.key(:subwidgets) |> Lens.all))
|> Lens.key(:size)
|> Lens.filter(&(&1 > 100))

Given that we can:

  • Extract all the relevant data
iex> Lens.to_list(lens, data)
[200.5, 160.5, 121.9, 120, 200, 120]
  • Update the described locations in the data structure
iex> Lens.map(lens, data, &round/1)
%{main_widget: %{size: 201,
    subwidgets: [%{size: 120, subwidgets: [%{size: 200, subwidgets: []}]}]},
  other_widgets: [%{size: 16.5, subwidgets: [%{size: 120, subwidgets: []}]},
   %{size: 161, subwidgets: []}, %{size: 122, subwidgets: []}]}
  • Simultaneously update and return something from every location in the data
iex> Lens.get_and_map(lens, data, fn size -> {size, round(size)} end)
{[200.5, 160.5, 121.9, 120, 200, 120],
 %{main_widget: %{size: 201,
     subwidgets: [%{size: 120, subwidgets: [%{size: 200, subwidgets: []}]}]},
   other_widgets: [%{size: 16.5, subwidgets: [%{size: 120, subwidgets: []}]},
    %{size: 161, subwidgets: []}, %{size: 122, subwidgets: []}]}}

Lenses are also compatible with Access and associated Kernel functions:

iex> get_in([1, 2, 3], [Lens.all() |> Lens.filter(&Integer.is_odd/1)])
[1, 3]
iex> update_in([1, 2, 3], [Lens.all() |> Lens.filter(&Integer.is_odd/1)], fn x -> x + 1 end)
[2, 2, 4]
iex> get_and_update_in([1, 2, 3], [Lens.all() |> Lens.filter(&Integer.is_odd/1)], fn x -> {x - 1, x + 1} end)
{[0, 2], [2, 2, 4]}

Formatting

Normally, mix format will change definitions like:

deflens a_lens(), do: some() |> implementation()
deflensp a_private_lens(), do: some() |> implementation()

into:

deflens(a_lens(), do: some() |> implementation())
deflensp(a_private_lens(), do: some() |> implementation())

To avoid this, you can import lens's formatter settings in your formatter.exs:

# my_app/.formatter.exs
[
  import_deps: [:lens]
]

lens's People

Contributors

febeling avatar mariusbutuc avatar obrok avatar patrikstenmark avatar sebastian avatar vic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

lens's Issues

Missing typespec for Lens.into

In the source code of lens.ex, the definition of into is missing a typespec. That is the cause of a dialyxir error.

  deflens_raw into(lens, collectable) do
    fn data, fun ->
      {res, updated} = get_and_map(lens, data, fun)
      {res, Enum.into(updated, collectable)}
    end
  end
Function call without opaqueness type mismatch.

Call does not have expected opaque term of type Lens.t() in the 2nd position.

Common.Utilities.lens_map(
  any(),
  _lens4 :: (:get | :get_and_update, _, (_ -> any()) -> any()),
  ...

Lens.multiple Question

Hello,

Thank you for writing this library!

My apologies, any chance you might be able to give me a hint where my logic might be off with the following lens and data structure?

data = [%{id: 1}, %{id: 2, sub_items_1: [%{id: 4}, %{id: 5}], sub_items_2: [%{id: 6}, %{id: 7}]}, %{id: 3}]

lens = Lens.all
                |> Lens.multiple([Lens.key?(:sub_items_1), Lens.key?(:sub_items_2), Lens.root])
                |> Lens.all
                |> Lens.key(:id)
                |> Lens.to_list(data)

The Lens.multiple() step works if I only include the first two entries in the argument list, but once I include Lens.root, I get the "no function clause matching in Access.fetch/2" error.

Thank you very much.

having a lot of trouble focusing on keys

maybe lenses are not designed for this use-case, but i thought it would be really neat if i could focus on keys in a map, and do Lens.map over them.

very cool library/concept!

Lens.filter, error from example code

There is the Svbtle article that introduces to lens, and it contains this example:

import Integer

data = 1..10
lens = Lens.filter(&is_odd/1)

get_in(data, [lens])
# => [1, 3, 5, 7, 9]
update_in(data, [lens], &(-&1))
# => [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]

When I follow that in iex, line 3 using filter/1 fails with this error:

iex(31)> lens = Lens.filter(&is_odd/1)
** (UndefinedFunctionError) function Lens.filter/1 is undefined or private. Did you mean one of:

      * filter/2
      * filter/3

    (lens) Lens.filter(#Function<6.99386804/1 in :erl_eval.expr/5>)

Which kind of makes sense, as the hex docs say it's expecting a lens as first argument. But then the article example contradicts that. What's going on? (Is that an API change?)

infinite recursion / hang on Lens.recur

It may be that I'm just being really dumb but here goes, in the case of both the following examples, typed in the console, the terminal just hung, I'm guessing they're off on a infinite recursion loop?

Lens.recur(Lens.key(:a)) |> Lens.to_list( %{a: %{b: :c}})
Lens.recur( Lens.root() |> Lens.key) |> Lens.map( %{a: %{b: :c}},  &IO.inspect/1)    

Why Lens.into does nothing inside the map ?

Hello,
Thanks for this fantastic library which is very useful. I stumbled upon a weird behaviour of Lens.into when used inside a map, not a the top level. IMHO I think test4_ko/1 should return a map instead of a list thanks to Lens.into in the expression:

Lens.map_values |> Lens.all |> Lens.into(%{}) |> Lens.map(h, fn {k,v} -> {k,v} end)

The code is copied below.

iex(1)> h = LensTest.get_a_map
%{
  "top" => %{
    "257" => %{
      "datetime" => "2020-03-03T14:58:30.200896+01:00",
      "value" => false
    }
  }
}
iex(2)> LensTest.test1_ok(h)
[
  {"top",
   %{
     "257" => %{
       "datetime" => "2020-03-03T14:58:30.200896+01:00",
       "value" => false
     }
   }}
]
iex(3)> LensTest.test2_ok(h)
%{
  "top" => %{
    "257" => %{
      "datetime" => "2020-03-03T14:58:30.200896+01:00",
      "value" => false
    }
  }
}
iex(4)> LensTest.test3_ok(h)
%{
  "top" => [
    {"257",
     %{"datetime" => "2020-03-03T14:58:30.200896+01:00", "value" => false}}
  ]
}
iex(5)> LensTest.test4_ko(h)
%{
  "top" => [
    {"257",
     %{"datetime" => "2020-03-03T14:58:30.200896+01:00", "value" => false}}
  ]
}
defmodule LensTest do
  def get_a_map do
    %{"top" => %{"257" => %{"datetime" => "2020-03-03T14:58:30.200896+01:00", "value" => false}}}
  end

  def test1_ok(h) do
    Lens.all |> Lens.map(h, fn {k,v} -> {k,v} end)
  end

  def test2_ok(h) do
    Lens.all |> Lens.into(%{}) |> Lens.map(h, fn {k,v} -> {k,v} end)
  end

  def test3_ok(h) do
    Lens.map_values |> Lens.all |> Lens.map(h, fn {k,v} -> {k,v} end)
  end

  def test4_ko(h) do
    Lens.map_values |> Lens.all |> Lens.into(%{}) |> Lens.map(h, fn {k,v} -> {k,v} end)
  end

end

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.