我是Haskell的新手,所以作为练习,我想实现一个类似于uncons返回列表中的元素init和last元素的函数.编写此函数的简便方法是
initLast :: [a] -> ([a], a)
initLast xs = (init xs, last xs)
Run Code Online (Sandbox Code Playgroud)
我是编写haskell程序的新手,但这对我来说似乎效率低下,因为它必须遍历列表两次.我提出了另一个我认为可能更好的功能,因为它不会多次遍历列表:
initLast' :: [a] -> ([a], a)
initLast' [x] = ([], x)
initLast' (x:xs) = let (xs', y) = initLast' xs
in (x:xs', y)
Run Code Online (Sandbox Code Playgroud)
但事实证明,当我在ghci中运行这些时,我发现第二个版本的速度慢了两倍,并且使用了大约3倍的内存!
ghci> :set +s
ghci> snd (initLast [1..1000000])
1000000
(0.28 secs, 122242144 bytes)
ghci> snd (initLast' [1..1000000])
1000000
(0.71 secs, 434147544 bytes)
Run Code Online (Sandbox Code Playgroud)
initLast吗?像往常一样:编译,如果你要进行性能测试.编译版本对两者使用大约相同的时间,但是67MB,initLast而只有6MB initLast'.
| 归档时间: |
|
| 查看次数: |
454 次 |
| 最近记录: |