Pukka
Pukka

Reputation: 31

Own instance of Num with a String Datatype

I want to turn my Dataconstructor MP into an instance of Num

MP looks like this data MP = MP String and the string is build only of + and - e.g. "++-+-+" where every + represents a +1 and a - represents -1.

I also have already a function that normalize that string e.g. "++-+-+" to "++"

nrm "" = ""
nrm (c:t) = take c (nrm t)
  where
    take c "" = [c]
    take c (s:xs)
      | c == s     = c:s:xs
      | otherwise  = xs

And now I would like to turn this into an instance of Num like this:

instance Num MP where
  (+) = undefined
  (*) = undefined
  negate = undefined
  signum = undefined
  abs = undefined
  fromInteger = undefined

So at the End it should work like this "+++" + "-" = "++" or "+++" * "-" = "---" and so on.

Does someone have an Idea how I could do this?

Upvotes: 0

Views: 50

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152682

You say:

I have tried (+) (MP a) (MP b) = (a++b)

You are correctly writing a function that accepts values of type MP, but you must also return a value of type MP, as in (+) (MP a) (MP b) = MP (a ++ b). There are still bugs in that implementation, of course, but that should get you over the first hump and on to something you can play with further yourself.

Upvotes: 1

Related Questions