1
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?

Crystal で Int32 や Float64 など数値をまとめて引数に取る場合

Posted at

タイトルの通りです。
Rubyのような動的言語だといい感じに数値を処理してくれるので、Crystalでどのすればいいか案外たどり着かないと思って記事化しました。

オーバーロード

まずは、大前提としてのオーバーロードです。
型によって条件分岐が発生するときはこれがベストでしょう。

def your_method(x : Int32)
end

def your_method(x : Int64)
end

def your_method(x : Float32)
end

def your_method(x : Float64)
end

IntFloat

整数と浮動小数点をまとめて引数に取りたい場合は、IntFloat が使えます。

def your_method(x : Int)
  @x = x.to_i64
end

def your_method(x : Float)
  @x = x.to_f64
end

Number - 整数も、浮動小数点数もすべて引数に取る

def your_method(x : Number)
  @x = x.to_i32 # 例
end

これで任意の型の数値を取ることができます。

BigDecimalBigFloat を引数に取りたい場合

このほかに特殊な型として BigDecimal BigFloat があります。これらは、Numberを継承しません。なのでこれらを Number と一緒に扱う場合はオーバーロードが必要です。

BigDecimalが十進数の計算に適しておりCrystalで実装されているのに対して、BigFloatはGMPを内部で利用しており任意制度の二進浮動小数点の計算に向いているそうです。金融計算ではBigDecimal、科学計算ではBigFloatを使うといいみたいですね。

Crystalの数値型のまとめ

  • Number (抽象基底型)
    • Int (整数の抽象基底型)
      • Int8, Int16, Int32, Int64, Int128
      • UInt8, UInt16, UInt32, UInt64, UInt128
    • Float (浮動小数点の抽象基底型)
      • Float32, Float64

BigDecimalBigFloatは独立した型として定義されており、Numberを継承しない。


この記事は以上です。

1
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
1
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?