[Haskell-cafe] Can I determin the function name passed in?

Keith Wansbrough Keith.Wansbrough at cl.cam.ac.uk
Thu Oct 7 06:20:48 EDT 2004

> I'm an utter noob to Haskell, and FP in gnereal. I would like to create
> a function taking an argument which is a function (actually an equation
> taking no args, but dependent on other equations), which prints the name
> of the function and and it's result. Is there a way of doing this in
> Haskell? Sounds like a job for macros, or some kind of
> introspection-type stuff.

You can't do this in Haskell.  In Haskell, functions are very
lightweight things, and often they are inlined or compiled away in
some way leaving no trace at runtime.  So there's nothing to reflect
on.  This is in contrast to a language like Java, where each object
has quite a lot of identity and state, and a large heap footprint.

If you *really* want it, you can do something similar with either the
C preprocessor or (perhaps) profiling and cost-centre stacks.  But you
probably don't.  Instead, you should pass around data items that
contain both the function and its name - either just pairs, like

f :: (String, a->b)
f = ("successor",\x -> x+1)

apply :: (String, a->b) -> a -> b
apply (_, ff) x = ff x

nameOf :: (String, a->b) -> String
nameOf (s,_) = x

or proper data types, like

data NamedFunc a b = NamedFunc String (a->b)

f :: NamedFunc Int Int
f = NamedFunc "successor" (\x -> x+1)

apply :: NamedFunc a b -> a -> b
apply (NamedFunc _ ff) x = ff x

nameOf :: NamedFunc a b -> String
nameOf (NamedFunc s _) = s


--KW 8-)

More information about the Haskell-Cafe mailing list