Skip to content

Instantly share code, notes, and snippets.

@martinos
Last active June 1, 2021 15:41
Show Gist options
  • Save martinos/fa63da9a4dbf59daf941c9662620481d to your computer and use it in GitHub Desktop.
Save martinos/fa63da9a4dbf59daf941c9662620481d to your computer and use it in GitHub Desktop.
Collections of lambda for processing data in a functionnal way
class Object
def _(fn)
fn.(self)
end
end
module DataFn
class DoubleEntries < StandardError
end
mattr_reader :count_by, :index_by, :h_fmap, :at, :attr, :attrs
@@count_by = ->fn, a {
a.reduce({}) do |memo, a|
key = fn.(a)
memo[key] ||= 0
memo[key] += 1
memo
end
}.curry
@@index_by = ->fn, a {
a.reduce({}) do |memo, a|
res = fn.(a)
if memo[res]
raise DoubleEntries
else
memo[res] = a
end
memo
end
}.curry
@@h_fmap = ->fn, a {
a.reduce({}) do |memo, (k, v)|
memo[k] ||= fn.(v)
memo
end
}.curry
@@at = ->key, a {
a.fetch(key)
}.curry
@@attr = ->method, a {
a.send(method)
}.curry
@@attrs = ->defn, a {
defn.inject({}) do |memo, (method, fn)|
memo[method] ||= fn.(attr.(method).(a))
memo
end
}.curry
end
include DataFn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment