为什么在 Haskell 编译时不计算(常量)表达式? [英] Why are (constant) expressions not evaluated at compile time in Haskell?

查看:25
本文介绍了为什么在 Haskell 编译时不计算(常量)表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 Haskell,但有一件事让我感到困惑:

I am currently learning Haskell, and there is one thing that baffles me:

当我构建一个复杂的表达式(其计算需要一些时间)并且该表达式是常量(意味着它仅由已知的硬编码值构建)时,该表达式不会在编译时计算.

When I build a complex expression (whose computation will take some time) and this expression is constant (meaning it is build only of known, hard coded values), the expression is not evaluated at compile time.

来自 C/C++ 背景的我已经习惯了这种优化.

Comming from a C/C++ background I am used to such kind of optimization.

在 Haskell/GHC 中执行此类优化(默认情况下)的原因是什么?如果有的话,有什么优势?

What is the reason to NOT perform such optimization (by default) in Haskell / GHC ? What are the advantages, if any?

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 我希望编译的程序打印并退出几乎立即.

As this will always print True I would expect the compiled programm to print and exit almost immediately.

推荐答案

您可能喜欢 这个 reddit 线程.编译器可以尝试这样做,但这可能很危险,因为任何类型的常量都可以做有趣的事情,比如循环.至少有两种解决方案:一种是超级编译,尚不能作为任何编译器的一部分使用,但您可以尝试各种研究人员的原型;更实用的一种是使用 Template Haskell,这是 GHC 的机制,让程序员在编译时要求运行一些代码.

You may like this reddit thread. The compiler could try to do this, but it could be dangerous, as constants of any type can do funny things like loop. There are at least two solutions: one is supercompilation, not available as part of any compiler yet but you can try prototypes from various researchers; the more practical one is to use Template Haskell, which is GHC's mechanism for letting the programmer ask for some code to be run at compile time.

这篇关于为什么在 Haskell 编译时不计算(常量)表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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