Skip to content

Instantly share code, notes, and snippets.

@baweaver
Created May 24, 2019 00:30
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 baweaver/003d3c33b10ccb65588f223a1d1ee354 to your computer and use it in GitHub Desktop.
Save baweaver/003d3c33b10ccb65588f223a1d1ee354 to your computer and use it in GitHub Desktop.
class Proc
def contramap(&fn) self << fn end
end
adds = -> a, b { a + b }.curry
[1, 2, 3].map(&adds[2])
# => [3, 4, 5]
# What if the type on the left doesn't work with `adds`?
%w(1 2 3).map(&adds[2])
# TypeError: String can't be coerced into Integer
# ...well we can always transform them first:
%w(1 2 3).map(&:to_i).map(&adds[2])
# => [3, 4, 5]
# ...or apply a transformation to the input before it
# gets to the function with contramap:
%w(1 2 3).map(&adds[2].contramap(&:to_i))
# => [3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment