-
Notifications
You must be signed in to change notification settings - Fork 0
/
HDBReusable.fs
1844 lines (1643 loc) · 76.2 KB
/
HDBReusable.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[<AutoOpen>]
module HD.Schema.BReusable
open System
open System.Collections.Generic
open System.Diagnostics
let tryFSwallow f =
try
f() |> Some
with _ -> None
[<AutoOpen>]
module MatchHelpers =
// purpose: 'when clauses' require binding variable names, and if two cases should have the same result, but one has a condition on the bound variable, it can no longer point to the same exact path
let (|IsTrue|_|) f x = if f x then Some() else None
// things that assist with point-free style
[<AutoOpen>]
module FunctionalHelpersAuto =
let makePrintFunction c f =
let old = System.Console.ForegroundColor
try
System.Console.ForegroundColor <- c
f()
()
finally
System.Console.ForegroundColor <- old
let cprintn c (msg:string) =
makePrintFunction c (fun () -> System.Console.WriteLine msg)
let cprintf c fmt = // https://blogs.msdn.microsoft.com/chrsmith/2008/10/01/f-zen-colored-printf/
Printf.kprintf (fun s ->
let old = System.Console.ForegroundColor
try
System.Console.ForegroundColor <- c
System.Console.Write s
finally
System.Console.ForegroundColor <- old
) fmt
let cprintfn c fmt =
Printf.kprintf (fun s ->
let old = System.Console.ForegroundColor
try
System.Console.ForegroundColor <- c
System.Console.WriteLine s
finally
System.Console.ForegroundColor <- old
) fmt
let teeTuple f x = x, f x
/// take a dead-end function and curry the input
let tee f x = f x; x
// take a value and adjust it to fall within the range of vMin .. vMax
let clamp vMin vMax v =
max v vMin
|> min vMax
/// super handy with operators like (*) and (-)
/// take a function that expects 2 arguments and flips them before applying to the function
let inline flip f x y = f y x
/// take a tuple and apply the 2 arguments one at a time (from haskell https://www.haskell.org/hoogle/?hoogle=uncurry)
let uncurry f (x,y) = f x y
/// does not work with null x
let inline getType x = x.GetType()
// based on http://stackoverflow.com/a/2362114/57883
// mimic the C# as keyword
let castAs<'t> (o:obj): 't option =
match o with
| :? 't as x -> Some x
| _ -> None
// purpose eliminate having to write (fun x -> x :?> _)
// or (fun x -> downcast x)
let downcastX<'T> (o:obj): 'T =
match o with
| :? 'T as x -> x
| x -> failwithf "Invalid cast to %s of %A" (typeof<'T>.Name) x
// long pipe chains don't allow breakpoints anywhere inside
// does this need anything to prevent the method from being inlined/optimized away?
let breakpoint x =
let result = x
result
let breakpointf f x =
let result = f x
result
// allows you to pattern match against non-nullables to check for null (in case c# calls)
let (|NonNull|UnsafeNull|) x =
match box x with
| null -> UnsafeNull
| _ -> NonNull
// for statically typed parameters in an active pattern see: http://stackoverflow.com/questions/7292719/active-patterns-and-member-constraint
//consider pulling in useful functions from https://gist.github.com/ruxo/a9244a6dfe5e73337261
let cast<'T> (x:obj) = x :?> 'T
module Tuple2 = // idea and most code taken from https://gist.github.com/ploeh/6d8050e121a5175fabb1d08ef5266cd7
let replicate x = x,x
// useful for Seq.mapi
let fromCurry x y = (x,y)
let curry f x y = f (x, y)
let ofKeyValue = (|KeyValue|)
// calling already defined function from outer namespace, instead of duplicating the functionality for consistency with gist
let uncurry f (x, y) = uncurry f (x, y)
let swap (x, y) = (y, x)
let mapFst f (x, y) = f x, y
let mapSnd f (x, y) = x, f y
let extendFst f (x,y) = f (x,y), y
let extendSnd f (x,y) = x, f(x,y)
let optionOfFst f (x,y) =
match f x with
| Some x -> Some (x, y)
| None -> None
let optionOfSnd f (x,y) =
match f y with
| Some y -> Some (x,y)
| None -> None
// start Brandon additions
let mapBoth f (x,y) = f x, f y
let private failNullOrEmpty paramName x = if String.IsNullOrEmpty x then raise <| ArgumentOutOfRangeException paramName else x
type System.String with
// // no idea how to call this thing with a comparer
// static member indexOf (delimiter,?c:StringComparison) (x:string) =
// match failNullOrEmpty "delimiter" delimiter,c with
// | d, Some c -> x.IndexOf(d,comparisonType=c)
// | d, None -> x.IndexOf d
static member indexOf delimiter (x:string) =
failNullOrEmpty "delimiter" delimiter
|> x.IndexOf
static member indexOfC delimiter c (x:string) =
x.IndexOf(failNullOrEmpty "delimiter" delimiter ,comparisonType=c)
// couldn't get this guy to call the other guy, so... leaving him out too
// static member contains (delimiter, ?c:StringComparison) (x:string) =
// match failNullOrEmpty "delimiter" delimiter, c with
// | d, Some c -> x.IndexOf(d, comparisonType=c) |> flip (>=) 0
// | d, None -> x.Contains d
static member contains delimiter (x:string) =
failNullOrEmpty "delimiter" delimiter
|> x.Contains
static member containsC delimiter c (x:string) =
x
|> String.indexOfC (failNullOrEmpty "delimiter" delimiter) c
|> flip (>=) 0
static member substring i (x:string) = x.Substring i
static member substring2 i e (x:string)= x.Substring(i,e)
// the default insensitive comparison
static member defaultIComparison = StringComparison.InvariantCultureIgnoreCase
static member Null:string = null
static member trim (s:string) = match s with | null -> null | s -> s.Trim()
static member split (delims:string seq) (x:string) = x.Split(delims |> Array.ofSeq, StringSplitOptions.None)
static member splitO (items:string seq) options (x:string) = x.Split(items |> Array.ofSeq, options)
static member emptyToNull (x:string) = if String.IsNullOrEmpty x then null else x
static member equalsI (x:string) (x2:string) = not <| isNull x && not <| isNull x2 && x.Equals(x2, String.defaultIComparison)
static member startsWithI (toMatch:string) (x:string) = not <| isNull x && not <| isNull toMatch && toMatch.Length > 0 && x.StartsWith(toMatch, String.defaultIComparison)
static member isNumeric (x:string) = not <| isNull x && x.Length > 0 && x |> String.forall Char.IsNumber
static member splitLines(x:string) = x.Split([| "\r\n";"\n"|], StringSplitOptions.None)
static member before (delimiter:string) s = s |> String.substring2 0 (s.IndexOf delimiter)
static member beforeOrSelf (delimiter:string) x = if x|> String.contains delimiter then x |> String.before delimiter else x
static member beforeAnyOf (delimiters:string list) (x:string) =
let index, _ =
delimiters
|> Seq.map (fun delimiter -> x.IndexOf(delimiter),delimiter)
|> Seq.filter(fun (index,_) -> index >= 0)
|> Seq.minBy (fun (index, _) -> index)
x.Substring(0,index)
static member replace (target:string) (replacement) (str:string) = if String.IsNullOrEmpty target then invalidOp "bad target" else str.Replace(target,replacement)
type Dictionary<'Key,'Value> with
member x.tryFind k =
if x.ContainsKey k then
Some x.[k]
else None
member x.addOrUpdate k v =
x.[k] <- v
// comment/concern/critique auto-opening string functions may pollute (as there are so many string functions)
// not having to type `String.` on at least the used constantly is a huge reduction in typing
// also helps with point-free style
module StringHelpers =
// I've been fighting/struggling with where to namespace/how to architect string functions, they are so commonly used, static members make it easier to find them
// since typing `String.` with this module open makes them all easy to find
// favor non attached methods for commonly used methods
// let before (delimiter:string) (x:string) = x.Substring(0, x.IndexOf delimiter)
let contains (delimiter:string) (x:string) = String.contains delimiter x
let containsI (delimiter:string) (x:string) = x |> String.containsC delimiter String.defaultIComparison
let substring i x = x |> String.substring i
let substring2 i length (x:string) = x |> String.substring2 i length //x.Substring(i, length)
let before (delimiter:string) s = s |> String.substring2 0 (s.IndexOf delimiter)
let beforeOrSelf delimiter x = if x|> String.contains delimiter then x |> before delimiter else x
let after (delimiter:string) (x:string) =
failNullOrEmpty "x" x
|> tee (fun _ -> failNullOrEmpty "delimiter" delimiter |> ignore)
|> fun x ->
match x.IndexOf delimiter with
| i when i < 0 -> failwithf "after called without matching substring in '%s'(%s)" x delimiter
| i -> x |> String.substring (i + delimiter.Length)
let afterI (delimiter:string) (x:string) =
x
|> String.indexOfC delimiter String.defaultIComparison
|> (+) delimiter.Length
|> flip String.substring x
let afterOrSelf delimiter x = if x|> String.contains delimiter then x |> after delimiter else x
let afterOrSelfI (delimiter:string) (x:string) = if x |> String.containsC delimiter String.defaultIComparison then x |> afterI delimiter else x
let containsAnyOf (delimiters:string seq) (x:string) = delimiters |> Seq.exists(flip contains x)
let containsIAnyOf (delimiters:string seq) (x:string) = delimiters |> Seq.exists(flip containsI x)
let delimit (delimiter:string) (items:#seq<string>) = String.Join(delimiter,items)
let endsWith (delimiter:string) (x:string) = x.EndsWith delimiter
let isNumeric (s:string)= not <| isNull s && s.Length > 0 && s |> String.forall Char.IsNumber
let replace (target:string) (replacement) (str:string) = if String.IsNullOrEmpty target then invalidOp "bad target" else str.Replace(target,replacement)
let splitLines(x:string) = x.Split([| "\r\n";"\n"|], StringSplitOptions.None)
let startsWith (delimiter:string) (s:string) = s.StartsWith delimiter
let startsWithI (delimiter:string) (s:string) = s.StartsWith(delimiter,String.defaultIComparison)
let trim = String.trim
let afterLast delimiter x =
if x |> String.contains delimiter then failwithf "After last called with no match"
x |> String.substring (x.LastIndexOf delimiter + delimiter.Length)
let stringEqualsI s1 (toMatch:string)= not <| isNull toMatch && toMatch.Equals(s1, StringComparison.InvariantCultureIgnoreCase)
let inline isNullOrEmptyToOpt s =
if String.IsNullOrEmpty s then None else Some s
// was toFormatString
// with help from http://www.readcopyupdate.com/blog/2014/09/26/type-constraints-by-example-part1.html
let inline toFormatString (f:string) (a:^a) = ( ^a : (member ToString:string -> string) (a,f))
let alterCasing fPrefix fChange (s:string) =
let prefix = s |> Seq.takeWhile fPrefix
s
|> Seq.skipWhile fPrefix
|> Seq.mapi fChange
|> Seq.append prefix
|> String.Concat
//if more is needed consider humanizer or inflector
// doesn't account for leading _
let toPascalCase s =
alterCasing (Char.IsLetter >> not) (fun i l -> if i=0 && Char.IsLower l then Char.ToUpper l else l) s
let toCamelCase s =
alterCasing (Char.IsLetter >> not) (fun i l -> if i=0 && Char.IsUpper l then Char.ToLower l else l) s
let humanize camel :string =
seq {
let pascalCased = toPascalCase camel
yield pascalCased.[0]
for l in pascalCased |> Seq.skip 1 do
if System.Char.IsUpper l then
yield ' '
yield l
else
yield l
}
|> String.Concat
open StringHelpers
// I've also been struggling with the idea that Active patterns are frequently useful as just methods, so sometimes methods are duplicated as patterns
[<AutoOpen>]
module StringPatterns =
open StringHelpers
open System.Text.RegularExpressions
let (|NullString|Empty|WhiteSpace|ValueString|) (s:string) =
match s with
| null -> NullString
| "" -> Empty
| _ when String.IsNullOrWhiteSpace s -> WhiteSpace
| _ -> ValueString s
let (|StartsWith|_|) (str:string) arg = if str.StartsWith(arg) then Some() else None
let (|StartsWithI|_|) s1 (toMatch:string) = if not <| isNull toMatch && toMatch.StartsWith(s1, StringComparison.InvariantCultureIgnoreCase) then Some () else None
let (|StringEqualsI|_|) s1 (toMatch:string) = if String.equalsI toMatch s1 then Some() else None
let (|InvariantEqualI|_|) (str:string) arg =
if String.Compare(str, arg, StringComparison.InvariantCultureIgnoreCase) = 0
then Some() else None
let (|IsNumeric|_|) (s:string) = if not <| isNull s && s.Length > 0 && s |> String.forall Char.IsNumber then Some() else None
let (|Contains|_|) s1 (toMatch:string) = if toMatch |> contains s1 then Some () else None
let (|ContainsI|_|) s1 (toMatch:string) = if toMatch |> containsI s1 then Some () else None
let (|OrdinalEqualI|_|) (str:string) arg =
if String.Compare(str, arg, StringComparison.OrdinalIgnoreCase) = 0
then Some() else None
let inline (|IsTOrTryParse|_|) (t,parser) (x:obj): 't option =
match x with
| v when v.GetType() = t -> Some (v :?> 't)
| :? string as p ->
match parser p with
| true, v -> Some v
| _, _ -> None
| _ -> None
// sample usage:
//let convert<'t> (op: 't -> 't -> bool) (tryParser:string -> bool*'t) (value:obj) _targetType param _culture : obj =
// let args = typeof<'t>,tryParser
// let result:obj=
// match param with
// | IsTOrTryParse args p ->
// match value with
// | :? 't as v when (box value |> isNull |> not) ->
// let result = op v p
// upcast result
// | _ -> DependencyProperty.UnsetValue
// | _ -> failwithf "parameter was not of the expected type %s" (typeof<'t>.Name)
// result
let (|ParseInt|_|) (x:obj) =
match x with
| :? string as p ->
let success,value = System.Int32.TryParse(p)
if success then
Some value
else None
| _ -> None
let (|ParseFloat|_|) (x:obj) =
match x with
| :? string as p ->
let success,value = System.Double.TryParse(p)
if success then
Some value
else None
| _ -> None
let (|ParseDateTime|_|) (s:string) =
match DateTime.TryParse s with
| true, dt -> Some dt
| _ -> None
let (|ParseBoolean|_|) (s:string) =
match Boolean.TryParse s with
| true, b -> Some b
| _ -> None
let (|ParseDecimal|_|) (s:string) =
match Decimal.TryParse s with
| true, x -> Some x
| _ -> None
let (|RMatch|_|) (pattern:string) (s:string) =
let r = Regex.Match(s,pattern)
if r.Success then
Some r
else None
type System.String with
static member IsValueString =
function
| ValueString _ -> true
| _ -> false
type System.Action with
static member invoke (x:System.Action) () = x.Invoke()
static member invoke1 (x:System.Action<_>) y = x.Invoke(y)
static member invoke2 (x:System.Action<_,_>) y z = x.Invoke(y,z)
static member invoke3 (x:System.Action<_,_,_>) a b c = x.Invoke(a,b,c)
type System.Func<'tResult> with
static member invoke (x:System.Func<'tResult>) () = x.Invoke()
static member invoke1<'t> (x:System.Func<'t,'tResult>) y = x.Invoke y
static member invoke2<'t1,'t2> (x:System.Func<'t1,'t2,'tResult>) y z = x.Invoke(y, z)
static member invoke3 (x:System.Func<'t1,'t2,'t3,'tResult>) a b c = x.Invoke(a,b,c)
static member invoke4 (x:System.Func<'t1, 't2, 't3, 't4, 'tResult>) a b c d = x.Invoke(a,b,c,d)
type FailureInfo =
|Ex of exn
|Text of string
|TxtEx of string*exn
with
member x.GetExn() =
match x with
| Ex ex -> Some ex
| TxtEx (_,ex) -> Some ex
| _ -> None
member x.GetText() =
match x with
| TxtEx(t,_) -> Some t
| Text t -> Some t
| _ -> None
static member Add fTxt x =
match x with
| TxtEx(t,ex) -> TxtEx(fTxt t, ex)
| Text t -> fTxt t |> Text
| Ex ex -> TxtEx(fTxt null, ex)
member x.AddText fTxt = FailureInfo.Add fTxt x
member x.AddText funcTxt = FailureInfo.Add (Func<_>.invoke1 funcTxt) x
type ChoiceRailway<'t> = Choice<'t,FailureInfo>
module Choice = // https://github.com/fsprojects/FSharpx.Extras/blob/master/src/FSharpx.Extras/ComputationExpressions/Monad.fs
let inline lift x = Choice1Of2 x
let inline protect f x =
try
f x
|> Choice1Of2
with e -> Choice2Of2 e
let inline map f =
function
| Choice1Of2 x -> f x |> Choice1Of2
| Choice2Of2 x -> Choice2Of2 x
let inline bind f =
function
| Choice1Of2 x -> f x
| Choice2Of2 x -> Choice2Of2 x
let inline mapSnd f =
function
| Choice1Of2 x -> Choice1Of2 x
| Choice2Of2 x -> f x
let inline bindIsNullOrWhitespace msg =
function
| ValueString v -> Choice1Of2 v
| _ -> Choice2Of2 (FailureInfo.Text msg)
let inline iter f =
function
| Choice1Of2 x -> f x
| _ -> ()
#if LINQPAD
let dumpt (title:string) x = x.Dump(title); x
#else
let dumpt (title:string) x = printfn "%s:%A" title x; x
#endif
let indent spacing (text:string) =
if String.IsNullOrEmpty(text) then
String.Empty
else if trim text |> String.contains "\r\n" then
"\r\n" + text |> splitLines |> Seq.map (fun s -> spacing + s) |> delimit "\r\n"
else text
//module Xml =
// open System.Xml.Linq
// let nsNone = XNamespace.None
// let toXName (ns:XNamespace) name =
// ns + name
// let getElement1 n (e:XElement) =
// e.Element n
// |> Option.ofObj
// // leaving out a 'getElement' as it will likely be (samples in code comments below):
// // let getElement = toXName nsNone >> getElement1
// // let getElement = toXName doc.Root.Name.Namespace >> getElement1
// let getElements1 n (e:XElement) = e.Elements n
// // point-free Seq.filter argument
// let isNamed n (e:XElement) = e.Name = n
// let getElementsAfter n (e:XElement) =
// e
// |> getElements1 n
// |> Seq.skipWhile (isNamed n >> not)
// |> Seq.skip 1
// let getAttributeVal name (e:XElement) =
// nsNone + name
// |> e.Attribute
// |> Option.ofObj
// |> Option.map (fun a -> a.Value)
// let setAttribVal name value (e:XElement) =
// e.SetAttributeValue(nsNone + name, value)
// let getDescendants n (e:XElement) = e.Descendants n
// let attribValueIs name value e =
// e
// |> getAttributeVal name
// |> Option.toObj
// |> (=) value
// let isElement (e:XNode) =
// match e with
// | :? XElement -> true
// | _ -> false
// // when you |> string an XElement, normally it writes appends the namespace as an attribute, but this is normally covered by the root element
// let stripNamespaces (e:XElement):XElement=
// // if the node is not XElement, pass through
// let rec stripNamespaces (n:XNode): XNode =
// match n with
// | :? XElement as x ->
// let contents =
// x.Attributes()
// // strips default namespace, but not other declared namespaces
// |> Seq.filter(fun xa -> xa.Name.LocalName <> "xmlns")
// |> Seq.cast<obj>
// |> List.ofSeq
// |> (@) (
// x.Nodes()
// |> Seq.map stripNamespaces
// |> Seq.cast<obj>
// |> List.ofSeq
// )
// XElement(nsNone + x.Name.LocalName, contents |> Array.ofList) :> XNode
// | x -> x
// stripNamespaces e :?> XElement
// ()
//https://blogs.msdn.microsoft.com/dsyme/2009/11/08/equality-and-comparison-constraints-in-f/
type System.Int32 with
static member tryParse x =
System.Int32.TryParse x
|> function
| true, x -> Some x
| _ -> None
module Choices =
let private allOrNone fChoose items =
match items with
| [] -> None
| items ->
List.foldBack(fun item state ->
match state with
| None -> None
| Some items ->
match fChoose item with
| Some item ->
item::items
|> Some
| None -> None
) items (Some [])
let (|Homogenous1Of2|_|) items = allOrNone (function | Choice1Of2 x -> Some x | _ -> None) items
let (|Homogenous2Of2|_|) items = allOrNone (function | Choice2Of2 x -> Some x | _ -> None) items
let (|Just1sOf2|) items =
items
|> List.choose(function | Choice1Of2 x -> Some x | _ -> None)
|> Some
let (|Just2sOf2|) items =
items
|> List.choose(function | Choice2Of2 x -> Some x | _ -> None)
module IComparable =
let equalsOn f x (yobj:obj) =
match yobj with
| :? 'T as y -> (f x = f y)
| _ -> false
let hashOn f x = hash (f x)
let compareOn f x (yobj: obj) =
match yobj with
| :? 'T as y -> compare (f x) (f y)
| _ -> invalidArg "yobj" "cannot compare values of different types"
module Paging =
type Page<'T> = {Index:int; PageSize:int; Total:int; PageItems:'T list}
with
member x.Page = x.Index + 1
member x.Pages = float x.Total / float x.PageSize |> ceil |> round
#nowarn "0042"
// http://fssnip.net/7SK
// allows using units of measure on other types
module IGUoM =
open System
type UoM = class end
with
static member inline Tag< ^W, ^t, ^tm when (^W or ^t) : (static member IsUoM : ^t * ^tm -> unit)> (t : ^t) = (# "" t : ^tm #)
static member inline UnTag< ^W, ^t, ^tm when (^W or ^t) : (static member IsUoM : ^t * ^tm -> unit)> (t : ^tm) = (# "" t : ^t #)
let inline tag (x : 't) : 'tm = UoM.Tag<UoM, 't, 'tm> x
let inline untag (x : 'tm) : 't = UoM.UnTag<UoM, 't, 'tm> x
[<MeasureAnnotatedAbbreviation>]
type string<[<Measure>] 'Measure> = string
type UoM with
// Be *very* careful when writing this; bad args will result in invalid IL
static member IsUoM(_ : string, _ : string<'Measure>) = ()
[<Measure>] type FullName = class end
[<Measure>] type FirstName= class end
/// this doesn't account for cases where the identity is longer than signed int holds
type ValidIdentity<[<Measure>] 'T> private(i:int<'T>) =
static let fIsValid i = i > 0<_>
let i = if fIsValid i then i else failwithf "Invalid value"
member __.Value = i
/// valid values are 1..x
static member TryCreateOpt i =
if fIsValid i then
ValidIdentity<'T>(i) |> Some
else None
static member get (vi:ValidIdentity<_>) : int<'T> = vi.Value
static member OptionOfInt x = if fIsValid x then Some x else None
member private __.ToDump() = i |> string // linqpad friendly
override x.ToString() =
x.ToDump()
override x.Equals y = IComparable.equalsOn ValidIdentity.get x y
override x.GetHashCode() = IComparable.hashOn ValidIdentity.get x
interface System.IComparable with
member x.CompareTo y = IComparable.compareOn ValidIdentity.get x y
module IntPatterns =
let (|PositiveInt|Zero|NegativeInt|) (x:int<_>) =
if x > 0<_> then PositiveInt
elif x = 0<_> then Zero
else NegativeInt
module Caching =
let (|IsUnderXMinutes|_|) maxAgeMinutes (dt:DateTime) =
let minutes =
DateTime.Now - dt
|> fun x -> x.TotalMinutes
if minutes < maxAgeMinutes then
Some()
else None
type Result =
| Success
| Failed
[<NoEquality>]
[<NoComparison>]
type CacheAccess<'TKey,'TValue when 'TKey: comparison> = {Getter: 'TKey -> 'TValue option; Setter : 'TKey -> 'TValue -> unit; GetSetter: 'TKey -> (unit -> 'TValue) -> 'TValue} with
// C# helper(s)
member x.GetSetterFuncy (k,f:Func<_>)=
x.GetSetter k f.Invoke
let iDictTryFind<'T,'TValue> (k:'T) (d:IDictionary<'T,'TValue>) =
if d.ContainsKey k then
Some d.[k]
else None
let createTimedCache<'TKey,'TValue when 'TKey:comparison> (fIsYoungEnough) =
let cache = System.Collections.Concurrent.ConcurrentDictionary<'TKey,DateTime*'TValue>()
//let cache: Map<'TKey,DateTime*'TValue> = Map.empty
let getter k =
let result = cache |> iDictTryFind k |> Option.filter( fst >> fIsYoungEnough) |> Option.map snd
match result with
| Some v ->
printfn "Cache hit for %A" k
Some v
| None ->
printfn "Cache miss for %A" k
None
let setter k v =
cache.[k] <- (DateTime.Now,v)
let getSetter k f =
match getter k with
| Some v -> v
| _ ->
let v = f()
setter k v
v
{Getter=getter;Setter =setter; GetSetter=getSetter}
module Debug =
open System.Collections.ObjectModel
type FListener(fWrite: _ -> unit,fWriteLn:_ -> unit, name) =
inherit TraceListener(name)
override __.Write (msg:string) = fWrite msg
override __.WriteLine (msg:string) = fWriteLn msg
new(fWrite,fWriteLn) = new FListener(fWrite,fWriteLn, null)
type FLineListener(source:string ObservableCollection, fLineMap) =
inherit TraceListener()
let mutable lastWasWriteNotWriteLine = false
let fLineMap = defaultArg fLineMap id
let addText msg isLineFinished =
if lastWasWriteNotWriteLine then
let lastLine = source.[source.Count - 1]
assert (source.Remove lastLine)
lastLine + msg
else msg
|> fun x -> if isLineFinished then fLineMap x else x
|> source.Add
new(source, lineMap:Func<_, _>) = new FLineListener(source,fLineMap = if isNull lineMap then None else Some lineMap.Invoke)
override __.Write (msg:string) =
addText msg false
lastWasWriteNotWriteLine <- true
override __.WriteLine (msg:string) =
addText msg true
lastWasWriteNotWriteLine <- false
type DebugTraceListener(?breakOnAll) =
inherit TraceListener()
let mutable breakOnAll:bool = defaultArg breakOnAll false
override __.Write (_msg:string) = ()
override __.WriteLine (msg:string) =
let toIgnorePatterns = [
@"BindingExpression path error: 'Title' property not found on 'object' ''String' \(HashCode=-[0-9]+\)'. BindingExpression:Path=Title; DataItem='String' \(HashCode=-[0-9]+\); target element is 'ContentPresenter' \(Name='Content'\); target property is 'ResourceKey' \(type 'String'\)"
]
let regMatch p =
let m = Text.RegularExpressions.Regex.Match(msg,p)
if m.Success then
Some p
else
None
let matchedIgnorePattern = toIgnorePatterns |> Seq.choose regMatch |> Seq.tryHead
match matchedIgnorePattern with
| Some _ -> ()
| None ->
if breakOnAll && Debugger.IsAttached then
Debugger.Break()
else ()
type Listener(created:DateTime, name) =
inherit TraceListener(name)
new(created) = new Listener(created, null)
override __.Write (msg:string) = printf "%s" msg
override __.WriteLine (msg:string) =
printfn "%s" msg
member __.Created= created
let inline assertIfDebugger b =
if not b then
printfn "Assertion failed"
if Diagnostics.Debugger.IsAttached then
Debugger.Break()
// this option may be different from Debug.Assert somehow
// https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/assertions
// else
// assert b
//module Array =
// let ofOne x = [| x |]
module Seq =
/// Seq.take throws if there are no items
[<Obsolete("Seq.truncate is built in")>]
let takeLimit limit =
let mutable count = 0
Seq.takeWhile(fun _ ->
let result = count < limit
count <- count + 1
result)
let inline any items = items |> Seq.exists(fun _ -> true)
let copyFrom (source: _ seq) (toPopulate:IList<_>) =
if not <| isNull source && not <| isNull toPopulate then
use enumerator = source.GetEnumerator()
while enumerator.MoveNext() do
toPopulate.Add(enumerator.Current)
let ofType<'t> items =
items |> Seq.cast<obj> |> Seq.choose (fun x -> match x with | :? 't as x -> Some x | _ -> None )
// not happy about exception style, but otherwise what... options could lead to believe this is SingleOrNone
// options can't express there were no items, vs. there was more than one errors.
let single<'T> x =
x
|> Seq.truncate 2
|> List.ofSeq
|> function
| [ (x:'T) ]-> x
| [] -> raise <| InvalidOperationException "Single called with no elements"
| _ -> raise <| InvalidOperationException "Single called with more than one element"
/// Iterates over elements of the input sequence and groups adjacent elements.
/// A new group is started when the specified predicate holds about the element
/// of the sequence (and at the beginning of the iteration).
///
/// For example:
/// Seq.windowedFor isOdd [3;3;2;4;1;2] = seq [[3]; [3; 2; 4]; [1; 2]]
let windowedFor f (input:seq<_>) = seq {
use en = input.GetEnumerator()
let running = ref true
// Generate a group starting with the current element. Stops generating
// when it founds element such that 'f en.Current' is 'true'
let rec group() =
[ yield en.Current
if en.MoveNext() then
if not (f en.Current) then yield! group()
else running := false ]
if en.MoveNext() then
// While there are still elements, start a new group
while running.Value do
yield group() |> Seq.ofList }
/// assumes you will iterate the entire sequence, otherwise not disposed
/// probably not ok for infinite sequences
let ofIEnumerator (en:System.Collections.IEnumerator) =
let unfolder () =
if en.MoveNext() then
Some(en.Current, ())
else
// sequence iterated, if it is disposable dispose it
match en with
| :? IDisposable as d -> d.Dispose()
| _ -> ()
None
Seq.unfold unfolder ()
module List =
// is this worth having/keeping?
// let except toScrape items =
// let toScrape = Set.ofList toScrape
// let items = Set.ofList items
// items - toScrape
let cartesian xs ys =
xs |> List.collect (fun x -> ys |> List.map (fun y -> x, y))
// return a Tuple where (A, B) (both present if they have a match)
let forceJoin b a =
let b = Set.ofList b
let a = Set.ofList a
let x = Set.intersect a b
let diffa = a - b
let diffb = b - a
diffa - x
|> Seq.map (fun a' -> Some a', None)
|> Seq.append (x |> Seq.map (fun x' -> (Some x', Some x')))
|> Seq.append (diffb - x |> Seq.map (fun b' -> None, Some b'))
|> List.ofSeq
module Observables =
open System.Collections.ObjectModel
open System.Collections.Specialized
let bindObsTToObsObjDispatched (obsCollection:ObservableCollection<'t>) fDispatch =
let obsObj = ObservableCollection<obj>()
obsCollection.CollectionChanged.Add (fun e ->
match e.Action with
|NotifyCollectionChangedAction.Add ->
fDispatch (fun () ->
e.NewItems
|> Seq.cast<obj>
|> Seq.iter obsObj.Add
)
|NotifyCollectionChangedAction.Move ->
fDispatch (fun () ->
let oldIndex = e.OldStartingIndex
let newIndex = e.NewStartingIndex
obsObj.Move(oldIndex,newIndex)
)
|NotifyCollectionChangedAction.Remove ->
fDispatch (fun () ->
e.OldItems
|> Seq.cast<obj>
|> Seq.iter (obsObj.Remove>> ignore<bool>)
)
|NotifyCollectionChangedAction.Replace ->
fDispatch (fun () ->
e.NewItems
|> Seq.cast<obj>
|> Seq.zip (e.OldItems |> Seq.cast<obj>)
|> Seq.iteri(fun i (oldItem,newItem) ->
assert (obsObj.[e.OldStartingIndex + i] = oldItem)
obsObj.[e.OldStartingIndex + i] <- newItem
)
)
| NotifyCollectionChangedAction.Reset ->
fDispatch (fun () ->
obsObj.Clear()
if not <| isNull e.NewItems then
e.NewItems
|> Seq.cast<obj>
|> Seq.iter obsObj.Add
)
| x -> failwithf "Case %A is unimplemented" x
)
obsObj
let bindObsTToObsObj (obsCollection:ObservableCollection<'t>) =
bindObsTToObsObjDispatched obsCollection (fun f -> f())
// |Null|Value| already in use by Nullable active pattern
type System.Convert with
static member ToGuid(o:obj) = o :?> Guid
static member ToBinaryData(o:obj) = o :?> byte[] // http://stackoverflow.com/a/5371281/57883
// based on http://stackoverflow.com/questions/15115050/f-type-constraints-on-enums
type System.Enum with // I think enum<int> is the only allowed enum-ish constraint allowed in all of .net
static member parse<'t when 't : enum<int>> x = Enum.Parse(typeof<'t>,x)
static member parseT t x = Enum.Parse(t, x)
static member fromString<'t when 't:enum<int>> x = Enum.parse<'t> x :?> 't
static member getName<'t when 't : enum<int>> x = Enum.GetName(typeof<'t>,x)
static member getAll<'t when 't : enum<int>>() =
Enum.GetValues typeof<'t>
|> Seq.cast<int>
|> Seq.map (fun x -> Enum.getName<'t> x)
|> Seq.map (fun x -> Enum.parse<'t> x :?> 't)
static member fromInt<'t when 't :enum<int>>(i:int) =
Enum.getName<'t> i
|> fun x -> Enum.parse<'t> x :?> 't
type System.DateTime with
static member addDays dy (dt:DateTime) = dt.AddDays dy
static member addHours h (dt:DateTime) = dt.AddHours h
static member addMinutes min (dt:DateTime) = dt.AddMinutes min
static member toShortDateString (dt:DateTime) = dt.ToShortDateString()
static member getStartOfMonth (dt:DateTime) = DateTime(dt.Year, dt.Month,1)
static member getYear (dt:DateTime) = dt.Year
static member getHour (dt:DateTime) = dt.Hour
static member getMinute (dt:DateTime) = dt.Minute
static member roundTo useRoundUp (ts:TimeSpan) (dt:DateTime) =
if useRoundUp then
ts.Ticks - 1L
else
ts.Ticks / 2L
|> flip (+) dt.Ticks
|> flip (/) ts.Ticks
|> (*) ts.Ticks
|> DateTime
// taken from SO http://stackoverflow.com/a/1595311/57883
static member getAge (now:DateTime) (dt:DateTime) =
let age = now.Year - dt.Year
if (now.Month < dt.Month || (now.Month = dt.Month && now.Day < dt.Day)) then
age - 1
else
age
static member toString (format:string) (dt:DateTime) = dt.ToString(format)
//public static string CalculateAge(DateTime birthDate, DateTime now)
static member getAgeDisplay (now:DateTime) (dob:DateTime) =
let years = DateTime.getAge now dob
let _days,now =
let days = now.Day - dob.Day
if days < 0 then
let newNow = now.AddMonths(-1)
let totalDays = now - newNow
let totalDays = int totalDays.TotalDays
days + totalDays,newNow
else days,now
let months = ((now.Year - dob.Year) * 12) + now.Month - dob.Month
if (years <= 2) then
months.ToString() + "m"
else
years.ToString() + "y"
member x.GetAge (now:DateTime) = DateTime.getAge now x
module Time =
[<CustomComparison>]
[<CustomEquality>]
// shadowed constructor/private implementation
type ValidatedTime = private {_Hour:int; _Minute:int;} with
static member op_LessThan (x:ValidatedTime,y:ValidatedTime) = x.Hour < y.Hour || (x.Hour = y.Hour && x.Minute < y.Minute)
static member op_GreaterThan (x:ValidatedTime, y:ValidatedTime) = x.Hour > y.Hour || (x.Hour = y.Hour && x.Minute > y.Minute)
static member op_GreaterThanOrEqual (x:ValidatedTime, y:ValidatedTime) = x.Hour > y.Hour || (x.Hour = y.Hour && x.Minute >= y.Minute)
static member op_LessThanOrEqual (x:ValidatedTime,y:ValidatedTime) = x.Hour < y.Hour || (x.Hour = y.Hour && x.Minute <= y.Minute)
static member CanCreate hour minute = hour < 24 && hour >= 0 && minute >=0 && minute < 60
static member Create hour minute = if ValidatedTime.CanCreate hour minute then {_Hour=hour; _Minute = minute} |> Some else None
// exposing any members is a questionable decision for a Pure ADT, but... maybe this is ok for the way I'm using it
member x.Hour = x._Hour
member x.Minute = x._Minute
override x.ToString() =
DateTime.Today
|> DateTime.addHours (float x.Hour)
|> DateTime.addMinutes (float x.Minute)
|> DateTime.toString "hh:mmtt"
override x.GetHashCode() = (x.Hour,x.Minute).GetHashCode()
override x.Equals obj =
match obj with
| :? ValidatedTime as y ->
x.Hour = y.Hour && x.Minute = y.Minute
| _ -> false
interface IComparable with
member x.CompareTo (obj:obj)=
match obj with
| :? ValidatedTime as y ->
if ValidatedTime.op_LessThan (x, y) then
-1
elif ValidatedTime.op_GreaterThan (x, y) then
1
else
0
| _ -> raise <| InvalidOperationException("Type must be ValidatedTime")
[<RequireQualifiedAccess; CompilationRepresentation (CompilationRepresentationFlags.ModuleSuffix)>]
module ValidatedTime = //| ValidatedTime of hour:int * minute:int
let create hour minute = if ValidatedTime.CanCreate hour minute then {_Hour = hour; _Minute=minute} |> Some else None
let ofDateTime (dt:DateTime) = ValidatedTime.Create dt.Hour dt.Minute
let ofTimeSpan (ts:TimeSpan) = ValidatedTime.Create ts.Hours ts.Minutes
let getHour (vt: ValidatedTime) = vt.Hour
let getMinute (vt:ValidatedTime) = vt.Minute
// // shadow constructor
// let ValidatedTime hour minute = ValidatedTime.Create hour minute
// where only the hour component and below are relevant
// a timespan of
type IntraDayTimeSpan = |IntraDayTimeSpan of start:ValidatedTime*stop:ValidatedTime with
member x.Start = x |> function |IntraDayTimeSpan(start,_) -> start
member x.Stop = x |> function |IntraDayTimeSpan(_,stop) -> stop
member x.Contains (t:ValidatedTime) =
x.Start < t && t < x.Stop
member x.Overlaps (y:IntraDayTimeSpan) =
x.Contains y.Start || x.Contains y.Stop || y.Contains x.Start || y.Contains x.Stop
let IntraDayTimeSpan start stop =
if start < stop then
IntraDayTimeSpan(start,stop) |> Some
else None