Re: RosettaCode
- Posted by jimcbrown (admin) Jan 26, 2011
- 1951 views
Yeah, I suppose not. With a little more work:
sequence compositions = {} function compose( sequence ids ) compositions = append( compositions, ids ) return length( compositions ) end function function call_composition( integer c, sequence x ) sequence comp = compositions[c] for i = length( comp ) to 1 by -1 do x = call_func( comp[i], x ) end for return x end function ... fg = compose( {f, g} ) -- edited to use {} call_composition( fg, {1} )
Matt
Still, this doesn't seem to be in the spirit of function composition. This compose function returns a "compose-id" which isn't compatible with routine-ids. With this you can't further compose two composed functions, although you've helpfully allowed any number of functions to be composed which should be equivalent. You still can't use a compose-id with anything expecting a routine-id.
But any singular routine-id can be turned into a compose-id.
We can extend this further so it allows composing with routine-ids, compose-ids, or any combination of compose-ids and routine-ids like so:
-- eat up the first element so compose-id -1 is never valid sequence compositions = {-1} function compose( sequence ids ) compositions = append( compositions, ids ) return -length( compositions ) end function function call_composition( integer c, sequence x ) sequence comp = compositions[-c] for i = length( comp ) to 1 by -1 do if comp[i] = -1 then -- error ? elsif comp[i] < 0 then x = call_composition( comp[i], x ) else x = call_func( comp[i], x ) end if end for return x end function ... fg = compose( {f, g} ) hfg = compose( {h, fg} ) call_composition( hfg, {1} )
It's not possible to turn the resulting compose-id into a routine-id (as far as I know). However, it is possible to create a c-func-id from a compose-id that can be used with c_func().