如何简化嵌套地图调用? [英] How to simplify nested map calls?

查看:58
本文介绍了如何简化嵌套地图调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些嵌套函子,例如List[Option[Int]],并且需要调用最内部的map.

Suppose I have a few nested functors, e.g. List[Option[Int]] and need to call the map of the most inner one.

现在我正在使用嵌套的maps:

Now I am using nested maps:

scala> val opts: List[Option[Int]] = List(Some(0), Some(1))
opts: List[Option[Int]] = List(Some(0), Some(1))

scala> opts.map(o => o.map(_ + 1))
res0: List[Option[Int]] = List(Some(1), Some(2))

例如,如果我有3个嵌套级别,该怎么办?
嵌套maps有什么简单的替代方法吗?

What if I have 3 nesting levels, for instance ?
Is there any simple alternative to nested maps ?

推荐答案

是的,使用scalaz.Functor可以实现:

Yes, this is possible with scalaz.Functor:

scala> import scalaz.Functor
import scalaz.Functor

scala> import scalaz.std.list._
import scalaz.std.list._

scala> import scalaz.std.option._
import scalaz.std.option._

scala> Functor[List].compose[Option].map(List(some(0), some(1)))(_ + 1)
res1: List[Option[Int]] = List(Some(1), Some(2))

但是,这比用嵌套的map简单地调用map更长.如果您经常映射嵌套结构,则可以创建辅助函数:

However, this is longer than to simply call map with a nested map. If you often map nested structures, you can create helper functions:

def map2[F[_], G[_], A, B](fg: F[G[A]])(f: A => B)
  (implicit F0: Functor[F], G0: Functor[G]): F[G[B]] =
  F0.map(fg)(g => G0.map(g)(f))

def map3[F[_], G[_], H[_], A, B](fg: F[G[H[A]]])(f: A => B)
  (implicit F0: Functor[F], G0: Functor[G], H0: Functor[H]): F[G[H[B]]] =
  F0.map(fg)(g => G0.map(g)(h => H0.map(h)(f)))

...

用法:

scala> map2(List(some(0), some(1)))(_ + 1)
res3: List[Option[Int]] = List(Some(1), Some(2))

scala> map3(List(some(some(0)), some(some(1))))(_ + 1)
res4: List[Option[Option[Int]]] = List(Some(Some(1)), Some(Some(2)))

这篇关于如何简化嵌套地图调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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