RosettaCodeData/Task/Execute-a-Markov-algorithm/Mathematica/execute-a-markov-algorithm-...

13 lines
564 B
Plaintext

markov[ruleset_, text_] :=
Module[{terminating = False, output = text,
rules = StringCases[
ruleset, {StartOfLine ~~ pattern : Except["\n"] .. ~~
" " | "\t" .. ~~ "->" ~~ " " | "\t" .. ~~ dot : "" | "." ~~
replacement : Except["\n"] .. ~~ EndOfLine :> {pattern,
replacement, dot == "."}}]},
While[! terminating, terminating = True;
Do[If[! StringFreeQ[output, rule[[1]]],
output = StringReplace[output, rule[[1]] -> rule[[2]]];
If[! rule[[3]], terminating = False]; Break[]], {rule, rules}]];
output];