reduce函数_快速创建自己的reduce函数

reduce函数

Reduce makes an Array a single function that is it combines all of the given elements in an array and outputs a single value (more on that in a minute) — according to the function we give it.

Reduce使数组成为单个函数,即它根据数组给出的函数将数组中所有给定的元素组合在一起并输出一个值(一分钟内会得到更多的值)。

How is that implemented? What do we do?

如何实施? 我们做什么?

Difficulty: Beginner | Easy | Normal | Challenging

难度:初学者| 简单 | 普通 | 具有挑战性的

先决条件: (Prerequisites:)

术语 (Terminology)

Array: An ordered series of objects which are the same type

数组:相同类型的对象的有序序列

Dictionary: The association between keys and values (where all the keys are of the same type, and all values are of the same type)

字典:键和值之间的关联(其中所有键都属于同一类型,并且所有值都属于同一类型)

Reduce: A higher-order function that returns the result of combining the elements of a sequence using a closure

Reduce:一种高阶函数,返回使用闭包组合序列的元素的结果

动机 (The Motivation)

Reduce is one of the coolest higher — order functions available to us in Swift.

Reduce是最酷的高级功能之一-Swift中可用的订购函数。

What if we could look about how reduce works under the hood, and perhaps mangle the functionality to be…whatever we would want it to be.

如果我们可以看看reduce如何在后台运行,并且可能破坏了功能……无论我们想要什么。

归约功能 (The reduce function)

原本的 (The original)

The classic, canonical use is to use reduce to perhaps sum an Array

经典的规范用法是使用reduce或求和 Array

var arr = [1,2,3,4]
arr.reduce(0, {$0 + $1}) //10

This is, of course, using lots of magic from Swift’s type inference. The longer version (for the same array arr) does have the same result

当然,这是使用Swift的类型推断中的许多魔术。 较长的版本(对于相同的数组 arr )确实具有相同的结果

arr.reduce(0, { sum, newVal inreturn sum + newVal
}) // 10

which makes it slightly easier to read for beginners, and slightly more tricky for the more experienced (you can’t win).

对于初学者来说,阅读起来会稍微容易一些;对于经验丰富的用户,这会变得有些棘手(您无法取胜)。

There are variations on uses for the reduce function. Although Reduce works on any array it doesn’t have to return an Integer (like the example above) but can return other types.

reduce函数的用法有所不同。 尽管Reduce可以在任何数组上使用,但它不必返回Integer(如上面的示例),但是可以返回其他类型。

What about returning a String to concatenate an array?

返回字符串以连接数组怎么办?

var names = ["James", "Ahemed", "Kim"]
names.reduce("", {$0 + $1})

This version of reduce just concatenates the array of Strings.

该版本的reduce只是连接字符串array

原始:使用减少计数频率 (The original: using reduce to count frequencies)

It might not seem amazing to perform the above functions with reduce, but reduce is more flexible than that!

reduce来执行上述功能似乎并不令人惊奇,但是reduce比这更灵活!

The documentation gives us something to go on here. reduce(_:_:) has a declaration :

文档为我们提供了一些要继续的内容。 reduce(_:_:)有一个声明:

