[Haskell-cafe] Functional version of this OO snippet

Thomas Davie tom.davie at gmail.com
Fri Dec 5 09:24:52 EST 2008


On 5 Dec 2008, at 13:40, Andrew Wagner wrote:

> Hi all,
> public interface IEngine {
>  void foo();
>  void bar(string bah);
>  ...
> }
> public class Program {
> public void Run(IEngine engine){
>  while(true){
>    string command = GetLine();
>    if (command.startsWith("foo")){
>      engine.foo();
>    } else if (command.startsWith("bar")){
>      engine.bar(command);
>    ...
>    else break;
> }
>
> In other words, I want to provide the same UI across multiple  
> implementations of the engine that actually processes the commands.

class IEngine a where
   foo :: a -> String
   bar :: a -> String -> String

run :: IEngine a => a -> IO ()
run x = interact (unlines . processCommand x . lines)

processCommand e c
   | "foo" `isPrefixOf` c = foo e
   | "bar" `isPrefixOf` c = bar e c

That should about do it.

Bob


More information about the Haskell-Cafe mailing list