拿这两个C函数和示例用法: vectorint makeVect() { vectorint v = {1,2,3}; return v;}//usageauto v = makeVect(); //vector is movedvoid addFour(vectorint v) { v.push(4);}//usageaddFour(v); //v is passed in as reference 两种情况都
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
两种情况都不会发生复制.这非常有效.
以下是相应的Haskell函数和用法:
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相比效率如何?
在Haskell中,值是不可变的.从概念上讲,复制或移动它们毫无意义.全世界有多少副本5号?这是一个毫无意义的问题. 5就是.每个人都可以自由地使用它,它是相同的数字5. [1,2,3]也是如此.如果我们查看典型编译器生成的代码,当然会有一些复制操作,但那些主要是指向不可变内存区域的指针.