功能编程中的vs地图 [英] for vs map in functional programming

查看:40
本文介绍了功能编程中的vs地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用Scala进行函数式编程.通常,我注意到for循环在功能程序中使用不多,而是使用map.

I am learning functional programming using scala. In general I notice that for loops are not much used in functional programs instead they use map.

问题

  1. 在性能,可读性等方面,使用map over for循环有什么优势?

  1. What are the advantages of using map over for loop in terms of performance, readablity etc ?

使用循环可以实现映射功能的目的是什么?

What is the intention of bringing in a map function when it can be achieved using loop ?

程序1:使用For循环

val num = 1 to 1000
val another = 1000 to 2000
for ( i <- num )
{
  for ( j <- another) 
  {
    println(i,j)
  }
}

程序2:使用地图

val num = 1 to 1000
val another = 1000 to 2000
val mapper = num.map(x => another.map(y => (x,y))).flatten
mapper.map(x=>println(x))

程序1和程序2都做同样的事情.

Both program 1 and program 2 does the same thing.

推荐答案

答案实际上很简单.

每当在集合上使用循环时,它就有语义上的意义.您想要迭代集合中的项目并打印它们.或者您想将元素的类型转换为另一种类型(地图).或者,您想更改基数,例如计算集合元素的总和(折叠).

Whenever you use a loop over a collection it has a semantic purpose. Either you want to iterate the items of the collection and print them. Or you want to transform the type of the elements to another type (map). Or you want to change the cardinality, such as computing the sum of the elements of a collection (fold).

当然,使用for-循环也可以完成所有操作,但是对于代码阅读者来说,与众所周知的命名操作(例如map,iter)相比,找出循环具有哪种语义目的需要做更多的工作.,折叠,过滤器...

Of course, all that can also be done using for - loops but to the reader of the code, it is more work to figure out which semantic purpose the loop has, compared to a well known named operation such as map, iter, fold, filter, ...

另一方面是,for循环导致使用可变状态的黑暗面.您如何在无可变状态的for循环中求和集合中的元素?你不会.相反,您将需要编写一个递归函数.因此,最好的方法是尽早放弃循环思考的习惯,并享受勇敢的新功能来做事.

Another aspect is, that for loops lead to the dark side of using mutable state. How would you sum the elements of a collection in a for loop without mutable state? You would not. Instead you would need to write a recursive function. So, for good measure, it is best to drop the habit of thinking in for loops early and enjoy the brave new functional way of doing things.

这篇关于功能编程中的vs地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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