word_split.erl 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. -module(word_split).
  2. -export([words/1, to_list/1, words_from_file/1]).
  3. % data WordState = {chunk, S} | {segment, L, C, R}
  4. nil() ->
  5. nil.
  6. singleton(S) ->
  7. {single, S}.
  8. conc(A, B) ->
  9. {conc, A, B}.
  10. to_list(nil) ->
  11. [];
  12. to_list({single, S}) ->
  13. [S];
  14. to_list({conc, A, B}) ->
  15. to_list(A) ++ to_list(B).
  16. maybe_word("") ->
  17. nil();
  18. maybe_word(S) ->
  19. singleton(S).
  20. process_char(C) ->
  21. case lists:member(C, " \t\n\f\l") of
  22. true ->
  23. {segment, "", nil(), ""};
  24. false ->
  25. {chunk, [C]}
  26. end.
  27. combine({chunk, S1}, {chunk, S2}) ->
  28. {chunk, S1 ++ S2};
  29. combine({chunk, S}, {segment, L, C, R}) ->
  30. {segment, S ++ L, C, R};
  31. combine({segment, L, C, R}, {chunk, S}) ->
  32. {segment, L, C, R ++ S};
  33. combine({segment, L1, C1, R1}, {segment, L2, C2, R2}) ->
  34. {segment, L1, conc(C1, conc(maybe_word(R1 ++ L2), C2)), R2}.
  35. words(Str) ->
  36. T = ebb_flow:map_reduce(fun process_char/1,
  37. fun(X, Y) -> combine(X, Y) end,
  38. Str),
  39. case ebb_run:run_distributed(T) of
  40. {ok, [{chunk, S}]} ->
  41. to_list(maybe_word(S));
  42. {ok, [{segment, L, C, R}]} ->
  43. to_list(conc(maybe_word(L), conc(C, maybe_word(R))));
  44. _ ->
  45. error
  46. end.
  47. words_from_file(Str) ->
  48. case file:read_file(Str) of
  49. {ok, Data} ->
  50. io:format("Number of words: ~w\n", [length(words(binary_to_list(Data)))]);
  51. _ ->
  52. io:format("File not found!")
  53. end.