This may be a simple matter, but I'm writing a function that I want to return a record, and several of the fields require doing things that might fail, so right now the resulting record looks like this (let's say it's type aliased as MyRecord
).
{ field1 : Maybe a
, field2 : Maybe a
, field3 : Maybe a
}
However, this does not accurately represent the "real" meaning of what has happened. The underlying goal of the function is to validate as well as reformat some data. So I want to say that if I have a MyRecord
, I have three fields worth of a
's. If I don't have those fields, I want to know that I don't have a MyRecord
. Logically, then, I want to return a Maybe MyRecord
, but for the life of me, this is escaping my newish-to-elm capabilities.
Currently, I am creating the record all at once, but that does not work for obvious reasons:
{ field1 = maybeProducingFunction1
, field2 = maybeProducingFunction2
, field3 = maybeProducingFunction3
}
How can I create this record so that if any of these functions produce a Nothing
, the whole record is Nothing
?
If I understand correct, what you want is to define a type
type alias MyRecord =
{ field1 : Maybe a
, field2 : Maybe a
, field3 : Maybe a
}
and to create a record only when you have all three pieces of constituent data? The way to do that is with Maybe.map3:
myResult =
Maybe.map3 MyRecord
maybeProducingFunction1
maybeProducingFunction2
maybeProducingFunction3
This will do all the Maybe checks for you and only construct your record if they all have Just
values.
There is also a similar approach with Result
that you can take which has the advantage that you can pass along information about which function failed (strictly speaking which was the first function to fail).