func reduce<Result>(_ initialResult: Result, _nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

Notice the generic Result here: This can be any time. This means…it can be…a value, an array, or in the case of this example: A dictionary.

注意此处的一般结果:这可以随时。 这意味着……它可以是……一个值,一个数组 ,或者在本例中为:一个dictionary

We can take an array of fruits:

我们可以吃很多fruits

var fruits = ["banana", "cherry", "orange", "apple", "cherry", "orange", "apple", "banana", "cherry", "orange", "fig"]

with which we are going to return a dictionary

我们将用它返回字典

fruits.reduce([:] as! [String: Int], {
a, b in
var c: [String:Int] = a
c[b, default: 0] += 1
return c
})

Although there is some tricky type casting going on, we can see that we have reduced the array down to a dictionary. This results in the following dictionary

尽管正在进行一些棘手的类型转换,但可以看到我们已将数组简化为字典。 这导致以下字典

["cherry": 3, "fig": 1, "apple": 2, "banana": 2, "orange": 3]

我们自己的reduce功能 (Our own reduce function)

We can set up a function to, well reduce. The idea of this is to reproduce the in-built function.

我们可以设置一个函数来,很好地reduce 。 这样的想法是重现内置功能。

一个简单的减少功能 (A simple reduce function)

This function is called (as shown above) with the following reduce(elements: test, initialResult: “”, nextPartialResult: {$0 + $1})

调用此函数(如上所示),并使用以下reduce(elements: test, initialResult: “”, nextPartialResult: {$0 + $1})

扩展中的reduce函数 (A reduce function in an extension)

The tests

测试

Let’s do this properly. Before writing this function, what do we expect it to do and what results do we expect it to give?

让我们正确地做这件事。 在编写此函数之前,我们期望它做什么以及期望得到什么结果?

That is, we need to write some Unit Tests.

也就是说,我们需要编写一些单元测试。

We can initially check the existing reduce function against these tests if this didn’t work I’d be very surprised (don’t worry, it does).

如果没有奏效,我们可以首先对这些测试检查现有的reduce函数,我会非常惊讶(不要担心,它确实可以)。

These tests are not complete, they are a rather basic suite to check if the extension performs as the original reduce (for production code more tests would be required to ensure that the function really does work as intended).

这些测试尚未完成,它们是一个相当基本的套件,用于检查扩展是否按原始的reduce执行(对于生产代码,将需要进行更多测试,以确保该功能确实按预期工作)。

so we wish to create a new reduce function (myReduce) that operates the same way, that is on an array.

因此我们希望创建一个新的reduce函数(myReduce),该函数以相同的方式操作,即在数组上。

This sounds like an extension to me.

这听起来像是我的延伸。

The extension

扩展名

To understand this you will need some experience of iterators in Swift, and remember this is going to be called myReduce to match with the tests above.

为了理解这一点,您将需要一些Swift 迭代器的经验,并记住这将被称为myReduce以与上面的测试相匹配。

myReduce is a generic function. This takes an initialResult and a nextPartialResult function in order to create a result of the type (generic) Result.

myReduce是通用函数。 这需要一个initialResultnextPartialResult函数,以创建(通用) Result类型的Result

The initial result (of type Result) is set to the initial result (which is fine, since the function nextPartialResult has not yet been applied to any element of the input Array).

初始结果(类型为Result )被设置为初始结果(这很好,因为函数nextPartialResult尚未应用于输入Array的任何元素)。

Entering a while loop with iterator.next(), which uses a while let in Swift (so only runs if iterator.next() is not nil) and uses try to run the nextPartialResult on the result and the nextElement which is then assigned to be the result.

进入while循环与iterator.next()它采用了while let在斯威夫特(因此只运行,如果iterator.next()不是零),并使用尝试运行nextPartialResultresultnextElement ,然后将其分配给是result

TO test this within the playground the ReduceTests.defaultTestSuite.run() runs the (3 tests) — which all pass!

为了在操场上进行测试, ReduceTests.defaultTestSuite.run()运行(3个测试)—全部通过!

Joy!

喜悦!

结论 (Conclusion)

The reduce function is fun!

reduce功能很有趣!

Being aware that the reduce function can return more than a single value puts you ahead of most developers, but if you can code your own and think about how it really works underneath the hood you are doing extremely well.

意识到reduce函数可以返回的值不止一个值,这使您领先于大多数开发人员,但是如果您可以自己编写代码,并考虑一下它在幕后的工作原理,那么您做得非常好。

This guide has taken you through just that, giving you some idea of reduce and how you can implement your own even including some testing.

本指南仅对您进行了介绍,使您对reduce有了一些了解,甚至可以进行一些测试来实现自己的方法。

I hope this has been an enjoyable article, and I hope to see you on the otherside.

我希望这是一篇愉快的文章,也希望能在另一方面看到您。

扩展您的知识 (Extend your knowledge)

Twitter联系人: (The Twitter contact:)

Any questions? You can get in touch with me HERE

任何问题? 您可以在这里与我联系

翻译自: https://medium.com/@stevenpcurtis.sc/create-your-own-reduce-function-in-swift-e92b519c9659

reduce函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值