Create a gist now

Instantly share code, notes, and snippets.

@igstan /oo.hs
Created Mar 19, 2011

A simple object system in Haskell
-- > :load oo.hs
-- [1 of 1] Compiling Main ( oo.hs, interpreted )
-- Ok, modules loaded: Main.
-- > :main
-- Hello, World
-- > :t (newGreeter "Hi, " |> sayHello)
-- (newGreeter "Hi, " |> sayHello) :: String -> IO ()
-- This would be an `interface` in Java.
data Greeter = Greeter {
terminalSymbol :: String,
sayHello :: String -> IO ()
}
-- This would be the class definition
newGreeter :: String -> Greeter
newGreeter greetingStart = this
where this = Greeter {
terminalSymbol = "!",
sayHello = privateMember
}
privateMember personName = putStrLn (greetingStart ++ personName ++ (this /> terminalSymbol))
-- This would be the dot (.) in languages like Java or Python.
(/>) = flip ($)
main :: IO ()
main = do greeter /> sayHello $ "World"
modifiedGreeter /> sayHello $ "World"
where greeter = newGreeter "Hello, "
-- Simple to replace existing implementation (prototypal inheritance?).
modifiedGreeter = greeter {
sayHello = \_ -> putStrLn "Modified!"
}
-- I'm not sure I can represent internal state using monads, but that would be
-- the next logical step.
-- I also, don't see how would be possible to implement inheritance as in Java,
-- but it's probably doable to model prototypal inheritance.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment