Dextruct v0.2.0 Dextruct View Source

The operator <~ imitates destructing assignment behavior like in Ruby or ES6.

It’s so obvious that pattern matching with = is just awesome. But less then occasionally, we still want some destructing assignment, witout MatchError, works like in other languge. Dextruct library provides a <~ operator which imitates similar behavior, with some other goodies.

The <~ operator works on two senarios, List and Map.

List

For destructing assignment on List, it simply fills up the list on left hand side with filler (nil by default).

  ```elixir
  iex> [a, b, c] <~ [1, 2]
  [1, 2, nil]

  iex> c
  nil
  ```

One of the useful example is use with Regex’s optional group matching. Originally it will omit the unmatched groups in the end.

    ```elixir
    iex> Regex.run(~r/(a)?(b)?(c)?(d)?/, "ab")
    ["ab", "a", "b"]

    iex> [matched, a, b, c, d] <~ Regex.run(~r/(a)?(b)?(c)?(d)?/, "ab")
    ["ab", "a", "b", nil, nil]
    ```

### Map Destructing assignment on Map, then as well, fill the keys missing in the right hand side map, with filler.

    ```elixir
    iex> %{a: a, b: b, c: c} <~ %{a: 1}
    iex> a
    1
    iex> b
    nil
    iex> c
    nil
    ```

Link to this section Summary

Functions

Use the library

Fill up the List or Map with the filler

A short-hand literal for create Map

Link to this section Functions

Link to this macro __using__(opts \\ []) View Source (macro)

Use the library.

You can specify the filler by fill option while use Dextruct. That means you can only have one filler for each module.

    ```elixir
    def YourModule do
      use Dextruct, fill: 0
    end
    ```
Link to this function fill(enum, length_or_keys, filler \\ nil) View Source
fill(List.t, number, any) :: List.t
fill(Map.t, List.t, any) :: Map.t

Fill up the List or Map with the filler.

For List, it takes the list and length, then fill the list upto then length with filler (nil by default)

Examples

```elixir
iex> Dextruct.fill([1], 3)
[1, nil, nil]
```

Pass the filler if you want something else.

Examples

```elixir
iex> Dextruct.fill([1, 2], 4, 0)
[1, 2, 0, 0]
```

For Map, it takes the map and a list of keys. For those keys which stay in the original map, no matter you include them in the second argument or not, this function will leave them untouched.

Example

```elixir
iex> Dextruct.fill(%{a: 1}, [:a, :b, :c])
%{a: 1, b: nil, c: nil}

# same as
iex> Dextruct.fill(%{a: 1}, [:b, :c])
%{a: 1, b: nil, c: nil}
```
Link to this macro sigil_m(arg, opt) View Source (macro)

A short-hand literal for create Map

  ```elixir
  iex> ~m{a, b, c: foo} = %{a: 1, b: 2, c: 3}
  %{a: 1, b: 2, c: 3}
  ```

Please notice that this sigil_m might be exclude by default or even deprecate, once the ShortMap literal becomes the de facto standard anytime in the future.