Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a type for mutability

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

like image 648
Chris Rackauckas Avatar asked Nov 20 '16 17:11

Chris Rackauckas


1 Answers

DataTypes have a mutable field, so you can define is_mutable and is_immutable using that, since doing that instead of accessing that field directly 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 a type and an 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 mutability:

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
like image 187
HarmonicaMuse Avatar answered Nov 04 '22 11:11

HarmonicaMuse