hotch-potch, Note to self

いろいろ作業記録

Elixir by Example - 1.Hello World

1.Hello World

最初のプログラムは、古典的な「こんにちは世界」メッセージを表示します。

ソースコード全体を次に示します。

IO.puts "hello world"

プログラムを実行するには、コードをhello-world.exsファイルに保存し、下記のように実行します。

$ elixir hello-world.exs
hello world

$

作成したプログラムをバイナリ形式にビルドしたいことも あるでしょう。

escriptを使えば可能です。

①アプリケーションを新規に作る

$ mix new helloworld
mix new helloworld
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating lib
* creating lib/helloworld.ex
* creating test
* creating test/test_helper.exs
* creating test/helloworld_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd helloworld
    mix test

Run "mix help" for more commands.

#アプリケーションのディレクトリに移動
$ cd helloworld

②mix.exsの編集

コメントの書かれている3カ所に追記します。

defmodule Helloworld.MixProject do
  use Mix.Project

  def project do
    [
      app: :helloworld,
      version: "0.1.0",
      elixir: "~> 1.10",
      start_permanent: Mix.env() == :prod,
      deps: deps(),
      # ↑行末にコンマを追記
      # ↓この1行を追記
      escript: escript()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
      extra_applications: [:logger]
    ]
  end

  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
    ]
  end

  # ↓この3行を追記
  defp escript do
    [main_module: Helloworld]
  end
end

一番最後に追記したmain_module: Helloworldのところが、実行時に自動的に実行されるモジュールになります。

③helloworld.exの編集

コメントの書かれている3カ所に追記します。

defmodule Helloworld do
  @moduledoc """
  Documentation for `Helloworld`.
  """

  @doc """
  Hello world.

  ## Examples

      iex> Helloworld.hello()
      :world

  """
  def hello do
    :world
  end

  # ↓この6行を追記
  @doc """
  メイン関数
  """
  def main(_args \\ []) do
    IO.puts("hello world")
  end
end

④実行

以下のようにすれば、ビルドしたバイナリを直接実行できます。

#ビルド
$ mix escript.build
Compiling 1 file (.ex)
Generated helloworld app
Generated escript helloworld with MIX_ENV=dev

#実行
$ ./helloworld
hello world
$

これで基本的な Elixir プログラムをビルド・実行できるように なりました。 さらに詳しく学んでいきましょう。

Next example: Values.

参考資料

(ひとこと)この記事の作成の背景

Elixirと並行して、Goも勉強をしているのですが、Goの教材を探しているときに非常にシンプルで分かり易いチュートリアルを見つけました。

gobyexample.com

ちなみにこれ、他の言語もあるようです。

同じようなやりたいことを、他の言語と比べながら学習できると面白そうなので、勝手に「Elixir」版をつくる連載をしてみます。

原文の説明文は、適当に翻訳ツールを使用&手直しして(原文のニュアンスを尊重しつつ)書いています。

Elixirの入門資料の多くは、iexの対話プロンプトで書かれていますが、この連載では、Go by Exampleの書き方に近いかたちに倣って、敢えてスクリプト版で書いています。

というのが、自分自身がElixirを最初に勉強するときに、どうしてもCとかPythonとか、ソースコードを先に書いてそれを実行するスタイルに慣れてしまってて、対話型で進めるのがどうしてもやりにくかったので・・・他の言語の入門資料に合わせた、Elixir言語の入門書を書いてみたい想いがありました。学習を始めて間もない、かつての自分向けのメッセージも込めて、このスタイルにしています

原文は非常にシンプルな作りになっていますが、当記事では、関連する補足情報、参考資料のリンクも書いています。 なので、あのシンプルで美しい「○○ by Example」にはなっていないので、予めご承知おき願います。

なお、これを作成するにあたり、日本語版「Go by Example」を参考にさせて頂いてます。作者の@oohira様に心より感謝申し上げます。