Created
January 19, 2009 22:05
-
-
Save jamesarosen/49201 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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