On Wednesday, December 9, 2015 at 10:01:25 PM UTC+10, milktrader wrote:
>
> Trying to wrap my mind around singleton types to see if they might be 
> useful for something I'm working on, but running into some confusion. Here 
> is an example that I started working with:
>
> julia> type BadInt
>        end
>
> julia> import Base.+
>
> julia> +(x::BadInt, y::Int64) = x - y
> + (generic function with 172 methods)
>
> julia> BadInt() = 2
> BadInt
>

Did not the above re-define BadInt() as a function returning 2 rather than 
the constructor for type BadInt?
 

>
> julia> BadInt + 2
>

As the error says, this is adding a type to an int, which isn't defined, 
not an instance of the singleton to the int as you intended.
 

> ERROR: MethodError: `+` has no method matching +(::Type{BadInt}, ::Int64)
> Closest candidates are:
>   +(::Any, ::Any, ::Any, ::Any...)
>   +(::Int64, ::Int64)
>   +(::Complex{Bool}, ::Real)
>   ...
>
> As I understand, a singleton type can only take on a single value. What's 
> the utility in supporting this?
>

Singletons take on no value, they have a size of zero (see 
http://docs.julialang.org/en/release-0.4/devdocs/object/?highlight=singleton#memory-layout-of-julia-objects).

There is only one instance of a singleton, no matter how often the 
constructor is called.  This is especially useful for parametric 
singletons, see Type{}

Reply via email to