Home > Software design >  Haskell make a List of own defined type
Haskell make a List of own defined type

Time:10-18

If I have a defined data type, say:

data Tag = Tag Char Int

Is there a way to define a List of Tag like this:

[("A",1),("A",2),("A",3),("B",1),("B",2)..............("D",2),("D",3)]

Instead of hard-coded?

CodePudding user response:

Yes, you can construct a list with:

[Tag 'A' 1, Tag 'A' 2, Tag 'A' 3, Tag 'B' 1, Tag 'B' 2, Tag 'B' 3, Tag 'C' 1, Tag 'C' 2, Tag 'C' 3, Tag 'D' 1, Tag 'D' 2, Tag 'D' 3]

If you want to use values from two lists, you can work with:

Tag <$> "ABCD" <*> [1,2,3]

This makes use of the instance of a Functor and Applicative of the list instance. This means that Tag <$> "ABCD" will return a list of functions like [Tag 'A', Tag 'B', Tag 'C', Tag 'D'], next it will make use of the (<*>) :: Applicative f => f (a -> b) -> f a -> f b which will take a list of functions and a list of values, and will return a list that contains any combination of a function from the first list, and a value from the second list.

CodePudding user response:

uncurry Tag has type (Char, Int) -> Tag, so if you want to use tuple syntax in your initializer list, you can do so like this:

myTags = uncurry Tag <$> [("A",1),("A",2),("A",3),("B",1),("B",2)..............("D",2),("D",3)]
  • Related