“s***"的“平面地图"在哪里?Scala中的惯用语从何而来? [英] Where does the "flatmap that s***" idiomatic expression in Scala come from?

查看:34
本文介绍了“s***"的“平面地图"在哪里?Scala中的惯用语从何而来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

flatmap 有什么强大之处,值得在 Scala 民间传说中占有一席之地?

What is so powerful about flatmap that it deserves such a place in the Scala folklore?

推荐答案

这句话背后的原因是,你可以用调用 flatMap(和其他高阶函数)来替换大量繁琐的 if/then/else 代码).

The reasoning behind this phrase is that you can replace a lot of tedious if/then/else code you would write with calls to flatMap (and other higher order functions).

对于选项尤其如此(参见 http://tonymorris.github.io/blog/posts/scalaoption-cheat-sheet/)

This is especially true for Options (see http://tonymorris.github.io/blog/posts/scalaoption-cheat-sheet/)

但它也适用于其他 monad(虽然我不得不承认,我自己还没有完全理解细节)

But it applies to other monads as well (although I have to admit, I don't exactly understand the details yet myself)

想象一下,您有一个集合,您想为其应用一个函数(或一系列函数),其中每个函数都可能返回 null.当您实际使用 null 时,您的代码将充斥着 null 检查.但是,如果您使用选项而不是值,则可以使用所需的函数对值进行平面映射,在多个函数的情况下链接函数并获得仅包含不为空的结果的集合,这在许多情况下正是你要.

Imagine the situation where you have a collection for which you want to apply a function (or a series of functions) where each function might return null. When you actually use null you code will be riddled with null checks. But if you use Options instead of values, you can just flatmap the values with the desired functions, chaining the functions in the case of multiple functions and get a collection with just the results that aren't null, which in many cases is exactly what you want.

由于该描述相当复杂,因此较短的建议只是平面地图那该死的东西"成立了.

Since that description is rather convoluted the shorter advice "just flatmap that shit" established itself.

这篇关于“s***"的“平面地图"在哪里?Scala中的惯用语从何而来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