fsprojects / Fleece

Json mapper for F#
http://fsprojects.github.io/Fleece
Apache License 2.0
199 stars 31 forks source link

Combinator to interpret absence of a field as an empty array #60

Closed gusty closed 2 years ago

gusty commented 6 years ago

The same way we have jfieldOpt which interpret the absence of a field as a None, we could add a combinator that interpret the absence as an empty array.

How can we call that combinator?

Or maybe we can upgrade the existing jfieldOpt to handle multiple values.

7sharp9 commented 6 years ago

My vote would be for jfieldMany or jfieldRepeated, is there anyway to work around this with the current combinators?

vchekan commented 6 years ago

"jfieldRepeated" repeated is protobuf terminology and will be confusing in fleece context.

gusty commented 5 years ago

I was analyzing this and came up to with an easy way to have this functionality, with the existing combinators.

Let's pretend we have a pair of functions to go from/to an option of list / plain list:

let flatten = function None -> [] | Some x -> x
let expand = function [] -> None | x  -> Some x

Now, we can use them this way:

type Repeat = { Name : string ; Ids : int list } with
    static member JsonObjCodec =
        fun n i -> { Name = n; Ids = flatten i }
        <!> jreq  "name" (fun x -> Some x.Name)
        <*> jopt  "ids"  (fun x -> expand x.Ids)

And we'll get the desired effect.

This has the additional advantage that we can apply this to any collection, not just lists and arrays.

7sharp9 commented 5 years ago

In Falanx this would be slightly different as it would be a ResizeArray instead

gusty commented 5 years ago

Yes, maybe something like this;

let flatten =  function None -> ResizeArray () | Some x -> x
let expand (x: ResizeArray<_>) = if Seq.isEmpty x then None else Some x
7sharp9 commented 5 years ago

Probably this as we would want 0 length intact.

let flattenResizeArray = function None -> ResizeArray() | Some x -> x
let expandResizeArray = function null -> None | x  -> Some x
gusty commented 2 years ago

Closing this as a mechanism was suggested in the comments and additionally:

Or maybe we can upgrade the existing jfieldOpt to handle multiple values.

jopt now as of 0.10.0 supports any type that has defined the zero value, including lists and arrays, which would do exactly what the title of the issue describes.