elixir-rational icon indicating copy to clipboard operation
elixir-rational copied to clipboard

~f'a/b' sigil for rationals

Open tmbb opened this issue 3 years ago • 0 comments

The implementation would be very simple:

defmodule Fraction do
  @doc """
  Sigil for fractions. Compiles to `Rational.new/2`.
  """
  defmacro sigil_f({:<<>>, _meta, [text]} = _content, _modifiers) do
    case Code.string_to_quoted!(text) do
      {:/, _meta, [numerator, denominator]} ->
        quote do
          Ratio.new(unquote(numerator), unquote(denominator))
        end

      _other ->
        raise ArgumentError, "Invalid fraction ~f'#{text}'."
    end
  end
end

This would allow arbitrary expressions inside the sigil, which I think is a cool feature.

iex(1)> import Fraction
Fraction
iex(2)> ~f'1/2'
Ratio.new(1, 2)
iex(3)> ~f'124/25'
Ratio.new(124, 25)
iex(4)> ~f'5 / 125' 
Ratio.new(1, 25)
iex(5)> ~f'(5 + 8) / 125'
Ratio.new(13, 125)
iex(6)> a = 13
13
iex(7)> b = 7
7
iex(8)> ~f'a / b'        
Ratio.new(13, 7)

What do you think?

tmbb avatar Dec 17 '22 16:12 tmbb