I'm reading Seven Languages in Seven weeks. It's a great book to discover different kind of languages. I went through Ruby, Io, Prolog, Scala and Erlang. So far, Prolog has been the most puzzling of all. For example, the map coloring sample. The author shows how to colorize several states of the United States, without assigning the same color to adjacent states. I finally got the point after noticing that all states names begin with an uppercase letter. Aaaaaaahhhh ! Colors will be assigned to each state (a state is just a variable), and prolog will go through all combinations of colors, returning true only if all combinations in the coloring query return true. Although it was obvious in the food example, food_type(What, meat), for some reason it was not so obvious in the map coloring example...
On the contrary, I'm very interested in Erlang. One of the exercises is to tell in which state a Tic-Tac-Toe board is. Did X win ? Did O win ? No winner yet ? No more moves ? This is the solution I came up with, after several refactoring passes. I like the way we can interact with lists and tuples.
-module(tic).
-export([winner/1]).
winner(Board) ->
[A,B,C,D,E,F,G,H,I] = Board,
% Filter the board for winning combinations
Result = lists:filter(
fun({X,Y,Z}) -> (X=:=Y) and (X=:=Z) end,
[{A,B,C},{D,E,F},{G,H,I},{A,D,G},{B,E,H},{C,F,I},{A,E,I},{C,E,G}]),
% Checking the winner
case Result of
% There is a winner
[First|_] -> {Winner,_,_} = First, Winner;
% No winner
_ ->
% Is there any slot left to play ?
case lists:any(fun(X) -> X=:="" end, Board) of
true -> "no winner";
false -> "cat"
end
end.
No comments:
Post a Comment