Haskell Zip循环列表,哪种方式有效?

Haskell Zip循环列表,哪种方式有效?,haskell,Haskell,例如,给定一个列表xs=[1..10],我想要的是: [(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10),(10,1)] 我的解决办法是 zip xs (tail xs ++ [head xs]) -- solution (1) 有人建议 zip xs (tail . cycle $ xs) -- solution (2) 但我不知道解决方案(2)是否更有效?或者两种解决方案是等效的?我的直觉是,它们将具有相

例如,给定一个列表
xs=[1..10]
,我想要的是:

[(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10),(10,1)]
我的解决办法是

zip xs (tail xs ++ [head xs])     -- solution (1)
有人建议

zip xs (tail . cycle $ xs)        -- solution (2)

但我不知道解决方案(2)是否更有效?或者两种解决方案是等效的?

我的直觉是,它们将具有相同的性能。如果你更喜欢实证答案而不是基于经验的答案,那么你应该为自己建立一个小的基准;Criteria或timeit软件包在这里很受欢迎。一定要编译并使用
-O2
,因为解释器的性能是出了名的不可靠,而GHC的优化器非常聪明。

出乎意料!解决方案(1)更快。我只是使用GHC运行时系统统计数据来测试它。测试用例是
[1..10^7]
,下面是代码:

解决方案(1):

解决方案(2):

编译选项:

ghc -O2 -rtsopts ZipCycleList1.hs
运行选项:

ZipCycleList1.exe +RTS -s
解决方案(1)的结果:

解决方案(2)的结果:


您是否尝试过为这两种方法计时并亲自查看?@AJFarmar我还没有学会如何为Haskell计划计时。我希望这些解决方案在性能上类似。您可以尝试使用
标准
库对它们进行基准测试@非常感谢。我以后再试试。
ghc -O2 -rtsopts ZipCycleList1.hs
ZipCycleList1.exe +RTS -s
   1,520,081,768 bytes allocated in the heap
         603,912 bytes copied during GC
          42,960 bytes maximum residency (2 sample(s))
          26,672 bytes maximum slop
               2 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0      1459 colls,     0 par    0.000s   0.004s     0.0000s    0.0006s
  Gen  1         2 colls,     0 par    0.000s   0.000s     0.0001s    0.0002s

  INIT    time    0.000s  (  0.001s elapsed)
  MUT     time    0.312s  (  0.305s elapsed)
  GC      time    0.000s  (  0.004s elapsed)
  EXIT    time    0.000s  (  0.000s elapsed)
  Total   time    0.312s  (  0.310s elapsed)

  %GC     time       0.0%  (1.3% elapsed)

  Alloc rate    4,872,025,717 bytes per MUT second

  Productivity 100.0% of total user, 98.5% of total elapsed
   1,520,081,832 bytes allocated in the heap
     992,426,304 bytes copied during GC
     250,935,040 bytes maximum residency (12 sample(s))
      42,981,632 bytes maximum slop
             569 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0      1449 colls,     0 par    0.296s   0.301s     0.0002s    0.0006s
  Gen  1        12 colls,     0 par    0.406s   0.622s     0.0518s    0.2284s

  INIT    time    0.000s  (  0.001s elapsed)
  MUT     time    0.328s  (  0.305s elapsed)
  GC      time    0.702s  (  0.922s elapsed)
  EXIT    time    0.000s  (  0.000s elapsed)
  Total   time    1.030s  (  1.228s elapsed)

  %GC     time      68.2%  (75.1% elapsed)

  Alloc rate    4,640,024,688 bytes per MUT second

  Productivity  31.8% of total user, 24.9% of total elapsed