Created
March 19, 2011 17:03
-
-
Save igstan/877617 to your computer and use it in GitHub Desktop.
A simple object system in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- > :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