我读到这个:
http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns
我喜欢这个主意,想使用扩展。但是,我想确定一件事:是否针对单个匹配对视图函数进行一次评估。
所以假设我们有:
{-# LANGUAGE ViewPatterns #-}
...
f (view -> Nothing) = ...
f (view -> Just x) = ...
view :: a -> Maybe b
现在假设我调用f a
. 为view
给定的参数调用两次还是只调用一次a
?
编辑:
我试图找出是否是这种情况并写了以下内容:
{-# LANGUAGE ViewPatterns #-}
import System.IO.Unsafe
blah (ble -> Nothing) = 123
blah (ble -> Just x) = x
ble x = unsafePerformIO $ do
putStrLn $ "Inside ble: " ++ show x
return x
main :: IO ()
main = do
putStrLn $ "Main: " ++ show (blah $ Just 234)
使用 GHC 输出:
Inside ble: Just 234
Inside ble: Just 234
Main: 234
使用 GHC 输出(经过优化)
Inside ble: Just 234
Main: 234
使用 GHCi 输出:
Main: Inside ble: Just 234
Inside ble: Just 234
234