跨守卫模式共享定义

sharing definitions across guard patterns

假设我有一个函数:

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

如何在两个保护块之间任意共享complex_calculation?这可以通过 let / where 来完成还是我必须编写一个辅助函数?

是的,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