word_split.erl 1.1 KB

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