Execute a Markov algorithm: Difference between revisions
Content deleted Content added
→{{header|AutoHotkey}}: Added AHK |
Added Scala |
||
Line 735: | Line 735: | ||
}) |
}) |
||
end</lang> |
end</lang> |
||
=={{header|Scala}}== |
|||
{{works with|Scala|2.8}} |
|||
<lang scala>import scala.annotation.tailrec |
|||
import scala.io.Source |
|||
object MarkovAlgorithm { |
|||
val RulePattern = """(.*?)\s+->\s+(\.?)(.*)""".r |
|||
val CommentPattern = """#.*|\s*""".r |
|||
def rule(line: String) = line match { |
|||
case CommentPattern() => None |
|||
case RulePattern(pattern, terminal, replacement) => Some(pattern, replacement, terminal == ".") |
|||
case _ => error("Syntax error on line "+line) |
|||
} |
|||
def main(args: Array[String]) { |
|||
if (args.size != 2 ) { |
|||
println("Syntax: MarkovAlgorithm inputFile inputPattern") |
|||
exit(1) |
|||
} |
|||
val rules = (Source fromPath args(0) getLines () map rule).toList.flatten |
|||
def algorithm(input: String): String = rules find (input contains _._1) match { |
|||
case Some((pattern, replacement, true)) => input replaceFirst ("\\Q"+pattern+"\\E", replacement) |
|||
case Some((pattern, replacement, false)) => algorithm(input replaceFirst ("\\Q"+pattern+"\\E", replacement)) |
|||
case None => input |
|||
} |
|||
println(args(1)) |
|||
println(algorithm(args(1))) |
|||
} |
|||
}</lang> |
|||
Sample outputs: |
|||
<pre> |
|||
C:\>scala MarkovAlgorithm ruleset1.txt "I bought a B of As from T S." |
|||
I bought a B of As from T S. |
|||
I bought a bag of apples from my brother. |
|||
C:\>scala MarkovAlgorithm ruleset2.txt "I bought a B of As from T S." |
|||
I bought a B of As from T S. |
|||
I bought a bag of apples from T shop. |
|||
C:\>scala MarkovAlgorithm ruleset3.txt "I bought a B of As W my Bgage from T S." |
|||
I bought a B of As W my Bgage from T S. |
|||
I bought a bag of apples with my money from T shop. |
|||
C:\>scala MarkovAlgorithm ruleset4.txt "_1111*11111_" |
|||
_1111*11111_ |
|||
11111111111111111111 |
|||
</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |