我有一个sideH
函数,冒着Prelude.head []
的风险。因此,我使用Maybe编写它,以避免这种情况:
sideH :: Residue -> Maybe (Atom, Atom)
sideH res
-- Make sure the elements exist
| nits /= [] && cars /= [] && oxys /= [] = Just (newH1, newH2)
| otherwise = Nothing where
...
以上工作完全符合预期,没有错误。现在,在调用sideH
(不是do构造)的函数中,我必须处理sideH
返回Nothing
的情况:
callerFunc :: [Residue] -> Aromatic -> [(Double, Double)]
callerFunc [] _ = []
callerFunc (r:rs) aro
-- Evaluate only if there is something to evaluate
| newHs /= Nothing = (newH1Pos, newH2Pos)
| otherwise = callerFunc rs aro where
newHs = sideH r
newH1Pos = atomPos $ fst $ fromJust newHs
newH2Pos = atomPos $ snd $ fromJust newHs
如果我在newH1Pos
时尝试评估newH2Pos
或newH = Nothing
,则会失败,因为fromJust Nothing
是错误的。但是,我希望这永远不会发生。我希望callerFunc
评估newHs
,Just something
或Nothing
。如果是Nothing
,则callerFunc
将进入下一步,而不会评估newH1Pos
或newH2Pos
。情况似乎并非如此。我收到了*** Exception: Maybe.fromJust: Nothing
错误,我希望newHs
能够返回Nothing
。
我被要求提供更多代码。我试图提出一个重现错误的最小情况,但同时,这是完整有问题的callerFunc
代码。
-- Given a list of residues and an aromatic, find instances where there
-- is a Hydrogen bond between the aromatic and the Hydrogens on Gln or Asn
callerFunc :: [Residue] -> Aromatic -> [(Double, Double)]
callerFunc [] _ = []
callerFunc (r:rs) aro
-- GLN or ASN case
| fst delR <= 7.0 && (resName r == gln || resName r == asn) &&
newHs /= Nothing && snd delR <= 6.0 =
[(snd delR, fst delR)] ++ hBondSFinder rs aro
| otherwise = hBondSFinder rs aro where
-- Sidechain identifying strings
gln = B.pack [71, 76, 78]
asn = B.pack [65, 83, 78]
-- Get the location of the Hydrogens on the residue's sidechain
newHs = sideH r
newH1Pos = atomPos $ fst $ fromJust newHs
newH2Pos = atomPos $ snd $ fromJust newHs
-- Get the location of the Nitrogen on the mainchain of the Residue
ats = resAtoms r
backboneNPos = atomPos $ head $ getAtomName ats "N"
hNVect1 = Line2P {lp1 = newH1Pos, lp2 = backboneNPos}
hNVect2 = Line2P {lp1 = newH2Pos, lp2 = backboneNPos}
interPoint1 = linePlaneInter (aroPlane aro) hNVect1
interPoint2 = linePlaneInter (aroPlane aro) hNVect2
delR = minimum [(interPoint1 `dist` newH1Pos, delr1),
(interPoint2 `dist` newH2Pos, delr2)]
delr1 = interPoint1 `dist` (aroCenter aro)
delr2 = interPoint2 `dist` (aroCenter aro)
我知道这是一个痛苦的代码转储。我试图减少它。
答案 0 :(得分:3)
这个问题的答案(在评论中提到)不符合评论:“我不确定如何使用模式匹配来删除这些if语句。”。
就像这样,例如,虽然仍有一些代码气味可能会通过一些额外的重构得到改善:
sideH :: Residue -> Maybe (Atom, Atom)
sideH res = case (nits, cars, oxys) of
(_:_, _:_, _:_) -> Just (newH1, newH2)
_ -> Nothing
where
...
如果你有灵活的道德,你可以尝试这样的事情:
sideH :: Residue -> Maybe (Atom, Atom)
sideH res = do
_:_ <- return nits
_:_ <- return cars
_:_ <- return oxys
return (newH1, newH2)
where
...
同样,如果有更多的上下文和代码可用于推荐,这两个代码示例都可能会改进大约十倍。