[Haskell-beginners] elegant handling of maybe and non-maybe values

Christopher Howard christopher.howard at frigidcode.com
Fri Sep 21 03:25:03 CEST 2012

I have a code situation similar to this simplified one: Let's say that
I've got a value v that is a Maybe type, and values x, y, and z that are
not. x, y, and z are dependent on the value inside v. So I must provide
default values for x, y, and z. An additional complication is that every
calculation returns a new (possibly different) value for v. So, I could
do something like this:

let (v', x) = case v of
                Nothing -> (Nothing, defaultValueOfX)
                Just vValue -> f vValue in
let (v'', y) = case v' of
                 Nothing -> (Nothing, defaultValueOfY)
                 Just vValue -> g vValue in
let (v''', z) = case v'' of
                  Nothing -> (Nothing, defaultValueOfZ)
                  Just vValue -> h vValue in

(f, g, h represent the calculations I am performing.) In the end, I need
the values of x, y, and z, and the last v value.

Obviously, the above solution is not very elegant, especially if I add a
few more variables. My other thought was some kind of fold operation,
where I store the functions (calculations) and the default values in a
list, and then fold over the list, applying subsequent values of v or
returning default values, as appropriate. But this seems rather clunky,
especially if I want to attach the values in the new list to variable
names afterwards.

Is there a better approach?


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 551 bytes
Desc: OpenPGP digital signature
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120920/fa1586e7/attachment.pgp>

More information about the Beginners mailing list