Skip to content

Instantly share code, notes, and snippets.

@k-tsj
Last active December 15, 2015 01:29
Show Gist options
  • Save k-tsj/5180187 to your computer and use it in GitHub Desktop.
Save k-tsj/5180187 to your computer and use it in GitHub Desktop.
ReplaceRepeated by Ruby
require 'pattern-match'
def replace_repeated(val, &block)
ret = match(val, &block)
if ret == val
ret
else
replace_repeated(ret, &block)
end
rescue PatternMatch::NoMatchingPatternError
val
end
replace_repeated([1, 2, 4, 4, 3, 3, 4, 0, 0]) do
with(_[*a, x, x, *b]) { [*a, x, *b] }
end #=> [1, 2, 4, 3, 4, 0]
# Mathematica (http://nyaruru.hatenablog.com/entry/20090311/p1)
# {1, 2, 4, 4, 3, 3, 4, 0, 0} //. {a___, x_, x_, b___} -> {a, x, b}
# (* 結果: {1, 2, 4, 3, 4, 0} *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment