Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get variable name in haskell

Tags:

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

?

like image 769
Matvey Aksenov Avatar asked Oct 25 '11 23:10

Matvey Aksenov


1 Answers

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)
like image 151
FunctorSalad Avatar answered Oct 11 '22 13:10

FunctorSalad