Extension to Erlang
Joe Armstrong
joe@REDACTED
Thu Nov 27 14:15:59 CET 2003
Hi Guys,
I'd lkie to posproe an einotsexn to the fatrnoimig civoentonns uesd
in io:foamrt. I'd lkie to see a ~w wichh wpars the opuutt text.
I have wtteirn warp.erl wihch waprs a flie (apdepned) - it should be
pttery esay to ilnudce tihs itno the sraatdnd laiirebrs.
This ieda is besad on smoe ctintug edge reecrash at Cgramidbe
Uientvsiry which has shwon that it deosn't rellay mttear how wrods are
selpt as long as the frist and lsat lrttees are cecorrt.
Cehers
/Joe
---- cut ----
-module(warp).
-import(lists, [map/2, reverse/1]).
-export([file/1, word/1]).
file(F) ->
{ok, B} = file:read_file(F),
L = binary_to_list(B),
L1 = tokenise(L, []),
Lines = map(fun warp_line/1, L1),
file:write_file(F ++ ".warp", Lines).
is_alpha(X) when X >= $a, X =< $z -> true;
is_alpha(X) when X >= $A, X =< $Z -> true;
is_alpha(X) -> false.
tokenise(All = [H|T], L) ->
case is_alpha(H) of
true ->
{Word, Rest} = collect_while(fun is_alpha/1, All),
tokenise(Rest, [{word,Word}|L]);
false ->
tokenise(T, [H|L])
end;
tokenise([], L) ->
reverse(L).
collect_while(Pred, L) ->
collect_while(Pred, L, []).
collect_while(pred, [], L) ->
{[], reverse(L)};
collect_while(Pred, All = [H|T], L) ->
case Pred(H) of
true ->
collect_while(Pred, T, [H|L]);
false ->
{reverse(L), All}
end.
warp_line({word,L}) -> word(L);
warp_line(X) -> X.
word([X]) ->
X;
word([H|T]) ->
[Last|R] = reverse(T),
[H|reverse([Last|warp_word(R, [])])].
warp_word([], L) ->
L;
warp_word(L1, L2) ->
N = random:uniform(length(L1)),
{H,T} = take_nth(N, L1, []),
warp_word(T, [H|L2]).
take_nth(1, [H|T], L) -> {H, T ++ L};
take_nth(N, [H|T], L) -> take_nth(N-1, T, [H|L]).
More information about the erlang-questions
mailing list