Clinton
Clinton

Reputation: 23135

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)?

Upvotes: 8

Views: 580

Answers (4)

tkx68
tkx68

Reputation: 101

A type class provides a unique mapping of types to functions. Therefore you should ask whether you always need the same functions for a type. For example, if you pass a vector to a function and your function needs a norm for the vector, it is usually not a good idea to use type classes since there are many useful norms. In such a case a function parameter is preferable.

Upvotes: 0

ertes
ertes

Reputation: 116

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.

Upvotes: 10

millimoose
millimoose

Reputation: 39970

"I just want to ensure they have a few behaviors that I need." – this pretty much describes what typeclasses are for, I'd go with that. Not sure about the output structure though, I think a function has to return a specific type, you can't return one of several types even if they are instances of the same typeclass.

Upvotes: 0

Bill
Bill

Reputation: 45466

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.

Upvotes: 3

Related Questions