Working with result type

Hi all,

I have a section in my code where I build a record from multiple fields. The fields are wrapped into Results. The resulting record should also be a Result, containing either the record or the first error from one of the fields.

Now I created this abomination:

            match id, content, priority, isCompleted, description, order, projectId with
            | Result.Ok id,
              Result.Ok content,
              Result.Ok priority,
              Result.Ok isCompleted,
              Result.Ok description,
              Result.Ok order,
              Result.Ok projectId ->
                Result.Ok
                    { Id = id
                      Title = content
                      Priority = priority
                      IsCompleted = isCompleted
                      Description = description
                      Order = order
                      ProjectId = projectId }
            | Result.Error e, _, _, _, _, _, _ -> Result.Error e
            | _, Result.Error e, _, _, _, _, _ -> Result.Error e
            | _, _, Result.Error e, _, _, _, _ -> Result.Error e
            | _, _, _, Result.Error e, _, _, _ -> Result.Error e
            | _, _, _, _, Result.Error e, _, _ -> Result.Error e
            | _, _, _, _, _, Result.Error e, _ -> Result.Error e
            | _, _, _, _, _, _, Result.Error e -> Result.Error e

For ASCII art enthusiasts this might look pleasing, but from a code perspective?

Please anyone tell me that there is a much better way to do this!

Thx

If you pull in a result computation expression, like from FSharpx.Extras, you could do it as

open FSharpx

result {
  let! id = id
  let! content = content
  let! priority = priority
  let! isCompleted = isCompleted
  let! description = description
  let! order = order
  let! projectId = projectId
  return 
    { Id = id
      Title = content
      Priority = priority
      IsCompleted = isCompleted
      Description = description
      Order = order
      ProjectId = projectId }
}
1 Like

Thank you! Works like a charm!

1 Like