Created
September 15, 2018 12:27
-
-
Save jigargandhi/c9a0a3ded09cffef190fde95ba7a4c45 to your computer and use it in GitHub Desktop.
Memento Pattern in F#
This file contains 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
// 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