Julia:函数的偶数数据类型 [英] Julia: Even-number datatype for functions
问题描述
我有大约50个函数,它们应该只使用偶数.现在,我每次都用"if"检查是否输入的数字是否为零:
I have about 50 functions which should consume only even positive numbers. Right now I am checking each time with an "if" whether the number put in is zero or not:
function grof(x::Int)
if (x % 2) == 0
println("good")
else
throw("x is not an even number!!!!!!!!!!!!! Stupid programmer!")
end
end
理想情况下,我希望有一个数据类型可以自动生成此数据,即
Ideally, I would like to have a datatype which produces this automatically, i.e.
function grof(x::EvenInt)
println("good")
end
但是,由于我无法理解纪录片.感谢您的帮助!
However, I am not able to produce this datatype by my own since I am unable to understand the documentary. Thanks for your help!
最佳,v.
推荐答案
I don't think creating a type is warranted in such a situation: I would simply @assert
that the condition is verified at the beginning of the function(s). (Funnily enough, checking the whether a number is even is the example that was chosen in the documentation to illustrate the effect of @assert
)
例如:
julia> function grof(x::Int)
@assert iseven(x) "Stupid programmer!"
println("good")
end
grof (generic function with 1 method)
julia> grof(2)
good
julia> grof(3)
ERROR: AssertionError: Stupid programmer!
Stacktrace:
[1] grof(::Int64) at ./REPL[5]:2
[2] top-level scope at REPL[7]:1
如果您确实要创建一个强制执行此类约束的类型,则可以.做到这一点的方法是
If you really want to create a type enforcing such a constraint, it is possible. The way to do this would be to
- 创建一个类型(可能是
Number
抽象类型之一的子类型;也许是Signed
) - 定义一个内部构造函数,以确保此类类型不能包含奇数
- create a type (possibly subtyping one of the
Number
abstract types; maybeSigned
) - define an inner constructor ensuring that such a type cannot hold an odd value
一个非常简单的示例将基于以下内容:
A very simple example to build upon would be along the lines of:
# A wrapper around an even integer value
struct EvenInt
val :: Int
# inner constructor
function EvenInt(val)
@assert iseven(val)
new(val)
end
end
# Accessor to the value of an EvenInt
val(x::EvenInt) = x.val
# A method working only on even numbers
grof(x::EvenInt) = println("good: $(val(x)) is even")
您将这样使用:
julia> x = EvenInt(42)
EvenInt(42)
julia> grof(x)
good: 42 is even
julia> y = EvenInt(1)
ERROR: AssertionError: iseven(val)
Stacktrace:
[1] EvenInt(::Int64) at ./REPL[1]:5
[2] top-level scope at REPL[6]:1
,但请注意,您还不能在EvenInt
上执行任何操作:您需要解开它们(在这种情况下使用val()
),或者对它们进行定义操作(如果您将其大大简化,则可以轻松完成此任务)将EvenInt
设为抽象数字类型之一的子类型,并遵循相关的界面.
but note that you can't do anything on EvenInt
s yet: you need to either unwrap them (using val()
in this case), or define operations on them (a task which can be vastly simplified if you make EvenInt
a subtype of one of the abstract number types and follow the relevant interface).
这篇关于Julia:函数的偶数数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!