如何重用 Haskell Either 绑定链中的中间值?

How do I reuse an intermediate value in chain of Haskell Either binds?

我确定已经回答了这个问题,但显然我不知道要搜索什么。

我正在开发我的第一个重要 Haskell 程序 -- 模拟我喜欢的纸牌游戏。我的程序正在运行,但我确信有一种情况可以得到更好的处理。

如果我有一系列 Either String TypeChangesBasedOnTheFunction 的绑定。

playerInput <- getLine
case playerInput of
   {- CASE STUFF NOT IMPORTANT TO THIS QUESTION -}
   _ -> do let handValue = inputHasAllValidChars playerInput >>= makeDeckFromString >>= deckSubset (getCurrentPlayersDeck gameState) >>= whatHandRepresents >>= handBeatsCurrentTopTrick

在这部分代码 运行 之后不久,我需要 whatHandRepresents 的值。我可以再次 运行 相同的绑定链,但我确信必须有更好的方法来存储在上面的代码中确定的值。

我的问题是,是否可以存储这个值。如果可以,怎么做?

你必须把它一直穿回到你需要的地方。

repr <- case playerInput of
    -- now you have to return something of the appropriate type,
    -- say, `Left "didn't get it"`, from these other cases.

    _ -> do let repr = ... >>= whatHandRepresents
                handValue = repr >>= handBeatsCurrentTopTrick
            -- use handValue
            return repr
-- now use repr :: Either String HandRepresentationOrWhatever

我当然希望您实际上是在默认情况下使用 handValue,而不是试图分配它供以后使用。它只会在那种情况下的范围内;如果你想在之后使用它,你也必须 return 它,就像 repr (例如在一个元组中)。