Apr 04 2009

foldl' better than foldl

Category: .geekAmit Bahree @ 12:13 pm

In Haskell the foldl' function defined in the module Data.List is better than foldl because that does not use a thunk. A thunked expression requires an internal stack. As an expression can grow infinitely large, the runtime imposes a limit on the size of this stack. As the simple example below shows that given a large enough input the stack will overflow.

Prelude> foldr (+) 0 [1..100]
5050
Prelude> foldl (+) 0 [1..100]
5050
Prelude> foldl (+) 0 [1..1000]
500500
Prelude> foldl (+) 0 [1..10000]
50005000
Prelude> foldl (+) 0 [1..100000]
5000050000
Prelude> foldl (+) 0 [1..1000000]
*** Exception: stack overflow

On the other hand, foldl' while similar to foldl does not build up on thunks and in real world programs is probably more useful.

Prelude> :module +Data.List
Prelude Data.List> foldl' (+) 0 [1..1000000]
500000500000
Prelude Data.List> foldl' (+) 0 [1..1000000]
500000500000
Prelude Data.List> foldl' (+) 0 [1..10000000]
50000005000000

Share
Similar posts to check out:
  • March 1, 2012 -- A great example of a MANET (0)
    I have been doing some research on MANETs and UAV’s and this TED talk is a great example of how a number of nodes operate in a MANET and implement some predetermined algorithm, which in this case is the Bond Theme Song. Worth watching. :)...
  • June 17, 2011 -- Kinect SDK (0)
    Microsoft recently release the Kinect SDK which allows you to implement a Natural User Interface and program against it! There is a lot of interest  around including claims on how Robotics will change to how you can integrate a light sensor. You can use Visual Studio (C++, C# and VB.NET supported) and get quite interesting results. Here are a series of links below which will help you get started. Download and install the Kinect SDK Download and install Quickstart Samples and Slide...
  • May 15, 2011 -- Tips on Buying a UPS? (0)
    After moving to Bangalore, it turns out that I would need to get one or more UPS's for the machines at home. The place we will be moving to in a few weeks does have power backup, but if/when there is a power cut it takes a few minutes for the generators to kick in and is not instantaneous as I was thinking. I have never bought a UPS until now and don't have any experience with it - what are the things that I need to consider? I will have the following equipment running which will need to be pow...

Tags:

Leave a Reply

*

Get Adobe Flash player