2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Elixir | コマンドラインアプリケーションを作成する #elixir

Posted at

Elixir | コマンドラインアプリケーションを作成する #elixir

概要

Elixir でコマンドラインアプリケーションを作成します

サンプル

仕様

  • FizzBuzz アプリケーション
    • 数値が 15 の場合は FizzBuzz を返却
    • 数値が 5 の場合は Buzz を返却
    • 数値が 3 の場合は Fizz を返却
    • その他の場合は、そのままの数値を返却
  • 第一引数を from, 第二引数を to とする

手順

プロジェクトの作成

$ mix new clisample

プロダクトコードの実装

  • lib/clisample.ex
defmodule Clisample do
  def main(args) do
    IO.inspect(fizzbuzz(String.to_integer(List.first(args)), String.to_integer(List.last(args))))
  end

  @doc ~S"""
  FizzBuzz.

  ## Examples

      iex> Clisample.fizzbuzz(1, 15)
      [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]
  """
  def fizzbuzz(from, to) when is_integer(from) and is_integer(to) do
    from..to |> Enum.map(&(fizzbuzz/1))
  end
  def fizzbuzz(_from, _to) do
    raise "invalid argument"
  end
  defp fizzbuzz(n) when rem(n, 15) == 0 , do: "FizzBuzz"
  defp fizzbuzz(n) when rem(n, 3) == 0, do: "Fizz"
  defp fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz"
  defp fizzbuzz(n), do: n
end

mix.exs で main モジュールの設定

  • lib/clisample.ex

project 関数の escript キーに対象モジュールを設定

$ cat mix.exs
defmodule Clisample.Mixfile do
  use Mix.Project

  def project do
    [app: :clisample,
     version: "0.0.1",
     elixir: "~> 1.0.0",
     escript: [ main_module: Clisample ],
     deps: deps]
  end

  # Configuration for the OTP application
  #
  # Type `mix help compile.app` for more information
  def application do
    [applications: [:logger]]
  end

  # Dependencies can be Hex packages:
  #
  #   {:mydep, "~> 0.3.0"}
  #
  # Or git/path repositories:
  #
  #   {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
  #
  # Type `mix help deps` for more examples and options
  defp deps do
    []
  end
end

プロジェクトの build を行う

$ mix escript.build

試行

$ ./clisample 1 5
[1, 2, "Fizz", 4, "Buzz"]
$ ./clisample 15 30
["FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz", 26, "Fizz", 28, 29, "FizzBuzz"]
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?