-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBReusable.fs
More file actions
2048 lines (1822 loc) · 84.3 KB
/
BReusable.fs
File metadata and controls
2048 lines (1822 loc) · 84.3 KB
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 BReusable
open System
open System.Collections.Generic
open System.Diagnostics
type System.Object with
member x.ThrowIfNull msg =
if isNull x then
nullArg msg
let inline guardAgainstNull msg (o:obj) =
if isNull o then
nullArg msg
let (|GuardNull|) msg (x:'T) =
x.ThrowIfNull msg
x
[<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 x else None
let (|IsAnyOf|_|) items x = if items |> Seq.exists((=) x) then Some x else None
// things that assist with point-free style
[<AutoOpen>]
module FunctionalHelpersAuto =
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()
// 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
// 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
// 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
let inline swallow f =
try
f()
with _ ->
()
let inline makeUnsafeDisposal f =
{ new IDisposable with
member __.Dispose() =
printfn "Disposing UnsafeDisposal"
f()
}
// this swallows. Disposal methods are never supposed to/allowed to throw.
let inline disposable (f:unit -> unit) =
let inline swallow () =
swallow f
// this is made safe by swallowing
makeUnsafeDisposal swallow
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)
// 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 containsI delimiter (x:string) =
String.containsC delimiter String.defaultIComparison x
static member Null:string = null
static member trim (s:string) = match s with | null -> null | s -> s.Trim()
static member trim1 (d:char) (s:string) = match s with | null -> null | s -> s.Trim(d)
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 startsWith (toMatch:string) (x:string) = not <| isNull x && not <| isNull toMatch && toMatch.Length > 0 && x.StartsWith toMatch
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)
// 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 trim1 (delim:string) (x:string) = x.Trim(delim |> Array.ofSeq)
// let after (delimiter:string) (x:string) =
// match x.IndexOf delimiter with
// | i when i < 0 -> failwithf "after called without matching substring in '%s'(%s)" x delimiter
// | i -> x.Substring(i + delimiter.Length)
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 inline getLength s = (^a: (member Length: _) s)
//if more is needed consider humanizer or inflector
let toPascalCase s =
s
|> Seq.mapi (fun i l -> if i=0 && Char.IsLower l then Char.ToUpper l else l)
|> String.Concat
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
/// assumes all that is needed is the first char changed, does not account for underscoring
let toCamelCase s = // https://github.com/ayoung/Newtonsoft.Json/blob/master/Newtonsoft.Json/Utilities/StringUtils.cs
if String.IsNullOrEmpty s then
s
elif not <| Char.IsUpper s.[0] then
s
else
let camelCase = Char.ToLower(s.[0], System.Globalization.CultureInfo.InvariantCulture).ToString(System.Globalization.CultureInfo.InvariantCulture)
if (s.Length > 1) then
camelCase + (s.Substring 1)
else
camelCase
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
let (|ToString|) (x:obj) =
match x with
| null -> null
| x -> x.ToString()
let isValueString = String.IsNullOrWhiteSpace >> not
let (|ValueString|NonValueString|) =
function
| x when isValueString x -> ValueString x
| x -> NonValueString x
let (|MultiLine|_|) x =
match splitLines x with
| [| |] -> None
| lines -> Some lines
let (|NullOrEmpty|_|) x =
if String.IsNullOrEmpty x then
Some()
else None
let (|WhiteSpace|_|) =
function
| null
| "" -> None
| x when String.IsNullOrWhiteSpace x -> Some x
| _ -> None
module Option =
let ofValueString = function |ValueString x -> Some x | _ -> None
//let (|NullString|Empty|WhiteSpace|ValueString|) (s:string) =
// match s with
// | null -> NullString
// | "" -> Empty
// | _ when String.IsNullOrWhiteSpace s -> WhiteSpace
// | _ -> ValueString s
let (|StartsWith|_|) d = Option.ofObj >> Option.filter (String.startsWith d) >> Option.map ignore
let (|StartsWithI|_|) d = Option.ofObj >> Option.filter (String.startsWithI d) >> Option.map ignore
let (|After|_|) d =
failNullOrEmpty "d" d |> ignore<string>
Option.ofObj >> Option.filter (String.contains d) >> Option.map (StringHelpers.after d)
let (|AfterI|_|) d =
failNullOrEmpty "d" d |> ignore<string>
Option.ofObj >> Option.filter (String.containsI d) >> Option.map (StringHelpers.afterI d)
let (|Before|_|) d =
failNullOrEmpty "d" d |> ignore<string>
Option.ofObj >> Option.filter (String.contains d) >> Option.map (StringHelpers.before d)
let (|StringEqualsI|_|) d = Option.ofObj >> Option.filter (String.equalsI d) >> Option.map ignore
let (|InvariantEqualI|_|) d = Option.ofObj >> Option.filter(fun arg -> String.Compare(d, arg, StringComparison.InvariantCultureIgnoreCase) = 0) >> Option.map ignore
let (|IsNumeric|_|) = Option.ofValueString >> Option.filter (String.forall Char.IsNumber) >> Option.map ignore
let (|Contains|_|) d = Option.ofObj >> Option.filter (contains d) >> Option.map ignore
let (|ContainsI|_|) d = Option.ofObj >> Option.filter (containsI d) >> Option.map ignore
let (|StringContains|_|) d = Option.ofObj >> Option.filter (contains d) >> Option.map ignore
let (|OrdinalEqualI|_|) (str:string) = Option.ofObj >> Option.filter(fun arg -> String.Compare(str, arg, StringComparison.OrdinalIgnoreCase) = 0) >> Option.map ignore
let (|RMatch|_|) (pattern:string) (x:string) =
let m = System.Text.RegularExpressions.Regex.Match(x,pattern)
if m.Success then Some m else None
let inline fromParser f x =
match f x with
| true, v -> Some v
| _, _ -> None
let inline (|TryParse|_|) parser (x:string): 't option =
match x with
| null -> None
| _ -> fromParser parser x
let (|ParseInt|_|) x = (|TryParse|_|) System.Int32.TryParse x |> Option.map LanguagePrimitives.Int32WithMeasure
let (|ParseInt64|_|) = (|TryParse|_|) System.Int64.TryParse
let (|ParseGuid|_|) = (|TryParse|_|) System.Guid.TryParse
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
// 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 inline (|IsTOrTryParse|_|) (t,parser) (x:obj): 't option =
match x with
| null -> None
| :? 't as t -> Some t
| v when v.GetType() = t -> Some (v :?> 't)
| :? string as p -> fromParser parser p
| _ -> None
type System.String with
static member IsValueString =
function
| ValueString _ -> true
| _ -> false
#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
type ChangedValue<'T> = {OldValue:'T;NewValue:'T}
type ChangeType<'T> =
| Unchanged of ChangedValue<'T>
| Added of 'T
| Removed of 'T
| Changed of ChangedValue<'T>
with
member x.GetChangeValues () =
match x with
| Changed y -> Some y
| _ -> None
member x.GetAdded () =
match x with
| Added y -> Some y
| _ -> None
member x.GetRemoved () =
match x with
| Removed y -> Some y
| _ -> None
module ChangeTracking =
let getChanges (changedItemValue:ChangedValue<'T list>) fIdentity fEqual =
let previous,current = changedItemValue.OldValue, changedItemValue.NewValue
let identities =
let oldIdentities = previous |> Seq.map fIdentity
let currentIdentities = current |> Seq.map fIdentity
oldIdentities |> Seq.append currentIdentities |> Seq.distinct |> List.ofSeq
identities
|> Seq.fold(fun changes identity ->
match previous |> Seq.tryFind (fun x -> fIdentity x = identity), current |> Seq.tryFind(fun x -> fIdentity x = identity) with
| None, None ->
failwithf "Identity function returned an identity not present in either item, or the identity was changed"
| Some prev,None ->
Removed prev :: changes
| None, Some curr ->
Added curr :: changes
| Some p, Some c ->
if fEqual p c then
Unchanged {OldValue=p;NewValue=c} :: changes
else
Changed {OldValue=p;NewValue=c} :: changes
) List.empty
// use structural equality
let getChangesUsingEquality changedItemValue fIdentity =
getChanges changedItemValue fIdentity (=)
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
type XElement with
static member GetElement1 name (x:XElement) = x.Element(XNamespace.None + name)
static member GetElements1 name (x:XElement) = x.Elements() |> Seq.filter(fun x -> x.Name.LocalName = name)
static member GetElements (x:XElement) = x.Elements()
()
//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"
open System.Collections.ObjectModel
// 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 isValid i = i > 0<_>
let i = if isValid i then i else failwithf "Invalid value"
member __.Value = i
/// valid values are 1..x
static member TryCreateOpt i =
if isValid i then
ValidIdentity<'T>(i) |> Some
else None
static member get (vi:ValidIdentity<_>) : int<'T> = vi.Value
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
[<RequireQualifiedAccess; CompilationRepresentation (CompilationRepresentationFlags.ModuleSuffix)>]
module ValidIdentity =
let isValid i = i > 0<_>
let optionOfInt (x:int<_>) = if isValid x then Some x else None
let optionOfNullable (x:int<_> Nullable) = x |> Option.ofNullable |> Option.bind optionOfInt
let (|IsValidIdentity|_|) x =
ValidIdentity.TryCreateOpt(x)
|> Option.map(fun vi -> vi.Value)
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
type System.Collections.ObjectModel.ReadOnlyCollection<'t> with
static member Empty = System.Collections.ObjectModel.ReadOnlyCollection<'t>(ResizeArray())
static member EmptyI = System.Collections.ObjectModel.ReadOnlyCollection<'t>.Empty :> IReadOnlyCollection<_>
module ReadOnlyCollection =
let empty<'t> : ReadOnlyCollection<'t> = ReadOnlyCollection<'t>.Empty
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)
static member invoke4 (x:System.Action<_,_,_,_>) a b c d = x.Invoke(a,b,c,d)
static member invoke5 (x:System.Action<_,_,_,_,_>) a b c d e = x.Invoke(a,b,c,d,e)
module Func =
let inline invoke (x:System.Func<_>) () = x.Invoke()
let inline invoke1 (x:System.Func<_,_>) y = x.Invoke y
let inline invoke2 (x:System.Func<_,_,_>) y z = x.Invoke(y, z)
let inline invoke3 (x:System.Func<_,_,_,_>) a b c = x.Invoke(a,b,c)
let inline invoke4 (x:System.Func<_,_,_,_,_>) a b c d = x.Invoke(a,b,c,d)
let inline invoke5 (x:System.Func<_,_,_,_,_, _>) a b c d e = x.Invoke(a,b,c,d,e)
//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 Map =
let ofDictionary x =
x :> _ seq
|> Seq.map (|KeyValue|)
|> Map.ofSeq
/// in the event of a matching key, 2nd in wins
let merge<'K ,'V when 'K : comparison> = Map.fold(fun acc (key:'K) (value:'V) -> Map.add key value acc)
let intersect (baseDict:IDictionary<_,_>) (overrideOrAppendDict:IDictionary<_,_>) =
baseDict
|> Seq.append overrideOrAppendDict
|> Seq.map (|KeyValue|)
|> dict
module PathHelpers=
open System.IO
let findNewest path =
Directory.GetFiles path
|> Seq.map File.GetLastWriteTime
|> Seq.max
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
// return a Tuple where (A, B) (both present if they have a match)
let forceJoinWith (b:'b list, f:'b -> 'a) (a:'a list) : ('a option * 'b option) list =
let a = a |> Set.ofList
let b = b |> List.map(fun b -> f b, b) |> dict
let result =
seq{
yield! a |> Seq.map(fun x -> if b.ContainsKey x then (Some x, Some b.[x]) else Some x,None)
yield! b.Keys |> Seq.filter(a.Contains >> not) |> Seq.map (fun bKey -> None,Some b.[bKey] )
}
result
|> List.ofSeq
type System.Collections.Generic.List<'T> with
static member tryItem i (x:List<'T>) =
if x.Count > i then
Some x.[i]
else None
module Observables =
open System.Collections.ObjectModel
open System.Collections.Specialized
// when loading a large number of items, wait until all are loaded to fire
// implementation from https://peteohanlon.wordpress.com/2008/10/22/bulk-loading-in-observablecollection/
type SuppressibleObservableCollection<'T> () =
inherit ObservableCollection<'T>()
let mutable suppress = false
override __.OnCollectionChanged e =
if not suppress then
base.OnCollectionChanged e
member x.AddRange items =
if isNull items then
raise <| ArgumentNullException "items"
suppress <- true
items
|> Seq.iter x.Add
suppress <- false
x.OnCollectionChanged (NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))
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