跨保护模式共享定义

Abr*_*m P 3 haskell helper pattern-matching

说我有一个功能:

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

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

Zet*_*eta 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
Run Code Online (Sandbox Code Playgroud)