Skip to content

Instantly share code, notes, and snippets.

@404pnf
Created May 26, 2014 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 404pnf/19b4ef978be621144253 to your computer and use it in GitHub Desktop.
Save 404pnf/19b4ef978be621144253 to your computer and use it in GitHub Desktop.
ruby coll, ascending? and friends
# my proposal to functional-ruby gem
def in_order?(compare_fn)
-> col, &blk do
if blk
col.map {|e| blk[e] }
.each_cons(2)
.all? { |e1, e2| e1.send(compare_fn, e2) }
else
col.each_cons(2).all? { |e1, e2| e1.send(compare_fn, e2) }
end
end
end
# ==> nil
def ascending?(col, &blk)
in_order?(:<)[col, &blk]
end
# ==> nil
def descending?(col, &blk)
in_order?(:>)[col, &blk]
end
# ==> nil
def non_ascending?(col, &blk)
in_order?(:>=)[col, &blk]
end
# ==> nil
def non_descending?(col, &blk)
in_order?(:<=)[col, &blk]
end
# ==> nil
## simple tests
ascending? ["z", "mn", "abc"]
# ==> false
ascending? ["z", "mn", "abc"], &:length
# ==> true
ascending? [1,2,2,3]
# ==> false
ascending? ["z", "mn", "abc"], &:length
# ==> true
non_descending? [1,2,2,3]
# ==> true
descending? [4, 3, 2, 1]
# ==> true
non_ascending? [4, 3, 3, 2]
# ==> true
non_ascending? [4, 3, 3, 2]
# ==> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment