Getting values ​​from an ADT chain with Maybe's

I have some ADT, each of which may or may not contain another ADT. I need to get data from lower levels, and I write very repeating code, which, I am sure, can be eliminated. I looked at the sample code in Real World Haskell and in "Learn You a Haskell For Great Good", but I can't figure it out. The following is an example of inappropriate ADT details.

  T24Report
      - projTitle :: Maybe ProjectTitle
            - zip :: Maybe String

To get the zip code from StreetAddress, I ended up with this:

 projNameStr :: T24Report -> String
 projNameStr t24 = if isNothing projTitleMaybe
                    then ""
                    else (fromMaybe "") $ zip $ fromJust projTitleMaybe
                where
                    projTitleMaybe = projTitle $ project t24

As the depth of the chain of objects increases, repeatability of the code also. There must be a better way. Ideas? Recommendations? I could not find a similar question in StackOverflow, but I think it should be here ... this seems like a simple problem to ask about.

Thanks Tim

+5
2

, - :

projNameStr :: T24Report -> String
projName t24 = fromMaybe "" $ do
    title <- projTitle $ project t24
    zip title

do Nothing.

, Maybe, :

projNameStr :: T24Report -> String
projName t24 = fromMaybe "" $ projTitle (project t24) >>= zip

, . , . , , .

+6

, monad . - , X, , Y , , Z , , b Maybe c ,

do x <- maybeX
   y <- maybeY
   z <- maybeZ
   return (x,y,z)

Maybe (a, b, c), - Maybes Nothing, Nothing.

, -

projNameStr t24 = fromMaybe "" $ do t <- projTitle t24
                                    zip t
+6

All Articles