Execute a Markov algorithm: Difference between revisions
Content added Content deleted
(→{{header|Java}}: added Java) |
(Added zkl) |
||
Line 3,563: | Line 3,563: | ||
00011H1111000 |
00011H1111000 |
||
</lang> |
</lang> |
||
=={{header|zkl}}== |
|||
<lang zkl> |
|||
fcn parseRuleSet(lines){ |
|||
if(vm.numArgs>1) lines=vm.arglist; // lines or object |
|||
ks:=L(); vs:=L(); |
|||
foreach line in (lines){ |
|||
if(line[0]=="#") continue; // nuke <comment> |
|||
pattern,replacement:=line.split(" -> ",1).apply("strip"); |
|||
ks.append(pattern); vs.append(replacement); |
|||
} |
|||
return(ks,vs); |
|||
} |
|||
fcn markov(text,rules){ |
|||
ks,vs:=rules; eks:=ks.enumerate(); |
|||
do{ go:=False; |
|||
foreach n,k in (eks){ |
|||
if (Void!=text.find(k)){ |
|||
if (Void==(v:=vs[n])) return(text); |
|||
if (v[0,1]==".") v=v[1,*] else go=True; |
|||
text=text.replace(k,v,1); |
|||
break; // restart after every rule application, unless terminating |
|||
} |
|||
} |
|||
}while(go); |
|||
text |
|||
}</lang> |
|||
<lang zkl>ruleSet:=parseRuleSet("# This rules file is extracted from Wikipedia:", |
|||
"# http://en.wikipedia.org/wiki/Markov_Algorithm", |
|||
"A -> apple", "B -> bag", "S -> shop", "T -> the", |
|||
"the shop -> my brother", "a never used -> .terminating rule"); |
|||
ruleSet.println(); |
|||
markov("I bought a B of As from T S.",ruleSet).println();</lang> |
|||
{{out}} |
|||
<pre> |
|||
L(L("A","B","S","T","the shop","a never used"),L("apple","bag","shop","the","my brother",".terminating rule")) |
|||
I bought a bag of apples from my brother. |
|||
</pre> |
|||
<lang zkl>parseRuleSet("# Slightly modified from the rules on Wikipedia", |
|||
"A -> apple", "B -> bag", "S -> .shop", "T -> the", |
|||
"the shop -> my brother", "a never used -> .terminating rule") : |
|||
markov("I bought a B of As from T S.",_).println(); |
|||
parseRuleSet("# BNF Syntax testing rules", "A -> apple", |
|||
"WWWW -> with", "Bgage -> ->.*", "B -> bag", "->.* -> money", |
|||
"W -> WW", "S -> .shop", "T -> the", |
|||
"the shop -> my brother", "a never used -> .terminating rule") : |
|||
markov("I bought a B of As W my Bgage from T S.",_).println();</lang> |
|||
{{out}} |
|||
<pre> |
|||
I bought a bag of apples from T shop. |
|||
I bought a bag of apples with my money from T shop. |
|||
</pre> |
|||
For the next two tasks, read the rule set from a file. |
|||
<lang zkl>parseRuleSet(File("ruleSet4")) : markov("_1111*11111_",_).println(); |
|||
parseRuleSet(File("ruleSet5")) : markov("000000A000000",_).println();</lang> |
|||
{{out}} |
|||
<pre> |
|||
11111111111111111111 |
|||
00011H1111000 |
|||
</pre> |
|||
{{omit from|GUISS}} |
{{omit from|GUISS}} |