1

I have a scenario that involves type classes and I'm not quite sure how to go about solving it.

I have

class Event a where
     timestamp :: a -> UTCTime
     rawData :: a -> ByteString

class Something a where
    something :: a -> SomethingElse

In my code, I want to create an object that implements both Event and Something. However, in certain cases, the function something is going to need the return from a call to rawData to construct the SomethingElse object. I was wondering if there was to structure these type classes to be able to build a function like

convert :: (Event a, Event b, Something b) => a -> b

being able to call convert x :: (Instance of something) in order to convert, a bit like how binary get is used.

I realize that this is a rather vague description, but please let me know if I can add anything else.

Thanks

3
  • I'm not entirely clear what you're asking, but in order for convert to be able to return a value of any Event & Something type, you need a way to construct a value of any Event & Something type while knowing only that the type belongs to those two classes. You could give one of the classes a method like unraw :: ByteString -> a or, if such a method would require utilizing features of both classes for some reason, make a new class that inherits both Event & Something and has the desired constructor. Commented Jun 30, 2011 at 0:58
  • you have to give some context to SomethingElse, way not just ByteString? Commented Jun 30, 2011 at 1:20
  • Pretty much SomethingElse is just a deserialized object where the bytestring is the serialized version Commented Jun 30, 2011 at 2:51

1 Answer 1

2

In type class Something you need to make sure that the type a has implemented type class Event, hence the definition of Something becomes:

class Event a => Something a where
     something :: a -> SomethingElse
Sign up to request clarification or add additional context in comments.

2 Comments

How would I abstract it out if Something doesn't always need an event. Lets say only in certain cases a Something is constructed by an event. How would I organize that hierarchy? I'm not that familiar with standard Object oriented practices.
In that case you can remove the (Event a) restriction from Something type class and put this restriction on a new method inside Something class.. somethingFromEvent ... this method will create something from event and the parameter to this method must have a instance of Event class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.