Seems like you have a good answer already, but for what it’s worth I have
the following code in a package I’m developing:
# Some helpful typealiases to keep things tidy
typealias SymExpr Union(Symbol, Expr)
typealias VecSymExpr Union(Vector{Symbol}, Vector{Expr})
# Take a name and type and return an argument
make_arg(nm::Symbol, typ::SymExpr) = Expr(:(::), nm, typ)
make_arg(nm::Symbol, typ::DataType) = Expr(:(::), nm, :($typ))
# Construct a type_name and correct subtype expression
function type_name(name::Symbol, super::SymExpr)
if super == :Any
return name
else
return Expr(:(<:), name, super)
end
end
# From a name, a vector of fields, and a vector of field types, make an
# expression that defines a new type
function make_type(name::Symbol, fields::Vector{Symbol}, super::SymExpr=:Any,
typs=fill(:Float64, length(fields));
mutable::Bool=false)
fs = map(x->make_arg(x...), zip(fields, typs))
t_name = type_name(name, super)
Expr(:type, mutable, t_name, Expr(:block, fs...))
end
the make_type function can easily be called from within a macro as follows
macro foo(...)
typ = make_type(args...)
# Do other stuff
esc(quote
$(typ)
# return parts of block expression
end)
end
On Monday, March 9, 2015 at 12:44:24 PM UTC-4, Kaj Wiik wrote:
Unfortunately parametric types did not pass through new() correctly
> resulting gibberish. Specifying the type explicitly works fine:
>
> macro gentype(N, typename, fieldtype)
> fields = [:($(symbol("I_$i"))::$(symbol("$fieldtype"))) for i=1
> :N]
> quote
> immutable $(typename)
> $(fields...)
> end
> end
> end
>
> Thanks,
> Kaj
>
>
>
> On Monday, March 9, 2015 at 6:05:10 PM UTC+2, Kaj Wiik wrote:
>>
>>
>>
>> This is more elegant Julian way that I tried to find, thanks!
>>
>> Kaj
>>
>>
>> On Monday, March 9, 2015 at 1:43:14 PM UTC+2, Simon Danisch wrote:
>>>
>>> Hi,
>>> I'm working on FixedSizeArrays, which does pretty much what you have
>>> tried here.
>>> Simplified version from constructors.jl
>>> <https://github.com/SimonDanisch/FixedSizeArrays.jl/blob/master/src/constructors.jl>
>>> :
>>> macro gentype(N, typename)
>>> fields = [:($(symbol("I_$i"))::T) for i=1:N]
>>> quote
>>> immutable $(typename){T}
>>> $(fields...)
>>> end
>>> end
>>> end
>>>
>>>
>>> Am Donnerstag, 5. März 2015 11:02:51 UTC+1 schrieb Kaj Wiik:
>>>>
>>>> I have been trying to write a macro that would generate fields in a
>>>> for-loop.
>>>>
>>>> However, when I try to generate the first line I get an error:
>>>>
>>>> julia> macro deftype(name,artype,num)
>>>> ex1 = :(esc( immutable $name))
>>>> ERROR: syntax: unexpected ")"
>>>>
>>>> julia> macro deftype(name,artype,num)
>>>> ex1 = :(esc(quote immutable $name end))
>>>> ERROR: syntax: extra token ")" after end of expression
>>>>
>>>>
>>>> There must be a way to do this, I cannot find how...
>>>>
>>>> Thanks,
>>>> Kaj
>>>>
>>>>