Skip to content

Commit

Permalink
implement reduce builtin
Browse files Browse the repository at this point in the history
  • Loading branch information
jreidinger committed Feb 4, 2013
1 parent 41d86c0 commit a7ef787
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/ruby/ycp/builtins.rb
Expand Up @@ -320,14 +320,16 @@ def self.flatten value

module List
# Reduces a list to a single value.
def self.reduce
raise "Builtin list::reduce() is not implemented yet"
def self.reduce *params, &block
return nil if params.first.nil?
list = params.first
if params.size == 2
return nil if params[1].nil?
list = [list] + params[1]
end
return list.reduce &block
end

# Reduces a list to a single value.
def self.reduce
raise "Builtin list::reduce() is not implemented yet"
end

# Creates new list with swaped elemetns at offset i1 and i2.
def self.swap
Expand Down
35 changes: 35 additions & 0 deletions tests/ruby/builtins_test.rb
Expand Up @@ -515,4 +515,39 @@ def test_flatten
assert_equal result, YCP::Builtins.flatten(value)
end
end

def test_list_reduce_1param
list = [0,1,2,3,2,1,-5]
res = YCP::Builtins::List.reduce(list) do |x,y|
next x>y ? x : y
end

assert_equal 3, res

res = YCP::Builtins::List.reduce(list) do |x,y|
next x + y
end
assert_equal 4, res

assert_equal nil, YCP::Builtins::List.reduce([]) { |x,y| next x }
assert_equal nil, YCP::Builtins::List.reduce(nil) { |x,y| next x }
end

def test_list_reduce_2params
list = [0,1,2,3,2,1,-5]
res = YCP::Builtins::List.reduce(15,list) do |x,y|
next x>y ? x : y
end

assert_equal 15, res

res = YCP::Builtins::List.reduce(15,list) do |x,y|
next x + y
end

assert_equal 19, res

assert_equal 5, YCP::Builtins::List.reduce(5,[]) { |x,y| next x }
assert_equal nil, YCP::Builtins::List.reduce(nil,nil) { |x,y| next x }
end
end

0 comments on commit a7ef787

Please sign in to comment.