Neo Streets
Neo Streets

Reputation: 535

Want to add to a data type in Haskell

Hi I have a data type which is

data MyIntStr = MyIntStr { intList :: IntList, strList :: StrInt}
type IntList = [[Int]]
type StrList = [[String]]

and I want to add things to the intList and strList in MyData. So I'm passing a default data which is just empty and then trying to add Ints to the Intlist:

putInts :: [Int] -> MyIntStr -> MyIntStr
putInts (h:t) d
    |length t /= 0 = putInts t (intList:h)
    |otherwise intList:h

this gives errors any ideas how to do this?

Upvotes: 0

Views: 71

Answers (1)

Random Dev
Random Dev

Reputation: 52270

Just to end this with some constructive aid (or so I hope) here is a version that should do what you expect:

type IntList = [Int]
type StrList = [String]

data MyIntStr = MyIntStr { intList :: IntList, strList :: StrList }
              deriving Show

empty :: MyIntStr
empty = MyIntStr [] []

putInts :: [Int] -> MyIntStr -> MyIntStr
putInts is (MyIntStr is' ss) = MyIntStr (is'++is) ss

here is an example:

λ> putInts [1,2,3] empty
MyIntStr {intList = [1,2,3], strList = []}

what I did:

  • added deriving Show so I can see my example ;)
  • changed StrInt into StrList because you obviously meant it
  • added empty so I could test
  • rewrote putInts using pattern matching and ++ to concatenate your [Int] lists

Upvotes: 2

Related Questions