Matvey Aksenov
Matvey Aksenov

Reputation: 3900

How to get variable name in haskell

I came to haskell having some c background knowledge and wondering is there an analog to

#define print( a ) printf( "%s = %d\n", #a, a )

int a = 5;
print( a );

that should print

a = 5

?

Upvotes: 12

Views: 2140

Answers (3)

applicative
applicative

Reputation: 8199

{-#LANGUAGE CPP#-}
import Text.Printf
#define print( a ) printf "%s = %d\n" (show a) a 

main = do  let a = (5 :: Int)
           print( a ) 



 $ ghci a.hs
 *Main> main
 5 = 5

Upvotes: 4

augustss
augustss

Reputation: 23004

You can use the same #define trick in Haskell if you turn on the CPP language extension. Or you can use Template Haskell to get the same effect.

But in pure Haskell it is impossible, because it violates the principle of alpha conversion, i.e., renaming bound variables (in a hygienic way) should not change the program semantics.

Upvotes: 19

FunctorSalad
FunctorSalad

Reputation: 2622

Here's the TH solution augustss mentioned:

{-# LANGUAGE TemplateHaskell #-}
module Pr where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax

pr :: Name -> ExpQ
pr n = [| putStrLn ( $(lift (nameBase n ++ " = ")) ++ show $(varE n) ) |]

then in another module:

{-# LANGUAGE TemplateHaskell #-}
import Pr
a = "hello"
main = $(pr 'a)

Upvotes: 22

Related Questions