advice on optional type -- Union or two fields?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

advice on optional type -- Union or two fields?

Tamas Papp
Hi,

I am working on a parsing framework where the parsing functions either
return a parsed value, or in case they could not parse, return a value
that signals this -- similar to Base.tryparse.

Originally I was using a Nullable{T}, but realize that in case I could
not parse then having the raw string would be handy (for running another
parser, reporting an error, etc). There are two alternatives:

# using Union
immutable ParsedField{T, S <: AbstractString}
    isparsed::Bool
    value::Union{T, S}
    ParsedField(string::S) = new(false, string)
    ParsedField(value::T) = new(true, value)
end

and

# using two fields
immutable ParsedField{T, S <: AbstractString}
    isparsed::Bool
    value::T
    raw::S
    function ParsedField(string::S)
        pf = new(false)
        pf.raw = string
        pf
    end
    function ParsedField(value::T)
        pf = new(true)
        pf.value = T
        pf
    end
end

I am leaning towards the "two fields" solution: I can make it type
stable. But I am not sure what the preferred style is.

Also, is there a syntax for new() to skip fields?

Best,

Tamas
Loading...