Skip to content

Commit

Permalink
Merge pull request #29 from shashi/nullable
Browse files Browse the repository at this point in the history
Add Nullable{T}
  • Loading branch information
shashi committed Mar 1, 2015
2 parents 94423b4 + b62c3c3 commit b1d654a
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ Currently, the `@compat` macro supports the following syntaxes:

* `Dict(ks, vs)` is now `Dict(zip(ks, vs))` [#8521](https://github.com/JuliaLang/julia/pull/8521)

## Nullable type
* [`Nullable` types](http://julia.readthedocs.org/en/latest/manual/types/?highlight=nullable#nullable-types-representing-missing-values) and their associated operations.

## Developer tips

If you're adding additional compatibility code to this package, the following shell script is useful for extracting the version number from a git commit SHA:
Expand Down
4 changes: 4 additions & 0 deletions src/Compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -173,4 +173,8 @@ end

export @compat, @inline, @noinline

if VERSION < v"0.4.0-dev+656"
include("nullable.jl")
end

end # module
63 changes: 63 additions & 0 deletions src/nullable.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import Base: eltype, convert, get, isequal, ==, hash, show
export Nullable, NullException, isnull

immutable Nullable{T}
isnull::Bool
value::T

Nullable() = new(true)
Nullable(value::T) = new(false, value)
end

immutable NullException <: Exception
end

Nullable{T}(value::T) = Nullable{T}(value)
Nullable() = Nullable{Union()}()

eltype{T}(::Type{Nullable{T}}) = T

function convert{T}(::Type{Nullable{T}}, x::Nullable)
return isnull(x) ? Nullable{T}() : Nullable{T}(convert(T, get(x)))
end

convert{T}(::Type{Nullable{T}}, x::T) = Nullable{T}(x)

convert{T}(::Type{Nullable{T}}, ::Void) = Nullable{T}()
convert( ::Type{Nullable }, ::Void) = Nullable{Union()}()

function show{T}(io::IO, x::Nullable{T})
if x.isnull
@printf(io, "Nullable{%s}()", repr(T))
else
@printf(io, "Nullable(%s)", repr(x.value))
end
end

get(x::Nullable) = x.isnull ? throw(NullException()) : x.value

get{T}(x::Nullable{T}, y) = x.isnull ? convert(T, y) : x.value

isnull(x::Nullable) = x.isnull

function isequal(x::Nullable, y::Nullable)
if x.isnull && y.isnull
return true
elseif x.isnull || y.isnull
return false
else
return isequal(x.value, y.value)
end
end

==(x::Nullable, y::Nullable) = throw(NullException())

const nullablehash_seed = UInt === UInt64 ? 0x932e0143e51d0171 : 0xe51d0171

function hash(x::Nullable, h::UInt)
if x.isnull
return h + nullablehash_seed
else
return hash(x.value, h + nullablehash_seed)
end
end

0 comments on commit b1d654a

Please sign in to comment.