import std.collection.*
let arr1 = Array<Int64>(9, {i => i + 1})
let arr2 = Array<Int64>(9, {i => i + 1})
arr2.reverse()
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [9, 8, 7, 6, 5, 4, 3, 2, 1]
filter
let arr1_odd_as_string = arr1 |> filter {x => x % 2 == 1} |> collectString<Int64>(delimiter: "-")
println(arr1_odd_as_string)
>>> 1-3-5-7-9
Explanation: `|>` is a pipe operator that feeds the `arr1` array to the filter function, which returns an "Iterator<T>". We use the same pipe operator to feed the iterator to the `collectString` function that concatenates every item of the iterator as a string, using dash `-` as the separator. We optionally specify that the input values are Int64.
contains
println( arr1 |> contains(6) )
>>> true
Explanation: by piping the array to the `contains` function, we check whether it contains a specific element. Returns true or false.
forEach
arr1 |> forEach<Int64>(println)
>>> 1
2
3
...
Explanation: `forEach` applies a given function to every element in the array. Note: the function given to `forEach` can only preform side effects, such as printing, writing to a file, etc. and cannot return values. The following doesn't work:
func square(x: Int64): Unit {
return x * x
}
arr2 |> forEach<Int64>(square) // only for side effects, can't modify the array itself
map
let a = arr1 |> map {x: Int64 => "${x}a"} |> collectArray<String>
println(a)
>>> [1a, 2a, 3a, 4a, 5a, 6a, 7a, 8a, 9a]
Explanation: similar to `forEach` but modifies the array itself. Because `map` returns an iterator, we convert it to an array with the `collectArray` function, specifying that the input values are now of type String.
zip
for (i in arr1 |> zip(arr2)) {
println("${i[0]}, ${i[1]}")
}
Explanation: similar to Python's zip() function, allows you to iterate through two arrays at the same time.
let b = arr1 |> zip(arr2) |> collectArray // can be converted to an array, returns an array of tuples
for ((i, j) in arr1 |> zip(arr2)) {
println("${i}, ${j}")
}
>>> 1, 9
2, 8
3, 7
...
enumerate
for ((e, i) in enumerate(arr1)) {
println("${e}, ${i}")
}
>>> 0, 1
1, 2
2, 3
...
Explanation: returns both the item `i` and its index `e`.
reduce
func sum(x: Int64, y: Int64): Int64 {
return x + y
}
let arrSum = [1, 1, 1] |> reduce(sum)
println(arrSum)
>>> Some(3)
功能:使用第一个元素作为初始值,从左向右计算(函数 - 仓颉语言库 API)。Notice that it returns an Enum. In order to get the actual value, we need to use the `getOrThrow()` method.
import std.math.*
let arrMax = [1, 2, 3] |> reduce(max)
println(arrMax.getOrThrow())
>>> 3
println(arrMax.getOrThrow() * 2)
>>> 6