Search code examples
haskellcompiler-optimizationghcobject-files

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


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?


Solution

  • Here's one illustrative difference:

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