haskell - 如何在 Haskell 中打印标识符或绑定(bind)的名称?

标签 haskell metaprogramming code-inspection

假设我想在 Haskell 中打印“变量”的名称和值。该名称在编译时已知!有没有比以下示例更好的方法?

module V
(e, c, eV, h, hbar, nm, k, viewAllConstants) where
import Text.Printf
c = 2.99792458e8::Double
e = exp(1)
eV = 1.602176565e-19
h = 6.62606957e-34
hbar = h/(2*pi)
nm = 1e-9
k = 1.3806488e-23
viewAllConstants = do
    putStr ((\a b -> (foldl (++) "" ( zipWith (++) a (map (printf " = %.2e\n") b))))
        ["c", "e", "eV", "h", "hbar", "nm", "k"]
        [c, e, eV, h, hbar, nm, k] )

请在您的回答中发布一个工作代码示例 (runhaskell)!

最佳答案

正如@PeterHall 所说:

In Lisp, the distinction between data and code is blurred and everything is inspectable and dynamic at runtime. In Haskell, all types and binding names are erased at compile time, which allows for a huge amount of optimisation.

换句话说,名称在运行时未知

此外,这些不是“变量”,而是常量,或者如前所述,绑定(bind)。出于这个原因,能够访问绑定(bind)的名称是没有意义的,因为它永远不会改变。

正如@MathematicalOrchid 所建议的,可能有一个模板 Haskell 解决方案,尽管它可能只是相对有用。

至于打印绑定(bind)的更好方法,试试这个:

import Control.Monad (forM_)

viewAllConstants = forM_ (\(a, b) -> putStrLn (a ++ " = " ++ show b)) 
                   $ zip ["c", "e", "eV", "h", "hbar", "nm", "k"] 
                         [ c,   e,   eV,   h,   hbar,   nm,   k ]

关于haskell - 如何在 Haskell 中打印标识符或绑定(bind)的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30172449/

相关文章:

haskell - Netwire - 如何构建一条产生位置、墙壁弹跳的电线?

c++ - 模板函数特化 C++

r - 检查 S4 方法

haskell - 如何在嵌套列表的元素上映射函数

haskell - 生成列表的子列表

c++ - 神秘的 oneliner 模板代码,任何一个?

google-chrome - Chrome 开发者工具中的 ==$0( double 等于零)是什么意思?

PhpStorm 在项目中打开外部文件并进行检查和突出显示

Haskell 和纯函数结果的内存

c++ - 从原始内存和类分析器中推断原始类型