Creating an analogue of Haskell. Any type in Julia

I want to create an analogue of the Data.Either type from Haskell to Julia. In v0.5, the following works:

 immutable Either{T, S} left :: Nullable{T} right :: Nullable{S} end either{T, S}(::Type{T}, ::Type{S}, value::T) = Either(Nullable{T}(value), Nullable{S}()) either{T, S}(::Type{T}, ::Type{S}, value::S) = Either(Nullable{T}(), Nullable{S}(value)) a = either(Int64, String, 1) b = either(Int64, String, "a") println(a) println(b) 

My question is: is it possible to perform the following constructions:

 a = Either{Int64, String}(1) b = Either{Int64, String}("a") 

(thus, an additional constructor function is not required).

There seems to be enough information to create the object, but so far I have not been able to convince the compiler to accept any of the options I tried; e.g. writing

 immutable Either{T, S} left :: Nullable{T} right :: Nullable{S} Either(value::T) = Either(Nullable{T}(value), Nullable{S}()) Either(value::S) = Either(Nullable{T}(), Nullable{S}(value)) end 

leads to

 ERROR: LoadError: MethodError: no method matching Either{T,S}(::Nullable{Int64}, ::Nullable{String}) 
+7
julia-lang
source share
1 answer

I seem to have forgotten that the default constructor is called with new . This option works:

 immutable Either{T, S} left :: Nullable{T} right :: Nullable{S} Either(value::T) = new(Nullable{T}(value), Nullable{S}()) Either(value::S) = new(Nullable{T}(), Nullable{S}(value)) end a = Either{Int64, String}(1) b = Either{Int64, String}("a") println(a) println(b) 

In addition, since the default constructor is not displayed, you cannot create an object with two nonzero values, so the invariant is forcibly executed.

+8
source share

All Articles