[Haskell-cafe] Data declaration vs type classes

Miguel Mitrofanov miguelimo38 at yandex.ru
Fri Jan 8 10:11:16 UTC 2016


First one is closed: there is a very clear list of all possibilities, kept in one place. Even if it's exported, it's impossible to add anything to the list of tasks without modifying that module.

Second is open; if it's exported, users of your module can add their own tasks.

On the other hand, adding new function that works on all tasks is, in the first case, simple: you can just write it in the same way as your `doTask`. Users can do that without modifying the module. In the second case you have to change your `Task` class if you want to add a function.

08.01.2016, 12:56, "Lian Hung Hon" <hon.lianhung at gmail.com>:
> Dear haskellers,
>
> What is the difference between writing
>
> data Task = GroceryTask String | LaundryTask Int
>
> doTask :: Task -> IO ()
> doTask (GroceryTask s) = print "Going to " ++ s
> doTask (LaundryTask n) = print (show n ++ " pieces washed"
>
> and
>
> class Task a where
>   work :: a -> IO ()
>
> data GroceryTask = GroceryTask String
> data LaundryTask = LaundryTask Int
>
> instance Task GroceryTask where ..
>
> instance Task LaundryTask where ..
>
> doTask :: Task a => a -> IO ()
> doTask = work
>
> They seem to be similar functionality wise, except that one is on the data level and another is on the class level. How should one go about deciding to use data or class? Is there a semantic difference? Which is more appropriate here?
>
> Happy new year,
> Hon
> ,
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe


More information about the Haskell-Cafe mailing list