Skip to content

Instantly share code, notes, and snippets.

@Heimdell
Last active December 19, 2015 11:19
Show Gist options
  • Save Heimdell/5946453 to your computer and use it in GitHub Desktop.
Save Heimdell/5946453 to your computer and use it in GitHub Desktop.
State machine test
type 'state machine =
{ state : 'state
; transitions : ('state transition) list
}
and 'state transition =
{ predicate : 'state -> bool
; arrow : 'state -> 'state
; name : string
}
let ( *= ) sm f =
{ sm with state = f.arrow sm.state }
let fulfills state = fun x -> x.predicate state
let decision sm =
List.find (fulfills sm.state) sm.transitions
let final_state sm =
not (List.exists (fulfills sm.state) sm.transitions)
let const x y = x
let rec run sm =
match final_state sm with
| true -> []
| false ->
let transition = decision sm in
let neue = sm *= transition in
( sm.state
, transition.name
, neue.state
) ::
run neue
let rec all preds = fun x ->
match preds with
| [] -> true
| pred :: rest -> pred x && (all rest) x
let dump machine =
List.iter
(fun (was, arrow, become) ->
Printf.printf "%s\t: %d\t -> %d\n" arrow was become
)
(run machine)
let () =
let machine =
{ state = 0
; transitions =
[ { predicate = all
[ (fun x -> x mod 2 = 1)
; (( >= ) 20)
]
; arrow = ( + ) 1
; name = "inc"
}
; { predicate = all
[ (fun x -> x mod 2 = 0)
]
; arrow = ( + ) 3
; name = "trinc"
}
]
}
in
dump machine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment