last day (16 days later) » 

12:02 PM
3
Q: How to convert my thoughts in OOP to Haskell?

MagicloudFor example, I have a container type to hold elements with common character. And I also provide some types to be the element. And I also want this function to be easily extended (others could make their own element type and be hold by my container). So I do: class ElementClass data E1 = E1 Stri...

 
You should skip the forall and don't bother with the Element class, then parameterise the container data structure on the element type. data Container e = Container [e]
 
@DanielWagner, read the data contained in each element.
@AndrewC, then a Container will hold only one type, right? I want it to hold any types that could work as ElementClass.
@CarstenKönig, yes, that is what I was thinking. But I really cannot come up with a solution.
@Barmar, done. Thanks.
@chi, that is an idea. Let me see if it works.
 
@Magicloud Why? Other than reimplement OOP or disable the type system or forget forever what your data was, why is this useful? The proper way to do this in Haskell style is not to mix all your data types together.
What every OOP programmer should read if they're tempted to do this in Haskell: Luke Palmer's Haskell Antipattern: Existential Typeclass. Here's the logic: with an existential typeclass (or equivalent GADT), the programmer has lost any ability to recover the original type, and can only deal with the data via the typeclass functions. It's much easier to simply pass these functions around as a record than mess with the type system while storing the original data. Functions are easy to manipulate in Haskell
 
@AndrewC, with "data Container e = Container [e]", if e is not a wrapper of ElementClass, based on the original code, once it is constructed as "Container [3 :: Int]", this container will only contain Int, right?
 
You'd not be able to mix types together except by means of a tagged union, so Container [3,7,4] would be a different type to Container [True,False,True], and you couldn't do Container [3,'h',False], but could do data MyTaggedUnion = AnInt Int | ABool Bool | AChar Char and then Container [AnInt 3, AChar 'h', ABool False]. My question was why you needed to mix types together.
 
12:06 PM
@AndrewC, I see. Let me make an exmaple. A GUI application normally has a window, and a few widgets (button, textbox, etc) in it. So, at least in OOP, I will define this as "data App = App Window; data Window = Window Title [WidgetClass]". Here, I have to put different types (but all could behave as WidgetClass) in the list.
 

  last day (16 days later) »