Haskell 中的 ViewPatterns 和多次调用
我读到了这个:
http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns
我喜欢这个想法,想使用扩展。然而,我想确定一件事:视图函数是否针对单个匹配计算一次。
假设我们有:
{-# LANGUAGE ViewPatterns #-}
...
f (view -> Nothing) = ...
f (view -> Just x) = ...
view :: a -> Maybe b
现在假设我调用 f a
。对于给定的参数a
,view
是调用了两次还是只调用了一次?
编辑:
我试图找出是否是这种情况,并编写了以下内容:
{-# 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)
Output using GHC:
Inside ble: Just 234
Inside ble: Just 234
Main: 234
Output using GHC (with optimization)
Inside ble: Just 234
Main: 234
Output using GHCi:
Main: Inside ble: Just 234
Inside ble: Just 234
234
I read this:
http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns
I like the idea, want to use the extension. I however would like to make sure as to one thing: whether the view function is evaluated once for a single matching.
So let's say we have:
{-# LANGUAGE ViewPatterns #-}
...
f (view -> Nothing) = ...
f (view -> Just x) = ...
view :: a -> Maybe b
Now let's say I invoke f a
. Is view
invoked twice or just once for the given argument a
?
EDIT:
I tried to find out whether this is the case and wrote the following:
{-# 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)
Output using GHC:
Inside ble: Just 234
Inside ble: Just 234
Main: 234
Output using GHC (with optimization)
Inside ble: Just 234
Main: 234
Output using GHCi:
Main: Inside ble: Just 234
Inside ble: Just 234
234
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就一次:
作为对于您的代码片段,问题在于您没有进行优化编译;使用 ghc -O 和 ghc -O2 时,该行仅打印一次。当您在使用 GHC 时遇到与性能相关的问题时,这始终是首先要检查的事情:)
(顺便说一下,Debug.Trace 让您可以检查此类内容,而无需编写手动
unsafePerformIO
hack。)Just once:
As for your snippet, the problem is that you're not compiling with optimisation; with both
ghc -O
andghc -O2
, the line is only printed once. That's always the first thing to check when you have performance-related problems when using GHC :)(By the way, Debug.Trace lets you check these kinds of things without having to write manual
unsafePerformIO
hacks.)