如何将javascript reduce()转换为Swift 2
How would you translate javascript reduce() to Swift 2?
…提供了js reduce(),采用如下三参数函数?
var relevance = _(s.words).reduce( function (memo, freq, w) {
var local = Math.log( 1 + freq );
var global = Math.log( N / containing(w).length );
return memo = memo + (local * global);
}, 0);
到目前为止,我想到了:
let relevance = s.words.reduce(0) {
(memo, freq, w) in
var local = log( 1 + freq )
var global = log( N / containing(w).length )
return memo = memo + (local * global)
} // ~reduce()
但是,由于参数数量不匹配,reduce()无法编译。
知道吗?
您可以使用reduce函数,如下所示:
[1, 3, 5].reduce(0) { previousValue, arrayValue in
return previousValue + arrayValue
}
// returns 9
在您的情况下,您可以通过调用enumerate:来获得值的索引
// indexValue is of type (index: Int, element: Int)
[1, 3, 5].enumerate().reduce(0) { previousValue, indexValue in
// access index
indexValue.index
// access value
indexValue.element
return previousValue + indexValue.element
}
// returns also 9
您的代码:
let relevance = s.words.enumerate().reduce(0) {
(memo, freqW) in
let freq = Double(freqW.index)
let w = freqW.element
// use let if you don't modify the value
let local = log( 1 + freq )
// you probably need to convert some of the variables to Double
let global = log( N / containing(w).length )
// in the next iteration memo will be this returned value
return memo + (local * global)
}
相关文章:
- 如何在JavaScript中将字符串转换为函数引用
- 如何在Javascript中将JSon对象转换为数组
- 使用JS将数组转换为json对象
- 如何使用json将对象列表从java转换为javascript
- 偶尔结结巴巴地说“;堆叠的”;translate()上的转换(v4.0.0-alpha40)
- 为什么在单独的函数中应用时转换会闪烁/断断续续(D3)
- 在Javascript中转换对象数组
- 将数字转换为一定数量的硬币
- 将纯文本URL转换为可单击链接
- 当图像转换为本地存储的DataURL时,EXIF被删除
- 如何使用js将SNAPSHOT内部版本号转换为3位数的整数
- 如何将TypeScript对象转换为普通对象
- 检测个位数整数时正在转换毫秒
- 从javascript到jquery的转换
- DOM事件通过JSON转换为java
- 将圆柱体转换为弯管
- 混合 ui-sref 和 $state.go 在 Angular ui-router 中进行状态转换
- JavaScript代码问题:我正在将对象转换为数组
- 如何将javascript reduce()转换为Swift 2
- 将JSON日期转换为Swift兼容的日期