Skip to content

Commit

Permalink
Extract INJECT from SUM and PRODUCT
Browse files Browse the repository at this point in the history
def inject(l, x, &block)
  if l.empty?
    x
  else
    inject(l[1..-1], block.call(x, l.first), &block)
  end
end
  • Loading branch information
tomstuart committed Oct 28, 2011
1 parent 0908d77 commit 5e10048
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/nothing.rb
Expand Up @@ -56,9 +56,11 @@ module Nothing
FIRST = -> l { LEFT[RIGHT[l]] } FIRST = -> l { LEFT[RIGHT[l]] }
REST = -> l { RIGHT[RIGHT[l]] } REST = -> l { RIGHT[RIGHT[l]] }


INJECT = Z[-> f { -> l { -> x { -> g { IF[IS_EMPTY[l]][x][-> _ { f[REST[l]][g[x][FIRST[l]]][g][_] }] } } } }]

RANGE = Z[-> f { -> m { -> n { IF[IS_LESS_OR_EQUAL[m][n]][-> _ { UNSHIFT[f[INCREMENT[m]][n]][m][_] }][EMPTY] } } }] RANGE = Z[-> f { -> m { -> n { IF[IS_LESS_OR_EQUAL[m][n]][-> _ { UNSHIFT[f[INCREMENT[m]][n]][m][_] }][EMPTY] } } }]
SUM = Z[-> f { -> l { IF[IS_EMPTY[l]][ZERO][-> _ { ADD[FIRST[l]][f[REST[l]]][_] }] } }] SUM = -> l { INJECT[l][ZERO][ADD] }
PRODUCT = Z[-> f { -> l { IF[IS_EMPTY[l]][ONE][-> _ { MULTIPLY[FIRST[l]][f[REST[l]]][_] }] } }] PRODUCT = -> l { INJECT[l][ONE][MULTIPLY] }
# CONCAT = # CONCAT =
# PUSH = # PUSH =
# REVERSE = # REVERSE =
Expand Down

2 comments on commit 5e10048

@cstrahan
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sweet. Are there any convenient combinators that could be used to write SUM and PRODUCT point-free?

@tomstuart
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, SUM and PRODUCT are already point-free when their arguments are taken in the conventional (vs the Ruby-friendly) order; on the pedant branch you can see how reordering INJECT's arguments allows you to eta-contract SUM and PRODUCT into point-free form.

Please sign in to comment.