评估"某事< - 东西"的陈述

Sté*_*ent 0 monads evaluation haskell lazy-evaluation operator-precedence

是否something <- stuff总是在Haskell中评估类似的语句,即使something在其余代码中没有调用它?(被something <- stuff称为"行动"? - 我不知道技术措辞).

如果这是真的,我还有另外一个问题.

我有一些代码从这样开始:

computeContour3d voxel voxmax level = do
    voxelmax <- somefunction voxel
    let max' = fromMaybe voxelmax voxmax
Run Code Online (Sandbox Code Playgroud)

也就是说,如果参数voxmax不是Nothing,则voxelmax没有必要,因为max' = fromJust voxmax在这种情况下.因此,如果我的第一个问题的回答是"是",我怎么能避免评估voxelmax何时没有必要?

Dan*_*ner 5

不,monadic绑定不能保证任何事情都得到评估.有懒惰的单子; 例如,读者monad不会强迫结果,somefunction voxel除非voxmaxNothing.

但是没有理由依赖这种行为; 很容易可靠地避免额外的计算:

computeContour3d voxel voxmax level = do
    max' <- case voxmax of
        Nothing -> somefunction voxel
        Just max -> return max
    -- use max'
Run Code Online (Sandbox Code Playgroud)

您可以考虑使用maybe,通常比显式更短case,如:

    max' <- maybe (somefunction voxel) return voxmax
Run Code Online (Sandbox Code Playgroud)