Created
January 29, 2019 18:47
-
-
Save JaggerJo/435971cadbfdd4035430aeace437bafd to your computer and use it in GitHub Desktop.
F# State
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* State *) | |
type IState<'data> = | |
abstract member Data: 'data | |
abstract member Update: 'data -> unit | |
[<CLIEvent>] | |
abstract member Updated: IEvent<'data> | |
(* Tracked State *) | |
type ITrackedState<'data> = | |
inherit IState<'data> | |
abstract member Undo: unit -> unit | |
abstract member Redo: unit -> unit | |
(* State *) | |
type State<'data> (init: 'data) = | |
let mutable data = init | |
let updated = new Event<'data> () | |
interface IState<'data> with | |
member __.Data = data | |
member __.Update state = | |
data <- state | |
updated.Trigger data | |
[<CLIEvent>] member __.Updated = updated.Publish | |
(* Tracked State *) | |
type TrackedState<'data> (init: 'data) = | |
let mutable history = [init] | |
let mutable index = 0 | |
let updated = new Event<'data> () | |
interface ITrackedState<'data> with | |
member __.Data = history.Item index | |
member __.Update state = | |
history <- state :: history | |
index <- 0 | |
history.Item index |> updated.Trigger | |
member __.Redo () = | |
if (index - 1) >= 0 then | |
index <- index - 1 | |
history.Item index |> updated.Trigger | |
member __.Undo () = | |
if (index + 1) <= history.Length - 1 then | |
index <- index + 1 | |
history.Item index |> updated.Trigger | |
[<CLIEvent>] member __.Updated = updated.Publish |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment