1

I have the following code:

data Instruction = Assignment (Int->Int->Int) Int Int

This allows me to create a method like this:

foo :: Assignment -> Int
foo (Assignment func a b) = (func a b) + 100

which can be used like this:

foo (Assignment (+) 5 6) --outputs 111

Or

foo (Assignment (*) 5 5) --outputs 125

Now I want to create a "show" for the Assignment. This is what I got so far:

instance Show Instruction where
    show (Assignment f a b) = show a ++ " " ++ show f ++ " " ++ show b --compile time error

What I want is if I did "show (Assignment (*) 5 8)" the output would be "5 * 8"

However the problem is that you cannot do "show f".

Note: please leave reliance on other libraries to a minimum or none.

halfer
  • 19,824
  • 17
  • 99
  • 186
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231
  • 3
    You can't show functions, once they're compiled there isn't any information about their source left. However, there are many other ways to solve this problem, but they probably won't be how you want to solve them. If you have a limited set of functions to choose from for `Assignment`, then you can make a data type representing those functions `data Func = Add | Sub | Mult deriving (Eq)` then `eval :: Func -> (Int -> Int -> Int)`; `eval Add = (+)`; `eval Sub = (-)`; `eval Mult = (*)` and `instance Show Func where show Add = "+"` etc. You can not show anything meaningful for a function though – bheklilr Nov 11 '14 at 16:15
  • 3
    A function doesn't have a name or anything else that has a suitable text representation. (What would you expect from `show (Assignment (\x y -> x + y) 3 5)`?) – molbdnilo Nov 11 '14 at 16:32
  • 2
    I would just add a `String` field to `Assignment` and show that instead. Is there a reason why that wouldn't work? – yatima2975 Nov 11 '14 at 16:53
  • 1
    You can make functions showable by [replacing them with named functions](http://stackoverflow.com/a/17762806/1598537). It's a lot of work for not much benefit, though. – AndrewC Nov 11 '14 at 22:22

0 Answers0