I am a beginner in Haskell and trying to learn about typeclasses and types. I have the following example (which represents a real problem in algebra that I am working on), in which I define a type which just wraps Num instances, and a typeclass which defines a binary operation baz.
newtype Foo i = B i deriving (Eq, Ord, Show)
class Bar k where
baz :: k -> k -> k
instance Num k => Bar (Foo k) where
baz (B a) (B b) = B (f a b)
f :: Num a => a -> a -> a
f a b = a + b
When defining Bar to be an instance of this, I realize that I want to be able to "vary" the function f with the type. To be clear: I want to supply a function f :: Num a => a -> a -> a and get back a new type Foo which is an instance of Bar. Say that I want to do this 5, 10 times with the only difference being different functions f. I can of course copy and paste the code above, but I wonder if there is another way?
It seems to me that I'm confusing things. What is the best way of doing something like this in Haskell? Is this a good choice of design, what am I thinking right/wrong and why?
EDIT: I realize that a concrete example might help to make the question clearer (beware that it may seem complicated, I was not able to simplify the code more than this. The question above contains the same information I think): the typeclass I am interested in is Algebra k v from the library HaskellForMaths:
class Algebra k b where
unit :: k -> Vect k b
mult :: Vect k (Tensor b b) -> Vect k b
Here k is a field (a mathematical structure such as the real or complex numbers), while v is a choice of basis in a vector space. I would want to use it something like this
newtype Basis i = T i deriving (Eq, Ord, Show)
type Expression k = Vect k (Basis Int)
instance Algebra k Basis where
unit x = x *> return I
mult = linear mult'
where mult' (T x ,T y) = comm x y
where comm a b = sum $ map (\c -> structure a b c *> t c) [0..n]
t :: Int -> Expression k
t a = return (T a)
and then vary the map structure as I please. Here the type T is just a convenient way of writing abstract basis elements T 1, T 2, .... The reason I want to do it is the standard mathematical definition of an algebra in terms of its structure constants (here: structure). To summarize: I want to be able to vary the function f (preferably not at compile time?) and get back an algebra. This may be a bad design decision: if so, why?