Okay. You can pair it manually through recursion if you prefer. But you could also use list comprehensions, or some lifting.
In any of the approaches, you can pair them together with tuples, rather than a list since it seems like you only want a fixed amount of elements with varying types Fruit
and Ncolour
. Normally, lists in Haskell are homogeneous so you can’t have an element that’s a Fruit
, and another element that’s an Ncolour
.
i.e You can’t (normally) do [Numeric 2, Apple]
, but you can do (Numeric 2, Apple)
.
List comprehension
List comprehensions gets you the cartesian product, which is what you’re looking for. (You can read more about list comprehensions here).
fruitColorPairsLC :: [(Ncolour, Fruit)]
fruitColorPairsLC =
[(nColour, fruit) |
nColour <- [Numeric 2, Red, Yellow, Green],
fruit <- [Apple, Banana, Pear, Cherry] ]
Lifting
If you want to explore the concept of functors and applicatives, using both can also give you the same result. This one is really cool, but do this when you’re more comfortable with recursion and whatnot.
fruitColorPairsLift :: [(Fruit, Ncolour)]
fruitColorPairsLift =
liftA2 (,)
[Numeric 2, Red, Yellow, Green]
[Apple, Banana, Pear, Cherry]
or this is equivalent to
fruitColorPairsLift :: [(Ncolour, Fruit)]
fruitColorPairsLift =
(,) <$> [Numeric 2, Red, Yellow, Green] <*> [Apple, Banana, Pear, Cherry]
This lifts the binary function (,)
to work with a list context. It’s a lot to get into so some helpful resources, when you choose to study these type classes, are:
- https://github.com/kowainik/learn4haskell
- https://github.com/system-f/fp-course
- https://haskellbook.com/
Either approach gives you
[(Numeric 2,Apple),(Numeric 2,Banana),(Numeric 2,Pear),(Numeric 2,Cherry),(Red,Apple),(Red,Banana),(Red,Pear),(Red,Cherry),(Yellow,Apple),(Yellow,Banana),(Yellow,Pear),(Yellow,Cherry),(Green,Apple),(Green,Banana),(Green,Pear),(Green,Cherry)]