I am trying to define a function that will concatenate two tuples of (In开发者_StackOverflow中文版t, Char)
like this:
tupleCat :: (Integral a, Char b )=> (a, b) -> (a, b) -> (a, [Char])
tupleCat (x1, y1) (x2, y2) =(x1+ x2, [y1] ++ [y2])
However, I get the following error message:
Type constructor `Char' used as a class ...
What am I doing wrong?
Char
is no type class, it is a type:
tupleCat :: (Integral a) => (a, Char) -> (a, Char) -> (a, [Char])
tupleCat (x1, y1) (x2, y2) =(x1 + x2, [y1] ++ [y2])
And if you really want Int
s and not an Integral
, they are types, too:
tupleCat :: (Int, Char) -> (Int, Char) -> (Int, [Char])
tupleCat (x1, y1) (x2, y2) =(x1+ x2, [y1] ++ [y2])
Further, you might consider to make this a new type and to implement the Monoid type class (as suggested in the comments). One possibility would be
newtype Cat = Cat (Int, String)
instance Monoid Cat where
mempty = Cat (0, [])
mappend (Cat (i1,s1)) (Cat (i2,s2)) = Cat (i1 + i2, s1 ++ s2)
With this definition tupleCat
becomes simply mappend
. Then you can e.g. concatenate the Cat
s in every Foldable
(e.g. a list). Of course I don't know your intentions, so this is just a educated guess.
Good points all around so far, but I think its worth pointing out that YOUR FUNCTION CODE IS OK! You did, however, mess up the type signature. Its not so much that it doesn't match your function, but that Char
is a concrete type, not a typeclass like Integral
, Ord
, Show
etc.
Others have shared the matching type signature, I want to help you get there. Often a good, (at least) first step is to let Haskell determine the type for you.
Prelude> let tupleCat (x1, y1) (x2, y2) =(x1+ x2, [y1] ++ [y2])
Prelude> :t tupleCat
tupleCat :: (Num t) => (t, t1) -> (t, t1) -> (t, [t1])
This is a little more general than you wanted, but replace Num
with Integral
and t1
with Char
and your there.
PS - the Monoid
idea above is a great idea and allows a lot of higher order uses. But don't be worried if it confuses you, it would've thrown me for a loop pretty badly just a few months back.
精彩评论