How to check the type of variability

Is there a way to check if a type is mutable or immutable? Can this check be performed at compile time (i.e. have if ismutable(T) branches compiled to just use the encoding for mutability or immutability)?

+6
source share
1 answer

DataTypes have a mutable field, so you can define is_mutable and is_immutable using this, since doing this instead of directly accessing this field is more Julian.

Using Julia version 0.5.0 :

  _ _ _ _(_)_ | By greedy hackers for greedy hackers. (_) | (_) (_) | Documentation: http://docs.julialang.org _ _ _| |_ __ _ | Type "?help" for help. | | | | | | |/ _' | | | | |_| | | | (_| | | Version 0.5.0 (2016-09-19 18:14 UTC) _/ |\__'_|_|_|\__'_| | Official http://julialang.org/ release |__/ | x86_64-w64-mingw32 

 julia> DataType. # <TAB> to auto complete abstract hastypevars instance layout llvm::StructType name parameters super uid depth haswildcard isleaftype llvm::DIType mutable ninitialized size types julia> is_mutable(x::DataType) = x.mutable is_mutable (generic function with 1 method) julia> is_mutable(x) = is_mutable(typeof(x)) is_mutable (generic function with 2 methods) julia> is_immutable(x) = !is_mutable(x) is_immutable (generic function with 1 method) 

Create type and immutable and instances for both of them:

 julia> type Foo end julia> f = Foo() Foo() julia> immutable Bar end julia> b = Bar() Bar() 

Check for variability:

 julia> is_mutable(Foo), is_mutable(f) (true,true) julia> is_mutable(Bar), is_mutable(b) (false,false) 

Check for immutability:

 julia> is_immutable(Foo), is_immutable(f) (false,false) julia> is_immutable(Bar), is_immutable(b) (true,true) 

For performance, also consider declaring these functions as @pure :

 Base.@pure is_mutable(x::DataType) = x.mutable 
+9
source

Source: https://habr.com/ru/post/1012506/


All Articles