How to design a new data type like Complex


I want to design a new data type that acts like Complex. What’s amazing is that by the identifier “im”, Julia compiler could recognize for example 1+1im as a complex number. That looks like a special form of struct to me.

My need comes from usage habit of people in some specific fields. For example in electricity, people use “L” to denote a inductor and “C” to denote a capacitor. In osscasions that they use these symbols a lot, type in “1e-9L” to denote a inductor that has value=1e-9 is certainly more convenient than input “Inductor(1e-9)”, if the struct Inductor is defined.

I have no idea how to google this. Thank you for any help or hint.

Yes, you can do this yourself. There’s no special parsing for im, so you can create your own notation L and C.

The best way to get started is probably looking at the source of complex. Try typing

jl> @edit complex(0, 1)

to see the source.


Thank you very much! That’s exactly what I need.

Yes, thanks, but this throws an error here:

julia> @edit complex(0, 1)
ERROR: IOError: could not spawn `code -g 'C:\Users\xxx\AppData\Local\Programs\Julia-1.7.0-rc1\share\julia\base\complex.jl:171'`: no such file or directory (ENOENT)
  [1] _spawn_primitive(file::String, cmd::Cmd, stdio::Vector{Any})
    @ Base .\process.jl:100
  [2] #690
    @ .\process.jl:113 [inlined]
  [3] setup_stdios(f::Base.var"#690#691"{Cmd}, stdios::Vector{Any})
    @ Base .\process.jl:197
  [4] _spawn
    @ .\process.jl:112 [inlined]
  [5] _spawn(::Base.CmdRedirect, ::Vector{Any})
    @ Base .\process.jl:140
  [6] run(::Base.CmdRedirect; wait::Bool)
    @ Base .\process.jl:449
  [7] (::InteractiveUtils.var"#2#3"{Bool, InteractiveUtils.var"#11#21", Vector{String}})(cmd::Cmd, path::String, line::Int32)
    @ InteractiveUtils C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.7\InteractiveUtils\src\editless.jl:98
  [8] edit(path::String, line::Int32)
    @ InteractiveUtils C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.7\InteractiveUtils\src\editless.jl:205
  [9] edit(f::Any, t::Any)
    @ InteractiveUtils C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.7\InteractiveUtils\src\editless.jl:234
 [10] top-level scope
    @ REPL[57]:1

complex.jl exists in


Opened another thread.

There’s really nothing special about im. It’s literally just defined as Complex(false, true):

In addition to what @simeonschaub said, the extra piece of information is that Julia allows you to write 3im and get 3 * im. This works for any variable name, so im is not special:

julia> x = 2

julia> 3x
1 Like

That’s right, I looked into the source code and found this as well. Thanks :slight_smile:

You might want to check out as well.

1 Like

That seems to be an ideal solution, I think I’ll switch my code to Unitful.jl at some point.