共享定义在守卫模式中的应用

3

假设我有一个函数:

arbitrary :: String -> String -> Maybe String
arbitrary st1 st2 | (st1 == st2) = Just "foo"
                  | (arbitrarily_complex_calculation == 7) = Nothing
                  | otherwise = Just $ show arbitrarily_complex_calculation

我应该如何在两个保护块之间共享任意复杂的计算?这可以通过let/where完成,还是必须编写一个辅助函数?

1个回答

9
是的,在卫兵中使用where子句是有效的(并经常使用):
arbitrary :: String -> String -> Maybe String
arbitrary st1 st2 
  | st1 == st2 = Just "foo"
  | acc ==  7  = Nothing
  | otherwise  = Just $ show acc
 where 
   acc = arbitrarily_complex_calculation

没有“where”呢?CSE仍然可以共享。 - d8d0d65b3f7cf42
1
@d8d0d65b3f7cf42 除非 arbitrary_complex_calculation 具有多态类型(这会影响 Show 实例),否则不会。此外,GHC 仅零星使用CSE(但我不知道在 GHC 7.10+ 中是否仍然如此)。 - Zeta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接