typealias constructors

139 views
Skip to first unread message

Krishna Subramanian

unread,
May 2, 2015, 2:40:16 PM5/2/15
to julia...@googlegroups.com
I would like to know how to do something like this-
typealias Corpus Array{Int,1}

and write a constructor for it. Currently, if I do -

Corpus() = Array(Int,0)

I get-

ERROR: cannot define function Corpus; it already has a value

I am sure others have encountered this problem before. I went through https://github.com/JuliaLang/julia/issues/1470 but I am still not able to figure out what is the issue involved. 

Thanks,
Krishna

Mauro

unread,
May 2, 2015, 2:43:58 PM5/2/15
to julia...@googlegroups.com
You need to be on 0.4 to do this.

Krishna Subramanian

unread,
May 2, 2015, 2:59:34 PM5/2/15
to julia...@googlegroups.com
Sorry for the bother-

I just resolved the issue like this-

import Base.push!
typealias Corpus Array{Int,1}
corpus = Int[]::Corpus
push!(corpus,1)
push!(corpus,2)
@assert typeof(corpus) == Corpus
@assert typeof(corpus) == Array{Int,1}

Thanks,
Krishna

Vincent Lostanlen

unread,
Jul 27, 2015, 1:45:52 PM7/27/15
to julia-users, maur...@runbox.com
Is there a way to make this backwards compatible with latest v0.3 ? I find typealias constructors extremely handy to extend the behavior of existing recursive constructors (LinkedList here).
Here is a minimal use case requiring DataStructures and Compat:

immutable Literal
    symbol::Symbol
    level::Int
end
typealias SymbolInt @compat(Tuple{Symbol,Int})
Literal(tup::SymbolInt) = Literal(tup[1], tup[2])
Literal(sym::Symbol) = Literal(sym, 1)

typealias MyList LinkedList{Literal}
MyList() = nil(Literal)
MyList(head::Literal, tail...) = cons(head, VariableKey(tail...))
MyList(head::Union(SymbolInt,Symbol), tail...) = cons(Literal(head), VariableKey(tail...))

On v0.4, this code makes the MyList type a synonym of LinkedList{Literal}, without having to explicitly construct a Literal object for every element in the list a priori.
What can I do ?

Vincent.

Vincent Lostanlen

unread,
Jul 28, 2015, 3:30:32 AM7/28/15
to julia-users, vincent....@gmail.com
Errata : here is a MWE that actually works.



immutable Literal
    symbol::Symbol
    level::Int
end
typealias SymbolInt @compat(Tuple{Symbol,Int})
Literal(tup::SymbolInt) = Literal(tup[1], tup[2])
Literal(sym::Symbol) = Literal(sym, 1)

typealias MyList LinkedList{Literal}
MyList() = nil(Literal)
MyList(head, tail...) = cons(Literal(head), MyList(tail...))



After running this on v0.4, MyList(:a, (:b, 2)) yields
list(Literal(:a,1), Literal(:b,2))
which is exactly what I want: a list of Literals that support mixed syntax for element construction.
Is it possible to do this on prior versions ?

Vincent.
Reply all
Reply to author
Forward
0 new messages