Re: [Haskell-cafe] no dynamic binding

You can use exisential types to do what you'd like. From memory, so
there are probably errors:
newtype ServerCommand = forall a. ServerCommandClass a => ServerCommand a
instance ServerCommandClass ServerCommand where
toString (ServerCommand c) = toString c
commands :: [ServerCommand]
commands = [ServerCommand $ DashCommand ..., ServerCommand $ MoveCommand ...]
Also, for a less type-safe approach, see Data.Dynamic.
On Sun, 19 Sep 2004 13:48:53 -0400, Andrew Harris
Hi -
I have another question. I am still working on a soccer server and thought it would be neat to create command objects that had a "toString" method. Then, I was going to keep a list of these command objects and at the right time stringify them and send them to the server. So I created a class with a toString method:
class ServerCommandClass a where toString :: a -> String
And then a few instances:
-- dash command data DashCommand = DashCommand { dashpower :: Double }
instance ServerCommandClass DashCommand where toString c = "(dash " ++ show (dashpower c) ++ ")\n"
-- move command data MoveCommand = MoveCommand { x :: Double, y :: Double }
instance ServerCommandClass MoveCommand where toString c = "(move " ++ show (x c) ++ " " ++ show (y c) ++ ")\n"
The problem is, I am not quite sure how to describe a *list* of command objects where the list could have both DashCommands and MoveCommands in it. Ideally the list could contain both, and then for each item in the list I could call the toString method.
I was reading Simon Thompson's Haskell: The Craft of Functional Programming and I read that Haskell 98 does not support dynamic binding, which (it seems) is what I'm trying to do. Does anyone have a suggestion on an alternative approach?
thanks, -andrew _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe

On Sun, Sep 19, 2004 at 02:46:12PM -0400, Abraham Egnor wrote:
You can use exisential types to do what you'd like. From memory, so there are probably errors:
newtype ServerCommand = forall a. ServerCommandClass a => ServerCommand a
This can't be newtype, you must use 'data'.
instance ServerCommandClass ServerCommand where toString (ServerCommand c) = toString c
commands :: [ServerCommand] commands = [ServerCommand $ DashCommand ..., ServerCommand $ MoveCommand ...]
As it was pointed to me some time ago, you can also achieve this without existential types, simply by keeping the partially applied methods in your ServerCommand data type, eg. data ServerCommand = ServerCommand { scToString :: String } or, if you want to avoid memoizing the toString result in this case data ServerCommand = ServerCommand { scToString :: () -> String } Best regards, Tom -- .signature: Too many levels of symbolic links
participants (2)
-
Abraham Egnor
-
Tomasz Zielonka