Created
January 3, 2010 03:31
-
-
Save OJ/267801 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%% My second code kata. | |
%% This is the first part of the question listed at this URL: | |
%% http://codekata.pragprog.com/2007/01/kata_eight_conf.html | |
%% more to come later. | |
-module(words). | |
-author('OJ Reeves <[email protected]>'). | |
-export([composition/1]). | |
-define(WORDLENGTH, 6). | |
composition(FileName) -> | |
Words = lists:map(fun string:to_lower/1, file_to_list(FileName)), | |
CW = composable_words(Words), | |
Results = lists:map(fun(W) -> composition(W, Words) end, CW), | |
lists:map(fun show_result/1, Results). | |
show_result(none) -> | |
ok; | |
show_result({ok, List}) -> | |
lists:map(fun({F,B}) -> io:format("~s + ~s => ~s~s~n", [F, B, F, B]) end, List). | |
composition(Word, Dict) -> | |
composition(breakdown(Word), Dict, []). | |
composition([], _, Accum) -> | |
case Accum of | |
[] -> none; | |
_ -> {ok, Accum} | |
end; | |
composition([Pair={Front,Back}|T], Dict, Accum) -> | |
case {lists:member(Front, Dict), lists:member(Back, Dict)} of | |
{true, true} -> composition(T, Dict, [Pair|Accum]); | |
_ -> composition(T, Dict, Accum) | |
end. | |
file_to_list(FileName) -> | |
{ok, Bin} = file:read_file(FileName), | |
string:tokens(binary_to_list(Bin), "\n"). | |
composable_words(Words) -> | |
lists:filter(fun(Word) -> length(Word) =:= ?WORDLENGTH end, Words). | |
breakdown(Word) -> | |
[_|W] = lists:zip(inits(Word), tails(Word)), | |
lists:takewhile(fun({_,X}) -> X =/= [] end, W). | |
inits([]) -> | |
[[]]; | |
inits([H|T]) -> | |
Inits = inits(T), | |
Tail = lists:map(fun(X) -> [H|X] end, Inits), | |
[[]|Tail]. | |
tails([]) -> | |
[[]]; | |
tails(List=[_|T]) -> | |
[List|tails(T)]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment