gpt4 book ai didi

haskell - 在 Haskell 中查找函数的行号

转载 作者:行者123 更新时间:2023-12-01 12:49:46 24 4
gpt4 key购买 nike

我正在尝试创建一个 Haskell 程序,该程序在屏幕上绘制一些简单的 2d 形状,但是当您将鼠标悬停在每个形状上时,它会打印创建形状的源代码行。

为了做到这一点,我希望能够创建带有尺寸参数和指示行号的最终参数的形状。像这样的东西:

rect1 = Shape(Rectangle 2 2 lineNumber)

这将创建一个宽度为 2 像素、高度为 2 像素的矩形,并使用函数 lineNumber 来存储编写这段代码的行。 Haskell中是否存在这样的功能?创建一个简单吗?

我搜索了堆栈溢出,发现 this question回答者建议可以使用 C++ 中的 __LINE__ 杂注来实现类似的效果。这是最好的方法还是有办法在纯 Haskell 中做到这一点?

最佳答案

您可以使用 Template Haskell 来做到这一点,它在技术上是另一个 GHC 扩展,但可能在某种程度上比 C 预处理器更“纯”。

here 窃取的代码并稍作修改。

{-# LANGUAGE TemplateHaskell #-}

module WithLocation (withLocation) where
import Language.Haskell.TH

withLocation' :: String -> IO a -> IO a
withLocation' s f = do { putStrLn s ; f }

withLocation :: Q Exp
withLocation = withFileLine [| withLocation' |]

withFileLine :: Q Exp -> Q Exp
withFileLine f = do
let loc = fileLine =<< location
appE f loc

fileLine :: Loc -> Q Exp
fileLine loc = do
let floc = formatLoc loc
[| $(litE $ stringL floc) |]

formatLoc :: Loc -> String
formatLoc loc = let file = loc_filename loc
(line, col) = loc_start loc
in concat [file, ":", show line, ":", show col]

像这样使用它(来自另一个模块):
{-# LANGUAGE TemplateHaskell #-}

module Main where
import WithLocation

main = do
$withLocation $ putStrLn "===oo0=Ü=0oo=== Kilroy was here"

关于haskell - 在 Haskell 中查找函数的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13379356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com