我目前正在学习 Haskell,有一件事情让我感到困惑:
当我构建一个复杂的表达式(其计算需要一些时间)并且该表达式是常量(意味着它仅由已知的硬编码值构建)时,不会在编译时评估该表达式。
来自 C/C++ 背景,我习惯了这种优化。
在 Haskell / GHC 中不执行此类优化(默认情况下)的原因是什么?有什么好处,如果有的话?
data Tree a =
EmptyTree
| Node a (Tree a) (Tree a)
deriving (Show, Read, Eq)
elementToTree :: a -> Tree a
elementToTree x = Node x EmptyTree EmptyTree
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = elementToTree x
treeInsert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
treeFromList :: (Ord a) => [a] -> Tree a
treeFromList [] = EmptyTree
treeFromList (x:xs) = treeInsert x (treeFromList xs)
treeElem :: (Ord a) => a -> Tree a -> Bool
treeElem x EmptyTree = False
treeElem x (Node a left right)
| x == a = True
| x < a = treeElem x left
| x > a = treeElem x right
main = do
let tree = treeFromList [0..90000]
putStrLn $ show (treeElem 3 tree)
由于这将始终打印True
,我希望编译后的程序几乎立即打印并退出。