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
?
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
?
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)
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.
"%s = %d\n"
leaves room for two arguments. So you'd write e.g. printf "%s = %d\n" "five" 5
rather than printf( "%s = %d\n", "five" , 5)
. I paste something that works below; see what you can make of it. –
Hillman #define DEMO(p,i) demo "p" i p
–
Hillman {-#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
© 2022 - 2024 — McMap. All rights reserved.
{-# LANGUAGE CPP #-}
. Seems GHC C preprocessor just ignores#
. – Saleswoman