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

Functor.map behaviour on tuples #95

Open
florius0 opened this issue Nov 17, 2021 · 1 comment
Open

Functor.map behaviour on tuples #95

florius0 opened this issue Nov 17, 2021 · 1 comment

Comments

@florius0
Copy link
Contributor

When called with first argument being tuple, Functor.map/2 applies a function only to the last element of tuple:

iex(1)> use Witchcraft
iex(2)> map({1, 2, 3}, fn x -> x + 1 end)
{1, 2, 4}

Is this intended behaviour?

@florius0
Copy link
Contributor Author

PS Looked in Witchcraft.Functor, looks like it is intended

definst Witchcraft.Functor, for: Tuple do
  def map(tuple, fun) do
    case tuple do
      {} ->
        {}

      {first} ->
        {fun.(first)}

      {first, second} ->
        {first, fun.(second)}

      {first, second, third} ->
        {first, second, fun.(third)}

      {first, second, third, fourth} ->
        {first, second, third, fun.(fourth)}

      {first, second, third, fourth, fifth} ->
        {first, second, third, fourth, fun.(fifth)}

      big_tuple ->
        last_index = tuple_size(big_tuple) - 1

        mapped =
          big_tuple
          |> elem(last_index)
          |> fun.()

        put_elem(big_tuple, last_index, mapped)
    end
  end
end

Can somebody explain my why it is so?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant