É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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.119.114