Created
March 20, 2013 18:18
-
-
Save zerokarmaleft/5207106 to your computer and use it in GitHub Desktop.
Adventures in Functional Ruby, Part 1
This file contains 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
require 'java' | |
require 'jbundler' | |
require 'stunted' | |
%w{ PersistentArrayMap, PersistentHashMap, PersistentHashSet, PersistentList, | |
PersistentQueue, PersistentStructMap, PersistentTreeMap, PersistentTreeSet, | |
PersistentVector }.each do |data_structure| | |
java_import "clojure.lang.#{ data_structure }" | |
end | |
java_import 'clojure.lang.Numbers' | |
module CoreBridge | |
extend Stunted::Defn | |
defn :update_in, -> m, k, f do | |
m.assoc(k, f.call(m.get(k))) | |
end | |
end | |
sarah = PersistentHashMap.create(:name, "Sarah", :age, 25, :wears_glasses?, false) | |
# basic access | |
sarah.get(:age) | |
sarah[:age] | |
# sharing structure | |
becky = sarah. | |
assoc(:name, "Becky"). | |
assoc(:age, 28) | |
# chaining value updates | |
sarah = sarah. | |
assoc(:name, sarah[:name] + " Plain and Tall"). | |
assoc(:age, sarah[:age] + 1). | |
# functional value updates | |
update_in.(sarah, :age, -> age { age.next }) | |
module CoreBridge | |
defn :inc, -> x { Numbers.inc(x) } | |
defn :dec, -> x { Numbers.dec(x) } | |
end | |
update_in.(sarah, :age, inc) | |
# chaining functional value updates | |
class PersistentHashMap | |
include Stunted::Chainable | |
end | |
sarah. | |
assoc(:name, "Sarah Plain and Tall"). | |
pass_to (-> m { update_in.(m, :age, inc) }) | |
# using functional value updates in an Atom | |
a = Atom.new(sarah) | |
a.swap(-> m { update_in.(m, :age, inc) }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment