[Haskell-beginners] how to skip pattern match error when applying a mapM_
Daniel Trstenjak
daniel.trstenjak at gmail.com
Wed Jan 18 11:53:26 UTC 2017
Hi Frederic,
> after investigating, I could not switch the IO and the Maybe
> I need to process the IO in order to know if I have a Just or a Nothing
> So this is a IO (Maybe ...)
>
> I just would like to know if there is a better way to write this
> knowing
There's the MaybeT[1] monad transformer for this use case.
Instead of having:
row :: t -> Int -> IO (Maybe (DifTomoFrame DIM1))
you would have:
row :: t -> Int -> MaybeT IO (DifTomoFrame DIM1)
So 'row' might look like:
row d idx = do
n <- len d
let eof = n - 1 == idx
let nxs' = h5nxs d
let mu = 0.0
let komega = 0.0
let kappa = 0.0
let kphi = 0.0
gamma <- get_position' (h5gamma d) 0
delta <- get_position' (h5delta d) idx
wavelength <- get_position' (h5wavelength d) 0
let source = Source (head wavelength *~ nano meter)
let positions = concat [mu, komega, kappa, kphi, gamma, delta]
-- print positions
let geometry = Geometry K6c source positions Nothing
let detector = ZeroD
m <- lift $ geometryDetectorRotationGet geometry detector
poniext <- lift $ ponigen d (MyMatrix HklB m) idx
return $ DifTomoFrame { difTomoFrameNxs = nxs'
, difTomoFrameIdx = idx
, difTomoFrameEOF = eof
, difTomoFrameGeometry = geometry
, difTomoFramePoniExt = poniext
}
This assumes that the functions 'len', 'get_position' also return a 'MaybeT IO (...)'.
Functions in the IO monad - like 'geometryDetectorRotationGet' and 'ponigen' -
have to be "lifted" into the IO monad by 'lift'.
To get at the 'Maybe' result of 'row' you're using the 'runMaybeT' function in the IO monad:
main :: IO ()
main = do
...
result <- runMaybeT (row t int)
...
Greetings,
Daniel
[1] https://hackage.haskell.org/package/transformers-0.5.2.0/docs/Control-Monad-Trans-Maybe.html
More information about the Beginners
mailing list