实现List#flatMap [英] Implementing List#flatMap
本文介绍了实现List#flatMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更好的函数写法 flatMap
?
def flatMap [A,B](list:List [A])(f:A => List [B]):List [B] =
list.map(x => f(x)) .flatten
从概念上讲,我明白 flatMap
in条款 flatten
。
解决方案
另一种方法:
<$ c (列表:列表[A])(f:A =>列表[B]):列表[B] =
list.foldLeft(List [B] )(_ ++ f(_))
我不知道更好。 (如果我们开始谈论高效实施,这是另一种蠕虫......)
Is there a better functional way to write flatMap
?
def flatMap[A,B](list: List[A])(f: A => List[B]): List[B] =
list.map(x => f(x)).flatten
Conceptually, I understand flatMap
in terms of flatten
.
解决方案
An alternate approach:
def flatMap[A, B](list: List[A])(f: A => List[B]): List[B] =
list.foldLeft(List[B]())(_ ++ f(_))
I don't know about "better". (And if we start talking about efficient implementation, that's another can of worms...)
这篇关于实现List#flatMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文