4
3

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 3 years have passed since last update.

Juliaでのabstract typeの使い方

Posted at

Juliaでは抽象型(Abstract type)というものがあり、これを使うとオブジェクト指向プログラミングでのクラスに似た感じのコーディングができます。具体的にはc++の抽象クラスでの純粋仮想関数みたいになります。

バージョン

Julia 1.6.2

Abstract type

抽象型(Abstract type)を使うには例えば、

module Mysupermodule
    export Mysuperstruct
    abstract type Mysuperstruct end

    function add(A::T,B::T) where T <: Mysuperstruct
        error("add is not implemented for $(typeof(A))")
        return
    end
end

のようなmoduleを作成します。ここで、Mysuperstructにはaddという関数が定義されていますが、これが呼び出されるとerrorで落ちるようにしておきます。

次に、このtypeをsuper typeにもつtypeを

module Mymodule
    import ..Mysupermodule:Mysuperstruct,add

    struct Mystruct <: Mysuperstruct
        a::Float64
    end

    function add(A::T,B::T) where T <: Mystruct 
        return Mystruct(A.a+B.a)
    end
end

と定義します。このようにしておくと、


module Testmodule
    import ..Mysupermodule:Mysuperstruct,add
    import ..Mymodule:Mystruct
    export test

    function test()
        A = Mystruct(2.0)
        B = Mystruct(10.0)

        C = add(A,B)
        println(C.a)

    end

end

using .Testmodule
test()

とした時に、Mystructで定義されているaddが呼び出されます。ここで、importしているのがMysupermoduleaddであることに注意してください。Mystructで動作するaddTestmoduleから呼び出していません。つまり、Mysupermoduleの中にaddが追加されています。Mysupermoduleでできることが増えているわけですね。

もし、addが定義されていないモジュールがあったとすると、

module Hismodule
    import ..Mysupermodule:Mysuperstruct,add

    struct Hisstruct <: Mysuperstruct
        a::Float64
    end

end
module Testmodule
    import ..Mysupermodule:Mysuperstruct,add
    import ..Mymodule:Mystruct
    import ..Hismodule:Hisstruct
    export test

    function test()
        A = Mystruct(2.0)
        B = Mystruct(10.0)

        C = add(A,B)
        println(C.a)

        A = Hisstruct(2.0)
        B = Hisstruct(10.0)

        C = add(A,B)
        println(C.a)
    end

end

を実行した結果は

12.0
ERROR: LoadError: add is not implemented for Main.Hismodule.Hisstruct

となり、addが実装されていない方はエラーで落ちます。

これは、C++での抽象クラスにvirtualを使って定義する「純粋仮想関数」と似た感じです。もう少し似せるならば、

module Mymodule
    import ..Mysupermodule:Mysuperstruct,add

    struct Mystruct <: Mysuperstruct
        a::Float64
    end

    add() = nothing

end

とすると、

ERROR: LoadError: MethodError: no method matching add(::Main.Hismodule.Hisstruct, ::Main.Hismodule.Hisstruct)

となります。どちらがいいかはお好みです。
ここではimportを使って書いていますが、usingを使っても同様の結果になるようです。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?