gpt4 book ai didi

具有部分默认值的 Julia-lang 构造函数

转载 作者:行者123 更新时间:2023-12-05 01:25:00 29 4
gpt4 key购买 nike

我是 Julia 的新手,这是一种令人兴奋的语言。我只是遇到一些奇怪的行为,我无法在网上找到解释。感谢您的帮助。

    versioninfo()
Julia Version 0.4.0

Commit 0ff703b* (2015-10-08 06:20 UTC)
Platform Info:
System: Darwin (x86_64-apple-darwin13.4.0)
CPU: Intel(R) Core(TM) i5-4258U CPU @ 2.40GHz
WORD_SIZE: 64
BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell)
LAPACK: libopenblas64_
LIBM: libopenlibm
LLVM: libLLVM-3.3

我定义了一个结构

type mytype
x :: UInt8
y :: UInt8
mytype(n::UInt8) = new(n, 0)
end

该类型包含一个构造函数,该构造函数对一个字段具有默认值并为另一个字段获取输入。然后我测试一下

 mytype(1)

LoadError: MethodError: `convert` has no method matching convert(::Type{mytype}, ::Int64)
This may have arisen from a call to the constructor mytype(...),
since type constructors fall back to convert methods.
Closest candidates are:
call{T}(::Type{T}, ::Any)
convert{T}(::Type{T}, !Matched::T)
mytype(!Matched::UInt8)
while loading In[56], in expression starting on line 1

in call at essentials.jl:56

错误信息很乱,看不懂。我测试过,如果我为两个参数提供默认值或接受两个输入,代码运行良好。

谢谢。

最佳答案

我明白了

julia> mytype(1)
ERROR: MethodError: `convert` has no method matching convert(::Type{mytype}, ::Int64)
This may have arisen from a call to the constructor mytype(...),
since type constructors fall back to convert methods.
Closest candidates are:
call{T}(::Type{T}, ::Any)
convert{T}(::Type{T}, ::T)
mytype(::UInt8)
in call at essentials.jl:56

为了分解它,它说它试图调用构造函数,但没有匹配的构造函数。为什么没有构造函数匹配?因为没有定义从 Int64(1)到 UInt8 的自动转换。

然后它尝试将 convertInt64 转换为 mytype,但该方法也未定义。然后它放弃了,并显示了最接近它最初尝试的东西 (mytype(::Int64))。

你可能想提供额外的方法来处理这个问题,或者在你的构造函数中接受任何整数并使用 convert 将它强制为 UInt8 - 如果失败,它'会抛出异常:

julia> type mynewtype
x :: UInt8
y :: UInt8
mynewtype(n::Integer) = new(n, 0)
end

julia> mynewtype(5)
mynewtype(0x05,0x00)

关于具有部分默认值的 Julia-lang 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425600/

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