Étude 7-5: Multiple Generators in List Comprehensions

Back to list comprehensions. You can have more than one generator in a list comprehension. Try this in erl:

1> [X * Y || X <- [3, 5, 7], Y <- [2, 4, 6]].
[6,12,18,10,20,30,14,28,42]

Using what you’ve learned from this example, write a module named cards that contains a function make_deck/0. The function will generate a deck of cards as a list 52 tuples in this form:

[{"A","Clubs"},
 {"A","Diamonds"},
 {"A","Hearts"},
 {"A","Spades"},
 {2,"Clubs"},
 {2,"Diamonds"},
 {2,"Hearts"},
 {2,"Spades"},
 ...
 {"K", "Clubs"},
 {"K", "Diamonds"},
 {"K", "Hearts"},
 {"K", "Spades"}]

Note

When you run this function, your output will not show the entire list; it will show something that ends like this. Don’t freak out.

{7,"Clubs"},
{7,"Diamonds"},
{7,[...]},
{7,...},
{...}|...]

If you want to see the full list, use this function.

show_deck(Deck) ->
  lists:foreach(fun(Item) -> io:format("~p~n", [Item]) end, Deck).

See a suggested solution in Appendix A.

Get Études for Erlang now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.