简体   繁体   中英

Why the syntax for defining sigils in Elixir doesn't use “defsigil”?

I was reading the page about sigils in the Elixir tutorial.
I expected the syntax for defining sigils uses "defsigil" just like "defstruct", "defprotocol", and so on.
But it was not so.
Why?

Sigils are just a fancy way to call specific methods. Take a look at the section on Custom Sigils . Basically ~x/things/options is the same as sigil_x(things, options) . So you can write something like:

defmodule Thing do
  def sigil_u(string, _options) do
    string |> String.upcase
  end

  def test do
    ~u/bob/
  end
end

IO.inspect Thing.test

The original sigil syntax was def __s__ where s is the character used for the sigil (this would now be def sigil_s .) You can see this in the initial commit that started work on sigils. I believe this work started before macros were implemented.

This syntax required a hack to allow them to be imported which you can read about in this issue.

Today, when someone writes %f"foo", it translates to f ("foo", []). This proposal is to change the translation to: sigil_f("foo", []).

This change brings two benefits:

1) The name is more explicit;
2) It allows us to remove a hack in our importer. Today, import Hello brings all functions from Hello that do not start with underscore but it makes an exception for sigils;

You can see in the discussion that some other suggestions such as defmodule Sigil.s were suggested, however the def sigil_s syntax was ultimately chosen.

The actual commit that implements these changes is https://github.com/elixir-lang/elixir/commit/c6284557e792efd67f13f421b723a7a301bdbb93

I am not sure why it is not defsigil perhaps nobody suggested it? This is my best guess given that at the time of this post, searching for "defsigil" on Google only returns this question. If it was mentioned on GitHub or IRC then there would have been a mention of it in the search results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM