Ronald
Ronald

Reputation: 667

Railway programming F#

I am trying to use the railway programming in F# using result as described in Scott Wlaschin's book 'Domain modeling made functional'. Normally a function has the structure

let functionName parameter : Result<ResultType, ErrorType> =
    result {
        let! resultValue = someValidationAndTransformation parameter
        return resultValue
    }

But I want to return also some calculated fields, in both to Ok and the Error case. The best I could come up with was

let functionName parameter : Result<ResultType, ErrorType> * CalculatedFields =
    let mutable calculatedFields = {some defaultvalue}
    let result = 
        result {
            let! resultValue = someValidationAndTransformation parameter
            let calculatedField = someCalculation resultValue
            calculatedFields <- {calculatedFields with calculatedField}
            return resultValue
        }
    result, calculatedFields

This mutable field does not look nice. Is there a better way to get the calculated fields in both Ok and Error case?

Upvotes: 3

Views: 123

Answers (1)

sdgfsdh
sdgfsdh

Reputation: 37121

I would use a match in this situation:

let functionName parameter : Result<ResultType, ErrorType> * CalculatedFields =
  let result = someValidationAndTransformation parameter

  let calculatedFields = 
    match result with
    | Ok x -> someCalculation x
    | Error e -> { some defaultvalue }

  result, calculatedFields

Upvotes: 2

Related Questions