On Nov 17, 2007 8:53 AM, metaperl.j <[EMAIL PROTECTED]> wrote:
>
> Folding and unfolding are staples of functional programming. Insert
> approximates fold-left, but what approximates fold-right?
I think Insert is more similar to FoldR actually:
-/ 1 2 3 4 5 NB. foldl with "-" would return _15
3
But it isn't "real" FoldR since we cannot define initial value of
accumulator and, more importantly, "accumulator" in insert may not be
of an arbitrary type.
So real FoldR could be implemented, for example, as the following adverb:
foldr=: 1 : '[:>[:u&.>/((,<)~<"_1)'
it still uses Insert but operates on boxed values and concatenates
"initial value" to the tail of the list so it can run with more
general cases like this one:
'start' (":@[,]) foldr 1 2 3 4 5
12345start
of course it still works with simple "insert-solvable" examples:
0 + foldr 1 2 3 4 5
15
but in more "foldr way":
5 + foldr 1 2 3 4 5
20
FoldL may be implemented as:
foldl=: 1 : 'u~ foldr |.'
And it seems to work as expected:
0 - foldl 1 2 3 4 5
_15
'start' (,":) foldl 1 2 3 4 5
start12345
However, these are just examples of a custom implementation of the
"staples of functional programming" and nor really practical ones
since they are rather slow in comparison to Insert (due to the boxing,
I presume). My understanding the in J you are supposed to solve the
tasks involving folding i some different "J-way" since J is not really
functional language, but rather an array and functional-level language
so if you can post here the actual problem of yours that you are
trying to solve using these staples J community will probably be able
to come up with good J-way solution for it :)
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm