match by value in a discriminated union, in F# - f#

with this union:
type T =
| A
| B
| C
and a T list
I would like to implement something like this pseudo code:
let countOfType (t: Type) (l: T list) =
l
|> List.filter (fun x -> x.GetType() = t)
|> List.length
when I would pass if I want to count the 'A', 'B', etc..
but A.GetType() and B.GetType() return the T type, so this doesn't work.
Is there a way where I could check the type by passing it as a parameter?
The practical case here is that I have a Map that gets updated every few seconds and its values are part of the same DU. I need to be able to see how many of each type, without having to update the code (like a match block) each time an entry gets added.
Addendum:
I simplified the original question too much and realized it after seeing Fyodor's answer.
So I would like to add the additional part:
how could this also be done for cases like these:
type T =
| A of int
| B of string
| C of SomeOtherType

For such enum type T as you specified, you can just use regular comparison:
let countOfType t (l: T list) =
l
|> List.filter (fun x -> x = t)
|> List.length
Usage:
> countOfType A [A; A; B; C; A]
3
> countOfType B [A; A; B; C; A]
1

Try List.choose: ('a -> 'b option) -> 'a list -> 'b list, it filters list based on 'a -> 'b option selector. If selectors evaluates to Some, then value will be included, if selector evaluates to None, then value will be skipped. If you worry about allocations caused by instantiation of Some, then you'll have to implement version that will use ValueOption
let onlyA lis =
lis |> List.choose (function
| (A _) as a -> Some a
| _ -> None)
let onlyB lis =
lis |> List.choose (function
| (B _) as b -> Some b
| _ -> None)
let lis = [
A 1
A 22
A 333
B ""
B "123"
]
lis |> onlyA |> List.length |> printfn "%d"

You can pattern match, and throw away the data, to create a function for the filter.
type T =
| A of int
| B of string
| C of float
[A 3;A 1;B "foo";B "bar";C 3.1; C 4.6]
|> List.filter (fun x ->
match x with
| A _ -> true
| B _ -> false
| C _ -> false
)
|> List.length
But in general i would asume, that you create a predicate function in your modul.
let isA x =
match x with
| A _ -> true
| _ -> false
if you have those functions you can just write
[A 3;A 1;B "foo";B "bar";C 3.1; C 4.6]
|> List.filter isA
|> List.length

Related

How to group data attached to discriminated union values, in F#?

Here is an example:
type Events =
| A of AData
| B of BData
| C of CData
and I have a list of those:
let events : Events list = ...
I need to build a list by event type. Right now I do this:
let listA =
events
|> List.map (fun x ->
match x with
| A a -> Some a
| _ -> None
)
|> List.choose id
and, repeat for each type...
I also thought I could do something like:
let rec split events a b c =
match events with
| [] -> (a |> List.rev, b |> List.rev, c |> List.rev)
| h :: t ->
let a, b, c =
match h with
| A x -> x::a, b, c
| B x -> a, x::b, c
| C x -> a, b, x::c
split t a b c
Is there a more elegant manner to solve this?
This processes a lot of data, so speed is important here.
You can fold back the list of events to avoid writing a recursive function and reversing results. With an anonymous record you will need to define it first and then pipe both arguments ||> to List.foldBack:
let eventsByType =
(events, {| listA = []; listB = []; listC = [] |})
||> List.foldBack (fun event state ->
match event with
| A a -> {| state with listA = a :: state.listA |}
| B b -> {| state with listB = b :: state.listB |}
| C c -> {| state with listC = c :: state.listC |})
With a named record it is more elegant:
{ listA = []; listB = []; listC = [] } |> List.foldBack addEvent events
addEvent is the same as the lambda above except usage of a named record {} instead of {||}.
I think your solution is pretty good, although you do pay a price for reversing the lists. The only other semi-elegant approach I can think of is to unzip a list of tuples:
let split events =
let a, b, c =
events
|> List.map (function
| A n -> Some n, None, None
| B s -> None, Some s, None
| C b -> None, None, Some b)
|> List.unzip3
let choose list = List.choose id list
choose a, choose b, choose c
This creates several intermediate lists, so careful internal use of Seq or Array instead might perform better. You would have to benchmark to be sure.
Test case:
split [
A 1
A 2
B "one"
B "two"
C true
C false
] |> printfn "%A" // [1; 2],[one; two],[true; false]
By the way, your current solution can be simplified to:
let listA =
events
|> List.choose (function A a -> Some a | _ -> None)
If you keep the union cases, you can group the list items like this.
let name = function
| A _ -> "A"
| B _ -> "B"
| C _ -> "C"
let lists =
events
|> List.groupBy name
|> dict
And then you can extract the data you want.
let listA = lists["A"] |> List.map (fun (A data) -> data)
(The compiler doesn't realize the list only consists of "A" cases, so it gives an incomplete pattern match warning😀)

How to properly pattern match JsonConversions

Hi I have the following code which works as I expect but the compiler warns me about incomplete pattern matching when I pattern match in the Option.defaultWith function. Is there a smarter way to achieve the same effect but without warnings?
I have been thinking about throwing an exception for the rest of the cases but that's pretty ugly.
namespace JsonParser
open System
open System.Globalization
open FSharp.Data
open FSharp.Data.Runtime
type public Key = string
type public Value =
| Int of int
| Double of double
| Decimal of decimal
| String of string
| DateTime of DateTime
| Boolean of Boolean
| Array of Value []
| Guid of Guid
| Null
| Object of Record []
and public Record =
{ Key: Key
Value: Value }
module public Json =
let private culture = CultureInfo.InvariantCulture
let private emptyArray = Array.empty<String>
let rec private map (value: JsonValue) =
JsonConversions.AsInteger culture value
|> Option.map Value.Int
|> Option.orElseWith (fun () -> JsonConversions.AsDecimal culture value |> Option.map Value.Decimal)
|> Option.orElseWith (fun () -> JsonConversions.AsFloat emptyArray true culture value |> Option.map Decimal |> Option.map Value.Decimal)
|> Option.orElseWith (fun () -> JsonConversions.AsGuid value |> Option.map Value.Guid)
|> Option.orElseWith (fun () -> JsonConversions.AsDateTime culture value |> Option.map Value.DateTime)
|> Option.orElseWith (fun () -> JsonConversions.AsBoolean value |> Option.map Value.Boolean)
|> Option.defaultWith (fun () ->
match value with
| JsonValue.String x -> Value.String x
| JsonValue.Null -> Value.Null
| JsonValue.Array x ->
x
|> Array.map map
|> Value.Array
| JsonValue.Record x ->
x
|> Array.map (fun (x, y) ->
{ Key = x
Value = map y })
|> Value.Object)
The answer really depends on how you want to handle various corner cases in your JSON data.
The operations in JsonConversions are implemented in a way where they attempt to convert the value to the target type whenever this can reasonably be done. This means that using those, a value true, 1 and "yes" will all be converted to boolan true. Is this what you want? If so, then I would probably just add a case to the pattern match that throws an exception, saying that the situation should not happen:
match value with
| JsonValue.String x -> Value.String x
| JsonValue.Null -> Value.Null
| JsonValue.Array x -> (...)
| JsonValue.Record x -> (...)
| JsonValue.Float _ | JsonValue.Number _ | JsonValue.Boolean _ ->
failwith "should never happen: Numbers and booleans handled earlier!"
If you want to turn JSON value "yes" to Value.String("yes") rather than to Value.Boolean(true), then it is a lot easier if you directly pattern match on JsonValue:
let rec private map (value: JsonValue) =
match value with
| JsonValue.Float f -> Value.Double f
| JsonValue.Number n -> Value.Decimal n
| JsonValue.Boolean b -> Value.Boolean b
| JsonValue.String x -> Value.String x
| JsonValue.Null -> Value.Null
| JsonValue.Array x ->
x |> Array.map map |> Value.Array
| JsonValue.Record x ->
x |> Array.map (fun (x, y) -> { Key = x; Value = map y }) |> Value.Object
You can find the details about how JsonConversions work by looking at the relevant file in the source code: JsonConversions and TextConversions.

How Reflection MakeUnion three level type?

I want to try to reflect all types of combinations,
I am using a recursive function
Working at two level
But it won't work at the third level.
open Microsoft.FSharp.Reflection
let rec getAll<'A> (c : UnionCaseInfo) : obj [] =
match c.GetFields() |> List.ofSeq with
| [ x ] when FSharpType.IsUnion x.PropertyType ->
FSharpType.GetUnionCases(x.PropertyType)
|> Array.map (fun uc ->
FSharpValue.MakeUnion(c, getAll(uc)))
|> Array.ofSeq
| _ ->
[| FSharpValue.MakeUnion(c, Array.empty) |]
type C = | C1 | C2
//type B = | B1 | B2
type B = | B1 of C | B2
type A =
| A1
| A2toB of B
| A3
static member GetAll =
FSharpType.GetUnionCases(typeof<A>)
|> Seq.collect getAll<A>
|> Seq.cast<A>
|> Array.ofSeq
(A2toB (B1 C1)).ToString() |> printfn "%A"
A.GetAll |> Array.map (fun t -> t.ToString() |> printfn "%A")
"A2toB (B1 C1)"
Unhandled Exception: System.Reflection.TargetParameterCountException: Parameter count mismatch.
when only use two levels
type B = | B1 | B2
Correct return
"A1"
"A2toB B1"
"A2toB B2"
"A3"
The reason you're getting the exception is that when you call getAll in the recursive case for B1, the field type is C, and C has two cases, C1 | C2, so you get back an array of two elements. Then, that array is passed to the MakeUnion call for B1, which expects only one element (a single instance of C). The call fails because there's an unexpected extra C passed in the array.
You can make this work for your example case by adding something like Array.take 1 to your recursive call to getAll, but it won't work in the general case. I'm not entirely sure what you're trying to accomplish, so providing a general solution is currently a little tricky. If you can clarify your requirements, we can probably provide a better solution.
Here's a version that works for your specific example (though as I said, this is not a good general solution):
let rec getAll<'A> (c : UnionCaseInfo) : obj [] =
match c.GetFields() |> List.ofSeq with
| [ x ] when FSharpType.IsUnion x.PropertyType ->
FSharpType.GetUnionCases(x.PropertyType)
|> Array.map (fun uc ->
FSharpValue.MakeUnion(c, getAll(uc) |> Array.take 1))
|> Array.ofSeq
| _ ->
[| FSharpValue.MakeUnion(c, Array.empty) |]
Here's the output:
"A1"
"A2toB (B1 C1)"
"A2toB B2"
"A3"
thanks Aaron M. Eshbach for found my recursive error, I fix my code
let rec getAll<'A> (c: UnionCaseInfo): obj [] =
match c.GetFields() |> List.ofSeq with
| [ x ] when FSharpType.IsUnion x.PropertyType ->
FSharpType.GetUnionCases(x.PropertyType)
|> Array.map (fun uc ->
let t = uc.Name
getAll (uc) |> Array.map (fun a ->
FSharpValue.MakeUnion(c, [| a |]))
)
|> Array.concat
|> Array.ofSeq
| _ ->
let t = c.Name
[| FSharpValue.MakeUnion(c, Array.empty) |]
I think your code can be simplified. Let us reduce the level of nesting by one; utilize an array sequence expression for generation; and also, let's recurse on System.Type instead of on the unwieldy UnionCaseInfo.
The type parameter, removed below, could have been used at run-time only for unboxing the outermost union type. The type of the other generated cases is necessarily obj, also demonstrating the somewhat limited utility of dynamically generated union cases.
let rec getCases t = [|
for ucinfo in FSharpType.GetUnionCases t do
match ucinfo.GetFields() with
| [|pinfo|] when FSharpType.IsUnion pinfo.PropertyType ->
for x in getCases pinfo.PropertyType ->
FSharpValue.MakeUnion(ucinfo, [|x|])
| _ -> yield FSharpValue.MakeUnion(ucinfo, [||]) |]
// val getCases : t:System.Type -> obj []
type A = A1 | A2toB of B | A3
and B = B1 of C | B2
and C = C1 | C2
getCases typeof<A>
// val it : obj [] = [|A1; A2toB (B1 C1); A2toB (B1 C2); A2toB B2; A3|]

Railway Oriented Programming and partial application

I like using ROP when I have to deal with IO/Parsing strings/...
However let's say that I have a function taking 2 parameters. How can you do clean/readable partial application when your 2 parameters are already a Result<'a,'b> (not necessary same 'a, 'b)?
For now, what I do is that I use tuple to pass parameters and use the function below to get a Result of a tuple so I can then bind my function with this "tuple-parameter".
/// Transform a tuple of Result in a Result of tuple
let tupleAllResult x =
match (fst x, snd x) with
| Result.Ok a, Result.Ok b -> (a,b) |> Result.Ok
| Result.Ok a, Result.Error b -> b |> Result.Error
| Result.Error a, _ -> a |> Result.Error
let f (a: 'T, b: 'U) = // something
(A, B) |> tupleAllResult
|> (Result.bind f)
Any good idea?
Here what I wrote, which works but might not be the most elegant
let resultFunc (f: Result<('a -> Result<'b, 'c>), 'd>) a =
match f with
| Result.Ok g -> (g a) |> Result.Ok |> Result.flatten
| Result.Error e -> e |> Result.Error |> Result.flatten
I am not seeing partial application in your example, a concept related to currying and argument passing -- that's why I am assuming that you are after the monadic apply, in that you want to transform a function wrapped as a Result value into a function that takes a Result and returns another Result.
let (.>>.) aR bR = // This is "tupleAllResult" under a different name
match aR, bR with
| Ok a, Ok b -> Ok(a, b)
| Error e, _ | _, Error e -> Error e
// val ( .>>. ) : aR:Result<'a,'b> -> bR:Result<'c,'b> -> Result<('a * 'c),'b>
let (<*>) fR xR = // This is another name for "apply"
(fR .>>. xR) |> Result.map (fun (f, x) -> f x)
// val ( <*> ) : fR:Result<('a -> 'b),'c> -> xR:Result<'a,'c> -> Result<'b,'c>
The difference to what you have in your question is map instead of bind in the last line.
Now you can start to lift functions into the Result world:
let lift2 f xR yR =
Ok f <*> xR <*> yR
// val lift2 :
// f:('a -> 'b -> 'c) -> xR:Result<'a,'d> -> yR:Result<'b,'d> -> Result<'c,'d>
let res : Result<_,unit> = lift2 (+) (Ok 1) (Ok 2)
// val res : Result<int,unit> = Ok 3

F# : filtering None out and keeping only Some

A quick question on how to effectively group/filter list/seq.
Filter for only records where the optional field is not None
Remove the "option" parameter to make future processes easier (as None has been filtered out)
Group (this is of no problem I believe)
Am I using the best approach?
Thanks!
type tmp = {
A : string
B : int option }
type tmp2 = {
A : string
B : int }
let inline getOrElse (dft: 'a) (x: 'a option) =
match x with
| Some v -> v
| _ -> dft
let getGrouped (l: tmp list) =
l |> List.filter (fun a -> a.B.IsSome)
|> List.map (fun a -> {A = a.A ; B = (getOrElse 0 (a.B)) })
|> List.groupBy (fun a -> a.A)
The most natural approach for map+filter when option is involved is to use choose, which combines those two operations and drops the option wrapper from the filtered output.
Your example would look something like this:
let getGrouped (l: tmp list) =
l
|> List.choose (fun a ->
a.B
|> Option.map (fun b -> {A = a.A; B = b})
|> List.groupBy (fun a -> a.A)
The simple solution is just use the property that an option can be transformed to list with one or zero elements then you can define a function like:
let t1 ({A=a; B=b} : tmp) =
match b with
| (Some i) -> [{ A = a; B= i}]
| _ -> []
let getGrouped (l: tmp list) =
l |> List.collect t1
|> List.groupBy (fun a -> a.A)

Resources