2016-01-12 113 views
3

说我有一个功能:共享定义

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

回答

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 
+0

并没有 “哪里”? CSE仍然可以共享。 – d8d0d65b3f7cf42

+1

@ d8d0d65b3f7cf42除非'arbitrary_complex_calculation'具有多态类型(尽管如此,这会与'Show'实例混淆)。此外,GHC [只使用CSE稀疏](https://wiki.haskell.org/GHC/FAQ#Does_GHC_do_common_subexpression_elimination.3F)(但我不知道这是否仍然在GHC 7.10+)。 – Zeta