Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Design pattern: classes or pass functions

Lets say I have a function which takes some input structure and returns some output structure (which may be related to but different to the input structure).

I don't want to enforce these input/output structures to a particular type, I just want to ensure they have a few behaviors that I need.

Should I?

a) Define a class which has the appropriate extraction methods and force the input data to be an instance of that class? OR
b) Have the function accept another parameter which is function(s) that define how one extracts data.

Also I have the same question for the output structures (except this time the required functionality is mutation)?

like image 438
Clinton Avatar asked Jul 11 '12 00:07

Clinton


2 Answers

Whenever you have to choose between explicit function arguments and type classes you should ask yourself this most important question: Are the functions specific to the type or to the application? An example of the former is sort, and an example of the latter is map.

Passing functions is always more flexible, but it may be overkill for your situation and cause unnecessary code bloat. Type classes on the other hand result in much smaller code, but they are also less flexible.

Without further information it's not possible to give a more precise answer here.

like image 142
ertes Avatar answered Sep 22 '22 06:09

ertes


It depends.

The advantage of a type class is that you don't have to explicitly pass around the functions to any helper functions. So, if you have more than two functions or if you're expecting a lot of functions to work with the same basic transformation functions, a type class is probably better.

like image 27
Bill Avatar answered Sep 20 '22 06:09

Bill