0

I have following declaration:

data Two a b = Two a b deriving (Eq, Show)

instance (Semigroup a, Semigroup b) => Semigroup (Two a b) where
  (Two a b) <> (Two c d) = Two (a <> c) (b <> d)

And tried it in the prelude:

*Main First Lib MonoidLaws Semi>   (Two a b) <> (Two c d) = Two (a <> c) (b <> d)

<interactive>:10:3: error:
    * Occurs check: cannot construct the infinite type: t1 ~ Two t1 t1
      Expected type: t1 -> t -> b
        Actual type: Two t1 t1 -> Two t t -> Two b b
    * Relevant bindings include
        (<>) :: t1 -> t -> b (bound at <interactive>:10:3)

How can I use mappend function from Semigroup for Two datatype in prelude?

2
  • What are the types of a and b in the repl?
    – Lee
    Jun 27, 2017 at 12:04
  • 2
    What do you hope to accomplish by typing Two a b <> Two c d = Two (a <> c) (b <> d) in the REPL? That's a declaration, i.e. you define a new <> operator there (which is not connected to the one from the Semigroup class). Why? Jun 27, 2017 at 12:27

1 Answer 1

5

Try it with something that's an instance of Semigroup, like List.

For example:

> (Two "1" "2") <> (Two "3" "4")

Two "13" "24"

In your attempt / example, a and b, c and d are not defined, so Haskell sees them as variables. Because you're using = between them, it's assuming you want to do pattern matching, so it's trying to match them to themselves, which is causing an infinite loop (as that is perfectly valid Haskell — to define values in terms of themselves). This is causing an error, though, because it would imply an infinite type, which it definitely seems is not what you want.

It might be worth starting with some simpler things, possibly. A good basic book which I helped author is http://happylearnhaskelltutorial.com but that doesn't deal with instantiating your own typeclasses. Having said that it'll give you a reasonably good understanding of pattern matching, variables, types and values which you'll need before you move on to understanding typeclasses enough to build your own instances.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.