Skip to content

Instantly share code, notes, and snippets.

@1tgr
Created June 19, 2012 10:11
Show Gist options
  • Select an option

  • Save 1tgr/2953367 to your computer and use it in GitHub Desktop.

Select an option

Save 1tgr/2953367 to your computer and use it in GitHub Desktop.
Given two sequences of items (identified by keys), generate adds/updates/deletes to make one sequence look like the other
module Utils =
let updateWith
(localKey : 'Local -> 'Key)
(remoteKey : 'Remote -> 'Key)
(add : 'State -> 'Local -> 'State)
(update : 'State -> 'Local -> 'Remote -> 'State)
(delete : 'State -> 'Remote -> 'State)
(state : 'State)
(local : #seq<'Local>)
(remote : #seq<'Remote>)
: 'State
=
let localMap = Map.ofSeq <| seq { for l in local -> localKey l, l }
let state, adds =
let folder (state, adds) r =
let key = remoteKey r
let state =
match Map.tryFind key localMap with
| Some l -> update state l r
| None -> delete state r
state, Map.remove key adds
Seq.fold folder (state, localMap) remote
Map.fold (fun state _ -> add state) state adds
let update
(localKey : 'Local -> 'Key)
(remoteKey : 'Remote -> 'Key)
(add : 'Local -> unit)
(update : 'Local -> 'Remote -> unit)
(delete : 'Remote -> unit)
(local : #seq<'Local>)
(remote : #seq<'Remote>)
: unit
=
updateWith localKey remoteKey (fun () -> add) (fun () -> update) (fun () -> delete) () local remote
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment