Rog Matthews
Rog Matthews

Reputation: 3247

Implement Interface in OO Haskell

In this program there is an interface IPoint and a function point (which acts as a class in c++) that implements the interface behaviour. I tried many methods to declare that the function point implements IPoint but could not do so.

{-# LANGUAGE EmptyDataDecls, TypeOperators, FlexibleContexts, FlexibleInstances,UndecidableInstances, MultiParamTypeClasses, ScopedTypeVariables, DeriveDataTypeable, TemplateHaskell #-}
{-# OPTIONS_GHC -fcontext-stack=100 #-}

module Point where

import OOHaskell

$(label "read'")
$(label "load")
$(label "incr")


type IPoint a = 
    Record ( Read' :=: IO a
          :*: Load :=: (a-> IO())
          :*: Incr :=: IO()
          :*: HNil)

--point value self = self :: IO (IPoint a)
point value self
    = do
    valueRef <- newIORef value :: IO (IORef Integer)
    returnIO $
         read' .=. readIORef valueRef
     .*. load  .=. (\v -> writeIORef valueRef v)
     .*. incr  .=. modifyIORef valueRef (+1)
     .*. emptyRecord

How can i specify that the function point implements IPoint??

Upvotes: 2

Views: 319

Answers (1)

dave4420
dave4420

Reputation: 47042

point :: Integer -> b -> IO (IPoint Integer)

n.b.

  1. Top level type annotations always state the type of a value defined elsewhere (usually immediately afterwards, e.g. point), not the type of an expression (e.g. point value self).

  2. The second argument is not used, hence it can be of any type.

  3. Your function does not generate an IPoint a, it generates an IPoint Integer, because it hardcodes the type of valueRef as IORef Integer.

I'm not sure that doing OO in Haskell is a good idea. It's certainly not idiomatic.

Upvotes: 2

Related Questions