在Haskell中移动或复制(与C ++) [英] Move or copy in Haskell (vs. C++)

查看:135
本文介绍了在Haskell中移动或复制(与C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用这两个C ++函数和示例用法:

Take these two C++ functions and example usages:

vector<int> makeVect() {
  vector<int> v = {1,2,3};
  return v;
}

//usage
auto v = makeVect(); //vector is moved

void addFour(vector<int> &v) {
  v.push(4);
}

//usage
addFour(v); //v is passed in as reference

在任何情况下都不会发生复制。

No copying happens in either case. This is really efficient.

下面是相应的Haskell函数和用法:

Here are the corresponding Haskell functions and usages:

makeVect :: (Num a) => [a]
makeVect = [1,2,3]

--usage
--Q1: is [1,2,3] copied or moved to v?
let v = makeVect

addFour :: (Num a) => [a] -> [a]
addFour xs = xs ++ [4]

--usage
--Q2: is the parameter copied or moved into the function?
--Q3: on return, is the result copied or moved out of the function?
addFour v

问题Q1,Q2,Q3在代码中。 Haskell移动或复制东西吗?有办法控制吗?在这些情况下,Haskell与C ++相比的效率如何?

The questions Q1, Q2, Q3 are in the code. Does Haskell move or copy things around? Is there a way to control it? In these cases, how efficient is Haskell compared to C++?

推荐答案

在Haskell中,值是不可变的。从概念上说,复制或移动它们是没有意义的。在全世界有多少个5的副本?这是一个没有意义的问题。 5只是。每个人都可以自由使用,它是相同的数字5.同样的 [1,2,3]

In Haskell, values are immutable. Conceptually, it makes no sense to speak of copying or moving them. How many copies of the number 5 are there in the entire world? This is a meaningless question. 5 just is. Everyone can use it freely, it's the same number 5. Same thing for [1,2,3].

如果我们看一个典型的编译器生成的代码,当然有一些复制操作在那里,但那些主要是指向不可变的内存区域。

If we look at code produced by a typical compiler, of course there are some copying operations going on there, but those are mostly pointers to immutable regions of memory.

这篇关于在Haskell中移动或复制(与C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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