Haskell相当于C的__LINE__ [英] Haskell equivalent of C's __LINE__

查看:140
本文介绍了Haskell相当于C的__LINE__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



(就像C的 __ LINE __ )有没有办法在Haskell中获得行号/追溯信息?宏或Python的 traceback.extract_stack()



这对于编写Haskell程序是有用的, C ++代码,这些代码将用注释告知Haskell行负责哪个C ++行。



Haskell示例:

  LINE#include< foo.h> - 这是第12行
:INDENTvoid Foo :: bar(){}
[LINE $blah(m_++ x ++,\++ x ++\);
| x< - [Potato,Avocado]
]

会产生这个C ++代码:

  #include< foo.h> // gen.hs:12 
void Foo :: bar(){// gen.hs:13
blah(m_Potato,Potato); // gen.hs:14
blah(m_Avocado,鳄梨); // gen.hs:14
} // gen.hs:13


解决方案

您可以在Haskell中使用CPP __ LINE __ 编译指示。

  { - #LANGUAGE CPP# - } 

main = do
printone
print __LINE__


$ runhaskell A.hs
one
5

另外,如果条件失败, Control.Exception.assert 函数将发出一个行号。

  import Control.Exception 

main = do
printone
assert False
printtwo


$ runhaskell A.hs
one
A.hs:A.hs:5:5-10 :断言失败


Is there a way to get line-number/traceback information in Haskell?

(like C's __LINE__ macro or Python's traceback.extract_stack())

That would be of use for me for writing Haskell program that generates C++ code, which would be notated with comments telling which Haskell line is responsible for which C++ line.

Haskell example:

LINE "#include <foo.h>" -- this is line 12
: INDENT "void Foo::bar() {" "}"
    [ LINE $ "blah(m_" ++ x ++ ", \"" ++ x ++ "\");"
    | x <- ["Potato", "Avocado"]
    ]

will generate this C++ code:

#include <foo.h>                  // gen.hs:12
void Foo::bar() {                 // gen.hs:13
  blah(m_Potato, "Potato");       // gen.hs:14
  blah(m_Avocado, "Avocado");     // gen.hs:14
}                                 // gen.hs:13

解决方案

You can actually use the CPP __LINE__ pragma in Haskell.

{-# LANGUAGE CPP #-}

main = do
    print "one"
    print __LINE__


$ runhaskell A.hs
"one"
5

Also, the Control.Exception.assert function will emit a line number if its condition fails.

import Control.Exception

main = do
    print "one"
    assert False $
        print "two"


$ runhaskell A.hs
"one"
A.hs: A.hs:5:5-10: Assertion failed

这篇关于Haskell相当于C的__LINE__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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