# [Haskell-cafe] How to "Show" an Operation?

Claus Reinke claus.reinke at talk21.com
Mon Jun 7 15:49:39 EDT 2010

```>> > If I have a problem where I have to select from a set of operations,
>> > how
>> > would I print the result?
>> >
>> > Example: If I can chose from (x+y), (x*y), (x^2+y)...
>> > and I feed them all into my problem solver
>> > and it finds that "(x*y) is right", how can I print that string?

As others have pointed out, you can't go from operation to representation,
but you can pair operations and expressions with their representations.

Unless your problem solver just tries out a list of known expressions,
you'll probably end up with a proper expression representation as an
algebraic datatype, and a way to bind the variables. However, if you
really only want arithmetic expressions and their values, you could
define your own instances of the classes defining those operations.

A small example of this approach can be found here:

It pairs up values with String representations of the expressions
that led to those values

data R a = R { rep:: String, val:: a }

and defines a Num instance for 'Num a => R a'

Then you can do things like (more examples in the source):

-- expressions at default type: show the value
*R> foldl (+) 0 [1..4]
10
*R> foldr (+) 0 [1..4]
10

-- expressions at 'R Int' types: show the representation
*R> foldl (+) 0 [1..4]::R Int
((((0 + 1) + 2) + 3) + 4)

*R> foldr (+) 0 [1..4]::R Int
(1 + (2 + (3 + (4 + 0))))

*R> flip (foldr (+)) [1..4]::R Int->R Int
\x->(1 + (2 + (3 + (4 + x))))

*R> flip (foldl (+)) [1..4]::R Int->R Int
\x->((((x + 1) + 2) + 3) + 4)

This approach does not easily scale to more complex expressions,
and the code was meant for small demonstrations only, but it might
give you some ideas.

Claus

```