Skip to content

Instantly share code, notes, and snippets.

@jamesarosen
Created January 19, 2009 22:05
Show Gist options
  • Save jamesarosen/49201 to your computer and use it in GitHub Desktop.
Save jamesarosen/49201 to your computer and use it in GitHub Desktop.
def merge_two_sorted_lists(a, b, &comparator)
comparator ||= lambda { |x,y| x <=> y }
linrec(
:cond => lambda { |pair| pair.first.empty? || pair.last.empty? },
:before => lambda do |pair|
preceding, following = case comparator.call(pair.first.first, pair.last.first)
when -1; [pair.first, pair.last]
when 0; [pair.first, pair.last]
when 1; [pair.last, pair.first]
end
[ preceding.first, [preceding[1..-1], following] ]
end,
:then => lambda do |pair|
if pair.first.empty? && pair.last.empty?; []
elsif pair.first.empty?; pair.last
else; pair.first
end
end,
:after => lambda { |trivial_part, recombined| [trivial_part] + recombined }
).call([a,b])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment