2
0

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 1 year has passed since last update.

ChatGPT で elixir を学ぶ (その2) 整数の加算

Last updated at Posted at 2024-03-03

こちらの記事の続きです。
ChatGPT で elixir を学ぶ (その1)

次に加算のプログラムを試みました。
残念ながら、ChatGPT も、Gemini も実行可能なプログラムは作成できませんでした。

Python のプログラム

sum.py
#! /usr/bin/python
#
import sys
#
sys.stderr.write("*** 開始 ***\n")
aa = int(sys.argv[1])
bb = int(sys.argv[2])
print("aa = %d\tbb = %d" % (aa,bb))
sum = aa + bb
print("sum = %d" % sum)
sys.stderr.write("*** 終了 ***\n")

実行結果

$ ./sum.py 12 34
*** 開始 ***
aa = 12	bb = 34
sum = 46
*** 終了 ***

ChatGPT が作成したプログラム

ch01.exs
args = System.argv()

IO.puts("*** 開始 ***")
aa = String.to_integer(Enum.at(args, 1))
bb = String.to_integer(Enum.at(args, 2))
IO.puts("aa = #{aa}\tbb = #{bb}")
sum = aa + bb
IO.puts("sum = #{sum}")
IO.puts("*** 終了 ***")

実行結果

$ elixir ch01.exs 12 34
*** 開始 ***
** (ArgumentError) errors were found at the given arguments:

  * 1st argument: not a binary

    :erlang.binary_to_integer(nil)
    ch01.exs:5: (file)
    (elixir 1.14.0) lib/code.ex:1245: Code.require_file/2

Gemini が作成したプログラム

ge01.exs
defmodule Sum do
  def main(args) do
    {aa, bb} = String.split(args.hd, " ") |> Enum.map(&String.to_integer/1)
    IO.stderr("*** 開始 ***\n")
    IO.puts("aa = #{aa}\tbb = #{bb}")
    sum = aa + bb
    IO.puts("sum = #{sum}")
    IO.stderr("*** 終了 ***\n")
  end
end

Sum.main(System.argv)

実行結果

$ elixir ge01.exs 12 34
** (KeyError) key :hd not found in: ["12", "34"]. If you are using the dot syntax, such as map.field, make sure the left-hand side of the dot is a map
    ge01.exs:3: Sum.main/1
    (elixir 1.14.0) lib/code.ex:1245: Code.require_file/2

私が作成したプログラム

sum.exs
IO.puts :stderr,"*** 開始 ***"
[ax | tail] = System.argv()
aa = String.to_integer(ax)
[bx | _] = tail 
bb = String.to_integer(bx) 
sum = aa + bb
IO.puts ("aa = #{aa}\tbb = #{bb}")
IO.puts("sum = #{sum}")
IO.puts :stderr,"*** 終了 ***"

実行結果

$ elixir sum.exs 12 34
*** 開始 ***
aa = 12	bb = 34
sum = 46
*** 終了 ***

Enum.at を使ったプログラム

sum02.exs
IO.puts :stderr,"*** 開始 ***"
args = System.argv()
aa = String.to_integer(Enum.at(args, 0))
bb = String.to_integer(Enum.at(args, 1))
sum = aa + bb
IO.puts ("aa = #{aa}\tbb = #{bb}")
IO.puts("sum = #{sum}")
IO.puts :stderr,"*** 終了 ***"

実行結果

$ elixir sum02.exs 12 34
*** 開始 ***
aa = 12	bb = 34
sum = 46
*** 終了 ***
2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?