Composition of functions without arguments: wrong number of arguments (given 1, expected 0)

71 Views Asked by At

Ie:

[1] pry(main)> @foo = rand
=> 0.46682153267547954
[6] pry(main)> multiply = -> () {@foo*2}
=> #<Proc:0x000000000121ac18@(pry):6 (lambda)>
[7] pry(main)> (multiply>>multiply).call
ArgumentError: wrong number of arguments (given 1, expected 0)
from (pry):6:in `block in __pry__'

Is there an elegant way around this? :-)

Before I get attacked by functional purists, this is not code golf even though I must admit I'm enjoying myself :P - I'm trying to see if there's a nice way to use function composition to ie disable event tracing in integration tests when using a callback-based infrastructure whose job it is to go around a web page, it's ONLY job is manipulating global state in that sense and do things like

    do_client_roundtrip around_client_return: method(:dont_trace_events) >> -> () {
      click_on "Continue"
      assert_invalid_session_page
    }

Ruby's "Everything returns something" bites here since none of the methods take any arguments and arity checks get upset by this. Adding arguments that do nothing just to satisfy my desire to play with >> / << is silly, so I'm wondering if there's something I should be doing different?

1

There are 1 best solutions below

0
On

Function composition is only defined for unary functions, the term doesn't even make sense for nullary functions. (Actually, a nullary function itself doesn't make sense, it is exactly the same thing as a constant.)

The definition of "function composition" is literally "passing the return value of one function as an argument to the next function". You simply cannot do function composition with nullary functions.