Skip to content

Commit

Permalink
Fix doctest warning (#14)
Browse files Browse the repository at this point in the history
Since Elixir 1.17 this code was generating a warning:


https://github.com/CargoSense/compare_chain/blob/7acb340ee6a6ae32349874f8c7bcd569728e83b5/lib/compare_chain.ex#L140-L146

Specifically, `a < b` generates a warning about comparing structs. This
is not unexpected (it's the whole point of `CompareChain` after all).
But there isn't a good way to circumvent the warning. See the discussion
here:

https://elixirforum.com/t/elixir-v1-18-0-rc-0-released/68015/36

This PR works around the issue by removing that code and instead
explaining what's going on in an info block:

![Screenshot 2024-12-18 at 11-32-30 CompareChain — compare_chain v0 5
0](https://github.com/user-attachments/assets/fa147c78-9630-45c7-9e4f-0078f4031b69)

I also tacked on a small refactor.
  • Loading branch information
billylanchantin authored Dec 18, 2024
2 parents 471c129 + 3c09cae commit ad75c19
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions lib/compare_chain.ex
Original file line number Diff line number Diff line change
Expand Up @@ -134,17 +134,26 @@ defmodule CompareChain do
## Examples
Semantic comparison (note how `a < b == false` because of native structural
comparison):
Semantic comparison:
iex> import CompareChain
iex> a = ~D[2017-03-31]
iex> b = ~D[2017-04-01]
iex> a < b
false
iex> compare?(a < b, Date)
true
> #### Semantic vs. Structural Comparison Differences {: .info}
>
> In the above example, `compare?(a < b, Date)` evaluates to `true`. On its
> own, `a < b` evaluates to `false` (with a warning). **This is why it's so
> important to not use comparison operators on structs directly.** The answer
> is not what you would expect.
>
> _Trivia!_ If you're curious, `b` comes before `a` because in term ordering,
> maps of equal size are compared key by key in ascending order. In this case,
> `:day` is the first key (due to ASCII byte ordering) where `a` and `b`
> differ. Since `a.day == 31` and `b.day == 1`, we have `b < a`.
Chained, semantic comparison:
iex> import CompareChain
Expand Down Expand Up @@ -236,7 +245,7 @@ defmodule CompareChain do
end

defp valid?(ast), do: valid?(ast, false)
defp valid?(node, false) when is_combination(node), do: Enum.all?(elem(node, 2), &valid?(&1))
defp valid?(node, false) when is_combination(node), do: Enum.all?(elem(node, 2), &valid?/1)
defp valid?(node, false) when is_comparison(node), do: true
defp valid?(_, _), do: false

Expand Down

0 comments on commit ad75c19

Please sign in to comment.