Function to output function name

后端 未结 5 1482
离开以前
离开以前 2020-12-17 22:20

Is it possible in Haskell to implement a function which returns its own function name?

A possible type could be (a -> b) -> String.

5条回答
  •  一个人的身影
    2020-12-17 23:05

    You can preprocess your source code with CPP. In CPP

    #define _NAMEOF(name) #name
    

    defines a macro, _NAMEOF, for stringifying text (including surrounding it with programmer's quotation marks). You can then use it as follows:

    head [] = error $ _NAMEOF(head) ++ ": empty list!"
    

    which CPP should translate into a valid Haskell source code line:

    head [] = error $ "head" ++ ": empty list!"
    

提交回复
热议问题