假设我有一个整数数组,我想得到所有偶数的总和和所有奇数的总和。例如,对于数组 [1,2,3] ,所有奇数之和为4,所有偶数之和为2。
这就是我的做法:
array.reduce((odd: 0, even: 0), { (result, int) in
if int % 2 == 0 {
return (result.odd, result.even + int)
} else {
return (result.odd + int, result.even)
}
})
let (oddSum, evenSum) = a.reduce((odd: 0, even: 0), { (result, int) in
if int % 2 == 0 {
return (result.odd, result.even + int)
} else {
return (result.odd + int, result.even)
}
})
Value of tuple type '(Int, Int)' has no member 'odd'
return声明。(oddSum, evenSum) .(0, 0) ,这使得闭包中的内容非常不可读。我必须将奇数和称为 result.0甚至总和为 result.1 .
最佳答案
TL; DR
这种行为很不幸,但由于以下原因的组合,它“按预期工作”:
Why does deconstructing the tuple cause the generic type to be inferred differently? The deconstruction part should just say what to do to the result. The method call should have been interpreted on its own, and then matched against the pattern
(evenSum, oddSum).
func magic<T>() -> T {
fatalError()
}
let x: Int = magic() // T == Int
T是 Int .let (x, y) = magic() // error: Generic parameter 'T' could not be inferred
let (x, y)有类型 ($T0, $T1) ,其中 $T{N}是一个类型变量。T ,所以约束系统推导出 T可转换为 ($T0, $T1) .但是没有进一步的信息 $T0和 $T1可以绑定(bind)到,所以系统失败。func magic<T>(_ x: T) -> T {
print(T.self)
fatalError()
}
let labelledTuple: (x: Int, y: Int) = (x: 0, y: 0)
let (x, y) = magic(labelledTuple) // T == (Int, Int)
T推断为 (Int, Int) .这怎么发生的?magic类型为 (T) -> T . (x: Int, y: Int) . ($T0, $T1) . T到未标记的元组类型 ($T0, $T1) , 强制类型 (x: Int, y: Int) 的参数执行删除其标签的元组转换。 T到标记的元组类型 (x: Int, y: Int) ,强制返回值执行元组转换,去除其标签,以便可以将其转换为 ($T0, $T1) . T至 ($T0, $T1) ,此时两个 $T0和 $T1可以绑定(bind)到Int由于(x: Int, y: Int)需要可转换为 ($T0, $T1) .func magic<T>(_ x: T) -> T {
print(T.self)
fatalError()
}
let labelledTuple: (x: Int, y: Int) = (x: 0, y: 0)
let tuple = magic(labelledTuple) // T == (x: Int, y: Int)
T现在绑定(bind)到 (x: Int, y: Int) .为什么?因为模式类型现在只是类型 $T0 .T绑定(bind)到 $T0 ,然后 $T0将绑定(bind)到参数类型 (x: Int, y: Int) . T绑定(bind)到 (x: Int, y: Int) ,然后 $T0也将绑定(bind)到 (x: Int, y: Int) . T 的可能性被绑定(bind)到一个未标记的元组类型仅仅是因为首先没有未标记的元组类型被引入到系统中。magic就是 reduce 没有额外的闭包参数: public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (_ partialResult: Result, Element) throws -> Result
) rethrows -> Result
let (oddSum, evenSum) = a.reduce((odd: 0, even: 0), { (result, int) in
if int % 2 == 0 {
return (result.odd, result.even + int)
} else {
return (result.odd + int, result.even)
}
})
Result 选择相同的绑定(bind)。 :Result到未标记的元组类型 ($T0, $T1) , 强制类型 (odd: Int, even: Int) 的参数执行删除其标签的元组转换。 Result到标记的元组类型 (odd: Int, even: Int) ,强制返回值执行元组转换,去除其标签,以便可以将其转换为 ($T0, $T1) . Result至 ($T0, $T1) , 解析为 (Int, Int) .删除元组分解有效,因为您不再引入类型 ($T0, $T1)进入约束系统——意味着Result只能绑定(bind)到(odd: Int, even: Int) ..odd和 .even在元组上,那么为什么约束系统不能弄清楚 Result 的绑定(bind)至 (Int, Int)不可行吗?嗯,这是因为 multiple statement closures don't participate in type inference .这意味着闭包体是独立于对 reduce 的调用而解决的。 ,所以当约束系统意识到绑定(bind)(Int, Int)无效,为时已晚。(Int, Int)作为 Result 的有效绑定(bind):let (oddSum, evenSum) = a.reduce((odd: 0, even: 0), { (result, int) in
return int % 2 == 0 ? (result.odd, result.even + int)
: (result.odd + int, result.even)
})
(odd: $T0, even: $T1) ,这避免了将未标记形式引入约束系统:let (odd: oddSum, even: evenSum) = a.reduce((odd: 0, even: 0), { (result, int) in
if int % 2 == 0 {
return (result.odd, result.even + int)
} else {
return (result.odd + int, result.even)
}
})
let (oddSum, evenSum) = a.reduce((odd: 0, even: 0), { (result: (odd: Int, even: Int), int) in
if int % 2 == 0 {
return (result.odd, result.even + int)
} else {
return (result.odd + int, result.even)
}
})
Result绑定(bind)到(Int, Int)由于模式引入了首选类型 ($T0, $T1) .允许这个例子编译的原因是编译器为传递的闭包插入了一个元组转换,它为其参数重新添加了元组标签。
关于swift - 为什么从reduce的返回值解构元组会导致错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575604/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?
我刚刚被困在这个问题上一段时间了。以这个基地为例:moduleTopclassTestendmoduleFooendend稍后,我可以通过这样做在Foo中定义扩展Test的类:moduleTopmoduleFooclassSomeTest但是,如果我尝试通过使用::指定模块来最小化缩进:moduleTop::FooclassFailure这失败了:NameError:uninitializedconstantTop::Foo::Test这是一个错误,还是仅仅是Ruby解析变量名的方式的逻辑结果? 最佳答案 Isthisabug,or