Haskell: design pattern: classes or skip functions

Suppose I have a function that takes some input structure and returns some output structure (which may be related to the input structure, but different from it).

I don't want these I / O structures to be bound to a specific type, I just want to make sure that they have several behaviors that I need.

Should I?

a) Define a class that has the appropriate extraction methods and force the input to be an instance of this class? OR
b) Ask the function to accept another parameter, which is the function (s) that determines how to retrieve the data.

Also, I have the same question for output structures (except that the required functionality is a mutation)?

+8
design design-patterns haskell
source share
4 answers

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

The transfer functions are always more flexible, but this may be redundant for your situation and cause unnecessary bloating of the code. Classes, on the other hand, lead to significantly smaller code, but they are also less flexible.

Without additional information, it is impossible to give a more accurate answer.

+10
source share

It depends.

The advantage of a type class is that you do not need to explicitly pass functions to any helper functions. So, if you have more than two functions or you expect that many functions will work with the same basic conversion functions, a type class is probably better.

+3
source share

"I just want them to have a few actions that I need." - It pretty much describes for what types of models I would go with this. However, I’m not sure about the structure of the output, I think that the function should return a certain type, you cannot return one of several types, even if they are instances of the same class.

0
source share

The type class provides a unique type mapping with functions. Therefore, you should ask if 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 recommended to use type classes, since there are many useful norms. In this case, a function parameter is preferred.

0
source share

All Articles