Skip to content

Instantly share code, notes, and snippets.

@JordanMarr
Last active December 9, 2021 04:35
Show Gist options
  • Save JordanMarr/cfce8639247ee9d6833aba918046bcb5 to your computer and use it in GitHub Desktop.
Save JordanMarr/cfce8639247ee9d6833aba918046bcb5 to your computer and use it in GitHub Desktop.
namespace Sample
type MetadataResult<'value> =
{
Value: 'value
Metadata: (string * string) list
}
module MetadataResult =
let init (value: 'a) =
{ Value = value; Metadata = [] }
let bind (binder: 'a -> 'b) (result: MetadataResult<'a>) =
{ Value = binder result.Value
; Metadata = result.Metadata }
let logMetadata key value result =
{ result with
Metadata = result.Metadata @ [ key, value ] }
let logTimestamp result =
result
|> logMetadata "timestamp" (System.DateTime.Now.ToShortTimeString())
let print result =
let metadata = result.Metadata
printfn $"Result: {result.Value}"
printfn "Metadata:"
for key, value in result.Metadata do
printfn $"- {key}: {value}"
module Sample.App =
let createOne () =
1
|> MetadataResult.init
|> MetadataResult.logMetadata "action" "Started with 1"
|> MetadataResult.logTimestamp
let addOne numberResult =
numberResult
|> MetadataResult.bind (fun number -> number + 1)
|> MetadataResult.logMetadata "action" "+ 1"
|> MetadataResult.logTimestamp
let multiplyByTwo numberResult =
numberResult
|> MetadataResult.bind (fun number -> number * 2)
|> MetadataResult.logMetadata "action" "* 2"
|> MetadataResult.logTimestamp
let toString numberResult =
numberResult
|> MetadataResult.bind string
|> MetadataResult.logMetadata "action" "stringified"
|> MetadataResult.logTimestamp
let run () =
createOne ()
|> addOne
|> multiplyByTwo
|> toString
|> MetadataResult.print
module Sample.Program
let [<EntryPoint>] main _ =
App.run ()
Result: 4
Metadata:
- 'action': Started with 1
- 'timestamp': 10:10 PM
- 'action': + 1
- 'timestamp': 10:10 PM
- 'action': * 2
- 'timestamp': 10:10 PM
- 'action': stringified
- 'timestamp': 10:10 PM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment