Skip to content

Instantly share code, notes, and snippets.

@Swoorup
Created June 13, 2019 14:28
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 Swoorup/bc9678f05d935d23fa0766984c908a18 to your computer and use it in GitHub Desktop.
Save Swoorup/bc9678f05d935d23fa0766984c908a18 to your computer and use it in GitHub Desktop.
[<AutoOpen>]
module Quantex.Common.Prelude
type Range<'T> = { From: 'T; To: 'T }
module Range =
let create (r: 'T * 'T) =
let (a,b) = r
if (a >= b) then Error("From cannot be greater than To") else Ok({ From = a; To = b})
type Range<'T> with
member x.ToTuple() = (x.From, x.To)
let inline map value (sourceRange: Range<'T>) (targetRange: Range<'T>) =
(value - sourceRange.From) / (sourceRange.To - sourceRange.From) * (targetRange.To - targetRange.From) + targetRange.From
/// Option extension
type Option<'T> with
member this.Unwrap() =
match this with
| Some value -> value
| None -> failwith "Fail to unwrap"
type MaybeBuilder() =
member this.Bind(x, f) = Option.bind f x
member this.Return(x) = Some x
let maybe = MaybeBuilder()
/// Use Fsharp.rop in the future
type Result<'Tr,'Te> with
member this.Unwrap() =
match this with
| Ok success -> success
| Error err -> failwithf "Fail to unwrap: %A" err
member this.toOpt() =
match this with
| Ok success -> Some success
| Error _ -> None
type ResultBuilder() =
member this.Bind(x, f) = Result.bind f x
member this.Return(x) = Some x
member this.Zero() = Ok()
let result = ResultBuilder()
/// Active patterns
open System
open System.Text.RegularExpressions
let ifTrueThen x = function
| true -> Some x
| false -> None
let (|NullOrEmpty|_|) =
String.IsNullOrEmpty
>> ifTrueThen NullOrEmpty
let (|NotMatchesRegex|_|) (pattern,regexOptions) input =
Regex.IsMatch (input, pattern, regexOptions)
|> not
|> ifTrueThen NotMatchesRegex
/// Unwrappers
[<RequireQualifiedAccess>]
module Result =
let unwrap = function | Ok succ -> succ | Error err -> failwithf "Fail to unwrap: %A" err
let isOk = function | Ok _ -> true | Error _ -> false
let toOpt (result: Result<_,_>) =
result.toOpt()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment