【发布时间】:2014-10-07 04:58:02
【问题描述】:
我是 Haskell 的新手。我试图了解haskell 可以如何处理递归函数调用及其惰性求值。我所做的实验是简单地在 C++ 和 Haskell 中构建二叉搜索树,并分别以后序遍历它们。 C++ 实现是带有辅助堆栈的标准实现。 (一旦我访问它,我就将元素打印出来)。
这是我的haskell代码:
module Main (main) where
import System.Environment (getArgs)
import System.IO
import System.Exit
import Control.Monad(when)
import qualified Data.ByteString as S
main = do
args <- getArgs
when (length args < 1) $ do
putStrLn "Missing input files"
exitFailure
content <- readFile (args !! 0)
--preorderV print $ buildTree content
mapM_ print $ traverse POST $ buildTree content
putStrLn "end"
data BSTree a = EmptyTree | Node a (BSTree a) (BSTree a) deriving (Show)
data Mode = IN | POST | PRE
singleNode :: a -> BSTree a
singleNode x = Node x EmptyTree EmptyTree
bstInsert :: (Ord a) => a -> BSTree a -> BSTree a
bstInsert x EmptyTree = singleNode x
bstInsert x (Node a left right)
| x == a = Node a left right
| x < a = Node a (bstInsert x left) right
| x > a = Node a left (bstInsert x right)
buildTree :: String -> BSTree String
buildTree = foldr bstInsert EmptyTree . words
preorder :: BSTree a -> [a]
preorder EmptyTree = []
preorder (Node x left right) = [x] ++ preorder left ++ preorder right
inorder :: BSTree a -> [a]
inorder EmptyTree = []
inorder (Node x left right) = inorder left ++ [x] ++ inorder right
postorder :: BSTree a -> [a]
postorder EmptyTree = []
postorder (Node x left right) = postorder left ++ postorder right ++[x]
traverse :: Mode -> BSTree a -> [a]
traverse x tree = case x of IN -> inorder tree
POST -> postorder tree
PRE -> preorder tree
preorderV :: (a->IO ()) -> BSTree a -> IO ()
preorderV f EmptyTree = return ()
preorderV f (Node x left right) = do
f x
preorderV f left
preorderV f right
我的测试结果表明 C++ 明显优于 Haskell:
C++ 性能:(注意 first15000.txt 大约是 first3000.txt 的 5 倍)
time ./speedTestForTraversal first3000.txt > /dev/null
real 0m0.158s
user 0m0.156s
sys 0m0.000s
time ./speedTestForTraversal first15000.txt > /dev/null
real 0m0.923s
user 0m0.916s
sys 0m0.004s
具有相同输入文件的 Haskell:
time ./speedTestTreeTraversal first3000.txt > /dev/null
real 0m0.500s
user 0m0.488s
sys 0m0.008s
time ./speedTestTreeTraversal first15000.txt > /dev/null
real 0m3.511s
user 0m3.436s
sys 0m0.072s
我期望haskell应该离C++不远。我犯了什么错误吗?有什么方法可以改进我的 haskell 代码吗?
谢谢
编辑: 2014 年 10 月 18 日
经过多次测试,haskell 的遍历仍然明显慢于 C++ 实现。我想对 Cirdec 的回答给予充分肯定,因为他指出我的 haskell 实施效率低下。但是,我最初的问题是比较 C++ 和 haskell 的实现。因此,我想保持这个问题的开放性并发布我的 C++ 代码以鼓励进一步讨论。
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <stack>
using namespace std;
using boost::algorithm::trim;
using boost::algorithm::split;
template<typename T>
class Node
{
public:
Node(): val(0), l(NULL), r(NULL), p(NULL) {};
Node(const T &v): val(v), l(NULL), r(NULL), p(NULL) {}
Node* getLeft() {return l;}
Node* getRight(){return r;}
Node* getParent() {return p;}
void setLeft(Node *n) {l = n;}
void setRight(Node *n) {r = n;}
void setParent(Node *n) {p = n;}
T &getVal() {return val;}
Node* getSucc() {return NULL;}
Node* getPred() {return NULL;}
private:
T val;
Node *l;
Node *r;
Node *p;
};
template<typename T>
void destoryOne(Node<T>* n)
{
delete n;
n = NULL;
}
template<typename T>
void printOne(Node<T>* n)
{
if (n!=NULL)
std::cout << n->getVal() << std::endl;
}
template<typename T>
class BinarySearchTree
{
public:
typedef void (*Visit)(Node<T> *);
BinarySearchTree(): root(NULL) {}
void delNode(const T &val){};
void insertNode(const T &val){
if (root==NULL)
root = new Node<T>(val);
else {
Node<T> *ptr = root;
Node<T> *ancester = NULL;
while(ptr && ptr->getVal()!=val) {
ancester = ptr;
ptr = (val < ptr->getVal()) ? ptr->getLeft() : ptr->getRight();
}
if (ptr==NULL) {
Node<T> *n = new Node<T>(val);
if (val < ancester->getVal())
ancester->setLeft(n);
else
ancester->setRight(n);
} // else the node exists already so ignore!
}
}
~BinarySearchTree() {
destoryTree(root);
}
void destoryTree(Node<T>* rootN) {
iterativePostorder(&destoryOne);
}
void iterativePostorder(Visit fn) {
std::stack<Node<T>* > internalStack;
Node<T> *p = root;
Node<T> *q = root;
while(p) {
while (p->getLeft()) {
internalStack.push(p);
p = p->getLeft();
}
while (p && (p->getRight()==NULL || p->getRight()==q)) {
fn(p);
q = p;
if (internalStack.empty())
return;
else {
p = internalStack.top();
internalStack.pop();
}
}
internalStack.push(p);
p = p->getRight();
}
}
Node<T> * getRoot(){ return root;}
private:
Node<T> *root;
};
int main(int argc, char *argv[])
{
BinarySearchTree<string> bst;
if (argc<2) {
cout << "Missing input file" << endl;
return 0;
}
ifstream inputFile(argv[1]);
if (inputFile.fail()) {
cout << "Fail to open file " << argv[1] << endl;
return 0;
}
while (!inputFile.eof()) {
string word;
inputFile >> word;
trim(word);
if (!word.empty()) {
bst.insertNode(word);
}
}
bst.iterativePostorder(&printOne);
return 0;
}
编辑: 2014 年 10 月 20 日 克里斯在下面的回答非常彻底,我可以重复结果。
【问题讨论】:
-
请注意,在主函数中,我注释掉了一行。我在想直接打印出元素而不是先列出一个列表可能会更好。事实证明,这两种方法具有相似的性能。看起来惰性评估在这里做得很好。
-
也许你的意思是
postorder (Node x left right) = postorder left ++ postorder right ++ [x]?
标签: haskell recursion lazy-evaluation