Skip to content

Instantly share code, notes, and snippets.

@orend
Created August 9, 2012 15:33
Show Gist options
  • Save orend/3305160 to your computer and use it in GitHub Desktop.
Save orend/3305160 to your computer and use it in GitHub Desktop.
games with curry
>> %w(NYC TLV LSW).product(["airport"]).map{|x| x * ' '}
# equivalent to
>> %w(NYC TLV LSW).product(["airport"]).map{|x| x.join(' ')}
[
[0] "NYC airport",
[1] "TLV airport",
[2] "LSW airport"
]
# now using curry:
join = proc{|x, y| y.join(x)}.curry
# this is equivalent
join = proc{|x, y| y * x}.curry
join_space = join.(' ')
join_dash = join.('-')
>> join_space.(['a','b'])
"a b"
>> %w(NYC TLV LSW).zip(["airport"]*3).map(&join_space)
[
[0] "NYC airport",
[1] "TLV airport",
[2] "LSW airport"
]
>> %w(NYC TLV LSW).zip(["airport"]*3).map(&join_dash)
[
[0] "NYC-airport",
[1] "TLV-airport",
[2] "LSW-airport"
]
# can also replace zip with product
>> %w(NYC TLV LSW).product(["airport"]).map(&join_space)
# in case we wanted to join with different characters...
join = proc{|x, y| y * x}.curry
>> " -\n".chars.to_a.map{|x| join.(x)}.map{|join_char| %w(NYC TLV LSW).product(["airport"]).map(&join_char)}
[
[0] [
[0] "NYC airport",
[1] "TLV airport",
[2] "LSW airport"
],
[1] [
[0] "NYC-airport",
[1] "TLV-airport",
[2] "LSW-airport"
],
[2] [
[0] "NYC\nairport",
[1] "TLV\nairport",
[2] "LSW\nairport"
]
]
# or without the curry altogether...
>> " -\n".chars.to_a.product(%w(NYC TLV LSW).product(["airport"])).map{|x, y| y * x}
[
[0] "NYC airport",
[1] "TLV airport",
[2] "LSW airport",
[3] "NYC-airport",
[4] "TLV-airport",
[5] "LSW-airport",
[6] "NYC\nairport",
[7] "TLV\nairport",
[8] "LSW\nairport"
]
# we could also add each_slice(3).to_a to get it in the same form as the curry version
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment