【问题标题】:sharing definitions across guard patterns跨守卫模式共享定义
【发布时间】:2016-01-12 11:18:49
【问题描述】:

假设我有一个函数:

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

【问题讨论】:

    标签: haskell pattern-matching helper


    【解决方案1】:

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

    【讨论】:

    • 没有“哪里”? CSE 仍有可能共享。
    • @d8d0d65b3f7cf42 除非arbitrary_complex_calculation 具有多态类型(不过这会与Show 实例混淆)。另外,GHC uses CSE only sparsely(但我不知道这是否仍然适用于 GHC 7.10+)。
    猜你喜欢
    • 2020-01-07
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 2017-10-20
    • 2018-02-14
    • 2011-09-28
    相关资源
    最近更新 更多