public
Last active

A simple object system in Haskell

  • Download Gist
oo.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
-- > :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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.