LoginSignup
12
0

【TIPS】Elixirのdefp(モジュール内関数)は型定義を書けない?

Last updated at Posted at 2023-12-06

この記事は、Elixir Advent Calendar 2023 シリーズ8 の10日目です

昨日は、 @mnishiguchi さんで 「Elixir で fortune を楽しむ」 でした


【本コラムは、3分で読め、3分で試せます】

piacere です、ご覧いただいてありがとございます :bow:

@im_miolab さんから、こんな質問がありました

普段、defpをほぼ書かない私には、新鮮なネタでしたので、軽くコラム化してみました

実際にdefpでspecを書くと…

defpでspecを書いてみます

defmodule Sample do
  @SPEC hoge(integer, string) :: {string, string}
  defp hoge(a, b) do
    {#{a}, #{b}}
  end

  def foo(), do: hoge(1, 2)
end

コンパイルすると、下記の通り、関数未定義エラーとなります

$ mix compile
Compiling 1 file (.ex)

== Compilation error in file lib/bright.ex ==
** (SyntaxError) lib/bright.ex:2:9: syntax error before: hoge
    |
  2 |   @SPEC hoge(integer, string) :: {string, string}
    |         ^
    (elixir 1.15.5) lib/kernel/parallel_compiler.ex:377: anonymous fn/5 in Kernel.ParallelCompiler.spawn_workers/8

defpはインライン化されるためspecが書けない…

黒田さん 曰く、defp関数はコンパイル時にインライン化されるため、specが意味を持たないようです

諦めないとダメ?

Elixirへの型システム導入(下記動画)により、この状況も変わる可能性はあるかも知れません


明日は、私で 「【TIPS】マップ:文字列キーとアトムキーの相互変換」 です

12
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
0