gpt4 book ai didi

julia - Julia 的代码生成

转载 作者:行者123 更新时间:2023-12-04 20:42:40 25 4
gpt4 key购买 nike

我想为自己的类型覆盖默认的字符串方法(因为我发现它们很丑陋)。

此函数将用于生成字符串

function prettyPrint(value::Any)
names::Vector{Symbol} = fieldnames(value)
nameCount::Int64 = length(names)
stringBuilder::IOBuffer = IOBuffer()
print(stringBuilder, string(typeof(value).name) *"(")
for (index, name) in enumerate(names)
print(stringBuilder, string(name) * "=" * string(getfield(value, name)))
if index != nameCount
print(stringBuilder, ", ")
end
end
print(stringBuilder, ")")
takebuf_string(stringBuilder)
end


让我们定义一个样本类型

type Foo
a::Int64
b::String
c::Float64
end


然后我尝试使用这段代码生成字符串函数

import Base.string

for dataType in (:Foo)
eval(quote
function string(dt::$dataType)
prettyPrint(dt)
end
end)
end

foo = Foo(1, "2", 3.0)
println(string(foo))


这将崩溃,并显示一条冗长的错误消息,告诉我我无法使用。

ERROR: LoadError: MethodError: no method matching start(::Symbol)
Closest candidates are:
start(!Matched::SimpleVector) at essentials.jl:170
start(!Matched::Base.MethodList) at reflection.jl:258
start(!Matched::IntSet) at intset.jl:184
...
in anonymous at .\<missing>:?
in include_from_node1(::String) at .\loading.jl:488
in process_options(::Base.JLOptions) at .\client.jl:265
in _start() at .\client.jl:321
while loading ~\codegeneration.jl, in expression starting on line 24


第24行是“(:Foo)中的dataType”行。

老实说,我希望将此功能作为宏使用,但我什至看不到如何实现。

macro PrettyPrint(someType)
? someType is an expression, how do I get to the type
? how do I even know what part of the expression is the type

end
@PrettyPrint type Foo
a::Int64 ... end

最佳答案

您收到的错误消息是因为(:Foo) == :Foo。我认为您想要一个元组进行迭代,因此您需要(:Foo,)。也就是说,eval不是首选的方法。

如果你这样做

function Base.show(io::IO, dt::Foo)
print(io,prettyprint(dt))
end


它将更改repl中的默认打印,并且您可以使用 repr获得字符串版本。

关于julia - Julia 的代码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43871755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com