Advertisement
migulorama

Untitled

Feb 23rd, 2014
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.05 KB | None | 0 0
  1. //
  2. // Scala implementation to test strings that match the expression a*bb* | aa*bc* | ef
  3. // by Miguel Marques
  4. //
  5.  
  6. object Main {
  7.  
  8.   val characters = Map('a' -> 0, 'b' -> 1, 'c' -> 2, 'e' -> 3, 'f' -> 4).withDefaultValue(5)
  9.  
  10.   val transitions = Array(
  11.     Array(0, 0, 0, 0, 0, 0),
  12.     Array(2, 3, 0, 6, 0, 0),
  13.     Array(2, 4, 0, 0, 0, 0),
  14.     Array(0, 3, 0, 0, 0, 0),
  15.     Array(0, 3, 5, 0, 0, 0),
  16.     Array(0, 0, 5, 0, 0, 0),
  17.     Array(0, 0, 0, 0, 7, 0),
  18.     Array(0, 0, 0, 0, 0, 0))
  19.  
  20.   val initialState = 1
  21.   val finalStates = Set(3, 4, 5, 7)
  22.  
  23.   def eval(str: String): Boolean =
  24.     finalStates contains (
  25.       str.foldLeft(initialState) { (state, character) =>
  26.         val charInt = characters(character)
  27.         transitions(state)(charInt)
  28.       })
  29.  
  30.   def main(args: Array[String]): Unit = {
  31.     Stream continually {
  32.       print("Enter a string to test (ctrl+z to exit): ")
  33.       readLine
  34.     } takeWhile (_ != null) foreach { line =>
  35.       println(if (eval(line)) "accept" else "reject")
  36.     }
  37.  
  38.     println("\nBye!!!")
  39.   }
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement