[Haskell-beginners] How to model this in haskell, get rid of my OO thinking?

edgar klerks edgar.klerks at gmail.com
Tue May 18 05:33:08 EDT 2010


He Nathan,

I would create an data type (SpaceObject), which holds the Position and an
object. Then I create a typeclass for SpaceObject, which has the function
move in it. Functions which all objects have are moved in the typeclass:


type Position = (Double, Double)

data SpaceObject a = SO a Position

data RocketObject = RocketObject {
                stuff :: String
        }

data SpaceShipObject = SpaceShipObject {
                bla :: Int
        }

type Rocket = SpaceObject RocketObject
type SpaceShip = SpaceObject SpaceShipObject

class ScreenObject a where
        move :: a -> Position -> a

instance ScreenObject (SpaceObject obj) where
        move (SO obj (x,y) ) (dx, dy)  = SO obj (x + dx, y + dy)
~

~

~

~

On Tue, May 18, 2010 at 5:21 AM, <haskell at lonely-star.org> wrote:

> Hi,
>
> I learning haskell and I am trying to understand how model certain
> things in it.
> As I have been doing a lot of C++ programming so far. Let's imagine we
> want to write a game. In the game there are spaceships and rocks (image
> something like astroids :) ). Now both spaceships and rocks have a
> position and can move. Spaceships can shoot, while rocks can explode.
> In C++, I would do (simplified):
>
> class ScreenObject
> {
>   float x,y;
>   void move(dx,dy){x+=dx;y+=dy;}
> };
>
> class Spaceship : public ScreenObject
> {
>    void shoot(){...}
> };
>
> class Rocket : public ScreenObject
> {
>    void explode(){...}
> };
>
> But what would I do in haskell? Ok, I can define a typeclass
> "ScreenObjectType" that has a move function (taking an object, retuning
> an moved object).
> But I do not want to implement "move" for both Spaceship and Rocket.
> Can I somehow give a default implementation for move that works on any
> datatype having an "x" and "y" element? Or what would I do?
> Can I somehow define a "base datatype" holding a x and y member form
> which Spaceship and Rocket derive?
> I feel like I am thinking to much OOP here.
> But the point is, I guess, that I want to avoid code duplication!
>
> So I guess, it comes down to the questions: How would you model the
> scenario described above in haskell?
>
> Thanks!
> Nathan
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



-- 
Flatliner ICT Service,
Email: Edgar.klerks at gmail.com,
Tel: +31727851429
Fax: +31848363080
Skype: edgar.klerks
Website: flatlinerict.nl
Adres: Koelmalaan 258,
1813JD, Alkmaar
Nederland
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100518/7fc23a33/attachment.html


More information about the Beginners mailing list