Skip to content

Instantly share code, notes, and snippets.

@FoleyAxel
Last active December 26, 2015 00:19
Show Gist options
  • Select an option

  • Save FoleyAxel/7063687 to your computer and use it in GitHub Desktop.

Select an option

Save FoleyAxel/7063687 to your computer and use it in GitHub Desktop.
mailbox clear
open System
type resultMsg =
| Add of string
| Fetch of AsyncReplyChannel<Set<string>>
| Clear
type Cache =
{
Add: string -> unit
Clear: unit
Fetch: unit -> Set<string>
}
let cache =
let mb =
MailboxProcessor.Start(fun inbox ->
let rec loop data =
async {
let! msg = inbox.Receive()
match msg with
| Add x -> return! loop (Set.add x data)
| Clear -> return! loop Set.empty
| Fetch reply ->
reply.Reply data
return! loop data
}
loop Set.empty
)
{
Add = Add >> mb.Post
Clear = mb.Post Clear
Fetch = fun() -> mb.PostAndReply Fetch
}
cache.Add "1"
cache.Add "2"
cache.Add "3"
cache.Fetch()
|> Seq.iter Console.WriteLine
cache.Clear
cache.Add "3"
cache.Add "2"
cache.Add "1"
cache.Fetch()
|> Seq.iter Console.WriteLine
@FoleyAxel
Copy link
Author

open System

type resultMsg =
    | Add of string
    | Fetch of AsyncReplyChannel<Set<string>>
    | Clear

type Cache =
    {
        Add: string -> unit
        Clear: unit -> unit
        Fetch: unit -> Set<string>
    }

let cache =
    let mb =
        MailboxProcessor.Start(fun inbox ->
            let rec loop data =
                async {
                    let! msg = inbox.Receive()
                    match msg with
                    | Add x -> return! loop (Set.add x data)
                    | Clear -> "WAAAAAA!!" |> Console.WriteLine
                               return! loop Set.empty
                    | Fetch reply ->
                        reply.Reply data
                        return! loop data
                }
            loop Set.empty
        )
    {
        Add = Add >> mb.Post
        Clear = fun() -> mb.Post Clear
        Fetch = fun() -> mb.PostAndReply Fetch
    }

cache.Add "1"
cache.Add "2"
cache.Add "3"
cache.Fetch()
|> Seq.iter Console.WriteLine
cache.Clear()
cache.Add "3"
cache.Add "2"
cache.Add "1"
cache.Fetch()
|> Seq.iter Console.WriteLine

Console.ReadLine() |> ignore

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment