Skip to content

Instantly share code, notes, and snippets.

@jigargandhi
Created September 15, 2018 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jigargandhi/c9a0a3ded09cffef190fde95ba7a4c45 to your computer and use it in GitHub Desktop.
Save jigargandhi/c9a0a3ded09cffef190fde95ba7a4c45 to your computer and use it in GitHub Desktop.
Memento Pattern in F#
// Memento Pattern in F#
type State<'T> = {State: State<'T> option; CurrentItem: 'T}
//'T -> State<'T>
let createState (instance :'T) =
{State=None; CurrentItem= instance}
//('a->'a)->State<'a>->State<'b'>
let updateState modifier currentState =
let newObject = modifier currentState.CurrentItem
{ State =Some currentState; CurrentItem = newObject}
let getPreviousState state =
match state.State with
| Some x -> x
| None -> failwith "No Old state"
type Person = { Name: string}
let changeNameTo name person =
{person with Name=name}
let person = {Name="Jigar"}
let finalState = createState person
|> updateState (changeNameTo "GitHub")
// GitHub
printfn "Current Name: %s" finalState.CurrentItem.Name
let previousState = getPreviousState finalState
//Jigar
printfn "Previous Name: %s" previousState.CurrentItem.Name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment