跨保护模式共享定义

时间:2016-01-12 11:18:49

标签: haskell pattern-matching helper

说我有一个功能:

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完成,还是必须编写辅助函数?

1 个答案:

答案 0 :(得分: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