[Haskell-cafe] OO idioms redux
Duncan Coutts
duncan.coutts at worcester.oxford.ac.uk
Wed Oct 13 09:15:22 EDT 2004
In message <slrncmo8qa.a82.jgoerzen at christoph.complete.org> John Goerzen
<jgoerzen at complete.org> writes:
> OK, recently I posed a question about rethinking some OO idioms, and
> that spawned some useful discussion.
>
> I now have a followup question.
>
> One of the best features of OO programming is that of inheritance. It
> can be used to slightly alter the behavior of objects without requiring
> modification to existing code or breaking compatibility with existing
> APIs.
Closures can do this:
// in C++/Java
class ConfigParser {
void read (String);
int getFoo (String);
}
-- in Haskell
data ConfigParser = ConfigParser {
read :: String -> IO ConfigParser
getFoo :: String -> Int
}
This is a structure of functions. The difference from C++/Java style objects is
that this gives us object based polymorphism rather than class based
polymorphism. Because they are Haskell closures rather than C-style functions
they can hold private state by using partial application.
configParser :: ConfigParser
configParser = ConfigParser {
read input = ...
getFoo = ...
}
envConfigParser :: ConfigParser
envConfigParser = configParser {
read input = do env <- getEnvVars
read configParser (substEnvVars input)
}
Duncan
More information about the Haskell-Cafe
mailing list