ここまでのあらまし
まだまだ四則演算に毛が生えた程度ですが、今回は等差数列を用いてモジュール化と実装を行います!
等差数列
a=初項 d=公差 等差数列のn個めの項の大きさは
a+(n-1)*d
となります。
詳しくはこちら
モジュール化、関数定義
lib/progression/arithmetic_progression.ex
defmodule ArithmeticProgression do
def calc(a,d,n) do
a + (n - 1) * d
end
end
適当なディレクトリでPJを作成したあと、
mix new progression
手で以上のディレクトリとファイルを作成します。
その後
iex -S mix
おっとここでわたしは2回のエラーに阻まれました。
ひとつめ
unexpected parentheses. If you are making a function call, do not insert spaces between the function name and the opening parenthes. ~~
予測していないカッコ。
関数呼び出しを作ろうとしてるなら、関数と最初のカッコのあいだにスペースを入れないでね。
的な感じで訳しました。calcと(のあいだにスペースあいてるじゃん〜
もう一度コンパイルも、エラー。
warning: variable "d" does not exist and is being expanded to "d()", please use parentheses to remove the ambiguity or change the variable name
lib/progression/arithmetic_progression.ex:3
warning: variable "b" is unused (if the variable is not meant to be used, prefix it with an underscore)
lib/progression/arithmetic_progression.ex:2
正確にはどのように訳していったのか失念しましたがどうもdとbまわりでなにかが...あっdを使うところbにしてた、というふうに解決しました。
ターミナルで関数を呼び出します。
iex(1)> ArithmeticProgression.calc(3,6,2)
9
やった!これは初項3の公差6の2個目の項の大きさですね。
編集後記
またなんとか自分のつくったPJを動かすことができた!
ここからスピードアップしていきたいです。
うまずたゆまず、頑張ります。
Kento Mizuno