Search code examples
ruby

What is the Ruby equivalent of Haskell's scanl?


This question presents a version of Haskell's scanl in Python, but is there a Ruby version of this function?


Solution

  • Probably a nicer version could be written, but this is what I came up with:

    require 'spec_helper'
    
    class Array
      def scanl accumulator, &block
        results = [accumulator] + self
        results.each_with_index do |e, i|
          results[i] = block.call(accumulator, e)
          accumulator = results[i]
        end
        results
      end
    end
    
    describe "#scanl" do
      it 'is similar to foldl, but returns a list of successive reduced values from the left' do
        # example from http://learnyouahaskell.com/higher-order-functions
        expect([3, 5, 2, 1].scanl(0, &:+)).to eq([0,3,8,10,11])
      end
    end
    

    I considered changing scanl to take just a method name like :+ instead of a block to be more like reduce. Thoughts?