最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

haskell - Does the behavior of these two function differ in any way that justifies GHC compiling them down to different object c

programmeradmin0浏览0评论

Here's a module:

module Foo where

foo ws = let ws' = take 3 $ ws ++ repeat mempty
             x = ws' !! 0
             y = ws' !! 1
             z = ws' !! 2
         in [x, y, z]

and here's another one

module Foo where

foo ws = let (x:y:z:_) = take 3 $ ws ++ repeat mempty
         in [x, y, z]

Via ghc -O2 -c foo.hs, they compile down to 8072 and 5288 bytes respectively. Not sure which is best, nor how to test them, but I'd guess they can't behave identically, performance-wise, simply because they are different.

Do the two functions baheave any differently? If not, is the difference in the generated binary due to a missed optimization? Or what?

Here's a module:

module Foo where

foo ws = let ws' = take 3 $ ws ++ repeat mempty
             x = ws' !! 0
             y = ws' !! 1
             z = ws' !! 2
         in [x, y, z]

and here's another one

module Foo where

foo ws = let (x:y:z:_) = take 3 $ ws ++ repeat mempty
         in [x, y, z]

Via ghc -O2 -c foo.hs, they compile down to 8072 and 5288 bytes respectively. Not sure which is best, nor how to test them, but I'd guess they can't behave identically, performance-wise, simply because they are different.

Do the two functions baheave any differently? If not, is the difference in the generated binary due to a missed optimization? Or what?

Share Improve this question asked 2 days ago EnlicoEnlico 28.4k8 gold badges67 silver badges147 bronze badges 3
  • 2 They should have the same result, but the original source code gets there in quite different ways. One does a single 3-layer-deep pattern match. The other calls the recursive function !! 3 times, each of which would do some arithmetic and pattern matches (and each call has to start from the beginning of the list again each time). I'd expect the optimiser to inline and remove a lot of the overhead of the !! version, but I would have no expectation that they would end up compiled to identical bytes. – Ben Commented 2 days ago
  • GHC does not unroll recursive functions like !!. – Noughtmare Commented 2 days ago
  • Please, explain downvote. – Enlico Commented 2 days ago
Add a comment  | 

1 Answer 1

Reset to default 6

Here's one illustrative difference:

-- first module
> foo ("":undefined) !! 0
""
-- second module
> foo ("":undefined) !! 0
"***Exception: Prelude.undefined

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论