//
// Author: Hongwei Xi (hwxi AT cs DOT bu DOT edu)
// Time: January, 2009
//

(*

M1 = (Q, Sigma, q0, delta, F)

Sigma = {0, 1}

The start state is q1

The transition function delta is

   |  0  1
------------------
q1 | q1 q2
------------------
q2 | q3 q2
------------------
q3 | q2 q2
------------------

F = { q2 }

*)

typedef state_t = int
typedef letter_t = char

extern val start: state_t
extern fun delta (s: state_t, a: letter_t): state_t
extern fun isfinal (s: state_t): bool

implement start = 1
implement delta (s, a) = let
  fn err1 (a: letter_t): state_t = begin
    prerr "Illegal input letter: "; prerr a; prerr_newline (); exit (1)
  end // end of [err1]
in
  case+ s of
  | 1 => begin case+ a of
    | '0' => 1 | '1' => 2 | _ => err1 (a)
    end // end of [1]
  | 2 => begin case+ a of
    | '0' => 3 | '1' => 2 | _ => err1 (a)
    end // end of [2]
  | 3 => begin case+ a of
    | '0' => 2 | '1' => 2 | _ => err1 (a)
    end // end of [3]
  | _ => begin
      prerr "Illegal state s = "; prerr s; prerr_newline ();
      exit (1)
    end // end of [_]
end // end of [delta]

implement isfinal (s: state_t) =
  if (s = 2) then true else false
// end of [isfinal]

(* ****** ****** *)

extern fun accept (s: string): bool

implement accept (str) = loop (str, start, 0) where {
  val str = string1_of_string (str)
  fun loop {n,i:nat | i <= n} .<n-i>.
    (str: string n, s: state_t, i: size_t i): bool =
    if string_is_atend (str, i) then isfinal (s) else let
      val a = str[i]; val s1 = delta (s, a) in loop (str, s1, i+1)
    end // end of [if]
  // end of [loop]
}

(* ****** ****** *)

implement main (argc, argv) = let
  val () = assert (argc >= 2)
  val str = argv.[1]
  val ans = accept (str)
in
  printf ("accept(%s) = ", @(str)); print ans; print_newline ()
end // end of [main]

(* ****** ****** *)

(* end of [DFA_example1.dats] *)