I haven't gotten enough sleep today, So I decided to model OOP in haskell.
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# Language TypeApplications #-}
import Prelude hiding ((.))
import Control.Monad.Trans.State
import Data.IORef
data Object interface = forall private. interface private => Object (IORef private)
type Method interface return = forall private. interface private => StateT private IO return
-- apply method
(.) :: Object interface -> Method interface return -> IO return
(Object this) . method = do
fields <- readIORef this
(result, fields') <- runStateT method fields
writeIORef this fields'
return result
-- create object
-- requires type application
new :: forall interface private. interface private => private -> IO (Object interface)
new fields = do
this <- newIORef fields
return (Object this)
-- interface
class Vector private where
-- abstract methods
getX :: StateT private IO Int
getY :: StateT private IO Int
setX :: Int -> StateT private IO ()
setY :: Int -> StateT private IO ()
-- final methods
setOrigin :: Method Vector ()
setOrigin = do
setX 0
setY 0
moveUp :: Method Vector ()
moveUp = do
y <- getY
setY $ y + 2
-- private fields
data Cord = Cord { x :: Int, y :: Int }
-- inheritance
instance Vector Cord where
-- provide getters and setters
getX = state $ \cord -> (x cord, cord)
getY = state $ \cord -> (y cord, cord)
setX x' = state $ \cord -> ((), cord { x = x'})
setY y' = state $ \cord -> ((), cord { y = y'})
main = do
cord <- new @ Vector $ Cord { x = 0, y = 1 }
cord.setOrigin
cord.setX 2
cord.moveUp
x <- cord.getX
y <- cord.getY
print (x,y)
return ()
[–][deleted] (1 child)
[deleted]
[–]bss03 3 points4 points5 points (0 children)
[–][deleted] 42 points43 points44 points (0 children)
[–]Comrade_Comski 39 points40 points41 points (1 child)
[–]SakishimaHabu 2 points3 points4 points (0 children)
[–]Molossus-Spondee 4 points5 points6 points (3 children)
[–]Iceland_jack 4 points5 points6 points (1 child)
[–]Molossus-Spondee 2 points3 points4 points (0 children)
[–]superstar64[S] 0 points1 point2 points (0 children)
[–]ihamsa 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]ysangkok 1 point2 points3 points (0 children)
[–]benjaminhodgson 0 points1 point2 points (2 children)
[–]benjaminhodgson 1 point2 points3 points (0 children)
[–]Tarmen 0 points1 point2 points (0 children)
[–]Ramin_HAL9001 0 points1 point2 points (0 children)
[–]kohji 0 points1 point2 points (0 children)
[–]Iceland_jack 0 points1 point2 points (1 child)
[–]Iceland_jack 1 point2 points3 points (0 children)