-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslit
executable file
·78 lines (65 loc) · 2.18 KB
/
translit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env escript
%% translit -- map characters
translit([FromSet, ToSet, File]) ->
Map = mpattern(FromSet, ToSet),
translit(File, Map, []).
translit([], _, Acc) ->
ststd:io({output, file}, Acc);
translit([H|T], Map, Acc) ->
case maps:find(H, Map) of
{ok, Change} -> translit(T, Map, lists:concat([Acc, [Change]]));
error -> translit(T, Map, lists:concat([Acc, [H]]))
end.
%% squashing -- substitute pattern for a single symbol
%%
%% Generate special Map, and reuses translit/3
squashing([FromSet, ToSet, File]) ->
CharList = lists:map(fun(_) -> ToSet end, lists:seq(1, erlang:length(FromSet))),
Map = mpattern(FromSet, CharList),
translit(File, Map, []).
%% deleteall -- delete all occurrences of pattern
%%
%% Generate special Map, and reuses translit/3
deleteall([FromSet, File]) ->
BlankList = lists:map(fun(_) -> [] end, lists:seq(1, erlang:length(FromSet))),
Map = mpattern(FromSet, BlankList),
translit(File, Map, []).
%% mpattern -- transform two Args (chars or lists) into a map
mpattern(FromSet, ToSet) ->
maps:from_list(lists:zip(FromSet, ToSet)).
%% parse -- detect pattern and return list
parse([Letter|[]]) ->
[Letter];
parse([Base,45,End|[]]) ->
List = lists:seq(Base,End),
List;
parse([Base,45,End|T]) ->
List = lists:seq(Base, End),
Tail = parse(T),
lists:concat([List, Tail]).
%% main -- receive and parse args
main([]) ->
halt(1);
main([_|[]]) ->
halt(1);
%% Arg1 = pattern
%% Arg2 = file
%% one pattern means to delete all occurrences on file
main([Arg, File|[]]) ->
FromSet = parse(Arg),
Input = ststd:io({input, file}, File),
deleteall([FromSet, Input]);
%% Arg1 = pattern (fromset)
%% Arg2 = pattern (toset)
%% Arg3 = file
main([Arg1, Arg2, File|[]]) ->
FromSet = parse(Arg1),
ToSet = parse(Arg2),
Input = ststd:io({input, file}, File),
selector(FromSet, ToSet, Input).
%% transliterate characters from Arg1[i] to Arg2[i]
%% if Arg2 is shorter than Arg1, squash instead
selector(FromSet,ToSet,File) when erlang:length(ToSet) < erlang:length(FromSet) ->
squashing([FromSet, ToSet, File]);
selector(FromSet, ToSet, File) ->
translit([FromSet, ToSet, File]).